From ef742ccb2af1e7869ce181e49456108a27c9a6d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 22:08:33 -0800 Subject: [PATCH 01/63] i18n: custom toolbar command errors are translated in every complete-message catalog The status bar showed the errors of the toolbars made with New Toolbar in English in 15 of the complete-message languages (cs, el, es, fr, hu, ja, ka, ko, ru, vi, zh-hant, fi, tr, ca, nl), and the errors that window.toolbar.dock gives for a side that is not a string and for an order out of range in those and in hi and sv. The message scan already lists these templates; the untranslated-strings report only prints missing rows, so nothing failed. - Every complete-message catalog has a row for each error: a missing, empty, too long or taken toolbar name, a name or toolbar that is not a string, a missing new name, the 64-toolbar limit, and the dock command's side and order. The toolbar's name, the parameter key and the value given are kept as they are; the error the command returns stays English. Test: i18n::tests::custom_toolbar_command_errors_are_translated. --- crates/ui-egui/src/i18n/ca.tsv | 13 ++++ crates/ui-egui/src/i18n/cs.tsv | 13 ++++ crates/ui-egui/src/i18n/el.tsv | 13 ++++ crates/ui-egui/src/i18n/es.tsv | 13 ++++ crates/ui-egui/src/i18n/fi.tsv | 13 ++++ crates/ui-egui/src/i18n/fr.tsv | 13 ++++ crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 13 ++++ crates/ui-egui/src/i18n/ja.tsv | 13 ++++ crates/ui-egui/src/i18n/ka.tsv | 13 ++++ crates/ui-egui/src/i18n/ko.tsv | 13 ++++ crates/ui-egui/src/i18n/nl.tsv | 13 ++++ crates/ui-egui/src/i18n/ru.tsv | 13 ++++ crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tests.rs | 92 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 13 ++++ crates/ui-egui/src/i18n/vi.tsv | 13 ++++ crates/ui-egui/src/i18n/zh-hant.tsv | 13 ++++ docs/target-app-parity.md | 1 + 19 files changed, 292 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 373eb0b79d..e7a1c105fb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7389,6 +7389,19 @@ breakText Glyphs Glifs Not Aligned to Pixel Grid No alineat a la quadrícula de píxels @msg only paths and compound paths can be aligned to the pixel grid només els traçats i els traçats compostos es poden alinear a la quadrícula de píxels @msg side is left or right, not `{s}` side ha de ser left o right, no `{s}` +@msg side is left or right, not `{v}` side ha de ser left o right, no `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order ha de ser un nombre enter de 0 a {others}, no `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (el nom d’una barra d’eines) ha de ser una cadena +@msg no toolbar named `{name}` no hi ha cap barra d’eines anomenada `{name}` +@msg toolbar name can't be empty el nom de la barra d’eines no pot ser buit +@msg a toolbar name has at most {MAX_NAME} characters un nom de barra d’eines té com a màxim {MAX_NAME} caràcters +@msg there is already a toolbar named `{name}` ja hi ha una barra d’eines anomenada `{name}` +@msg there is already a toolbar named `{to}` ja hi ha una barra d’eines anomenada `{to}` +@msg a workspace keeps at most {MAX} toolbars un espai de treball conté com a màxim {MAX} barres d’eines +@msg name (a toolbar's name) must be a string name (el nom d’una barra d’eines) ha de ser una cadena +@msg name (a toolbar's name) is required cal name (el nom d’una barra d’eines) +@msg to (the new name) is required cal to (el nom nou) +@msg name must be a toolbar's name name ha de ser el nom d’una barra d’eines Ignore All Ignora-ho tot Add to Dictionary Afegeix al diccionari No Suggestions No hi ha suggeriments diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7178be3143..ef9f0764b0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7408,6 +7408,19 @@ breakText Glyphs Glyfy Not Aligned to Pixel Grid Nezarovnané na mřížku obrazových bodů @msg only paths and compound paths can be aligned to the pixel grid na mřížku obrazových bodů lze zarovnat jen cesty a složené cesty @msg side is left or right, not `{s}` side je left nebo right, ne `{s}` +@msg side is left or right, not `{v}` side je left nebo right, ne `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order je celé číslo od 0 do {others}, ne `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (název panelu nástrojů) musí být řetězec +@msg no toolbar named `{name}` panel nástrojů s názvem `{name}` neexistuje +@msg toolbar name can't be empty název panelu nástrojů nesmí být prázdný +@msg a toolbar name has at most {MAX_NAME} characters název panelu nástrojů má nejvýše {MAX_NAME} znaků +@msg there is already a toolbar named `{name}` panel nástrojů s názvem `{name}` už existuje +@msg there is already a toolbar named `{to}` panel nástrojů s názvem `{to}` už existuje +@msg a workspace keeps at most {MAX} toolbars pracovní prostor obsahuje nejvýše {MAX} panelů nástrojů +@msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec +@msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné +@msg to (the new name) is required to (nový název) je povinné +@msg name must be a toolbar's name name musí být název panelu nástrojů Ignore All Ignorovat vše Add to Dictionary Přidat do slovníku No Suggestions Žádné návrhy diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 62e3adc491..afd25adaab 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7361,6 +7361,19 @@ breakText Glyphs Γλύφοι Not Aligned to Pixel Grid Μη στοιχισμένα στο πλέγμα εικονοστοιχείων @msg only paths and compound paths can be aligned to the pixel grid μόνο διαδρομές και σύνθετες διαδρομές μπορούν να στοιχιστούν στο πλέγμα εικονοστοιχείων @msg side is left or right, not `{s}` το side είναι left ή right, όχι `{s}` +@msg side is left or right, not `{v}` το side είναι left ή right, όχι `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` το order είναι ακέραιος αριθμός από 0 έως {others}, όχι `{v}` +@msg toolbar (a toolbar's name) must be a string το toolbar (το όνομα μιας γραμμής εργαλείων) πρέπει να είναι συμβολοσειρά +@msg no toolbar named `{name}` δεν υπάρχει γραμμή εργαλείων με όνομα `{name}` +@msg toolbar name can't be empty το όνομα της γραμμής εργαλείων δεν μπορεί να είναι κενό +@msg a toolbar name has at most {MAX_NAME} characters ένα όνομα γραμμής εργαλείων έχει το πολύ {MAX_NAME} χαρακτήρες +@msg there is already a toolbar named `{name}` υπάρχει ήδη γραμμή εργαλείων με όνομα `{name}` +@msg there is already a toolbar named `{to}` υπάρχει ήδη γραμμή εργαλείων με όνομα `{to}` +@msg a workspace keeps at most {MAX} toolbars ένας χώρος εργασίας κρατά το πολύ {MAX} γραμμές εργαλείων +@msg name (a toolbar's name) must be a string το name (το όνομα μιας γραμμής εργαλείων) πρέπει να είναι συμβολοσειρά +@msg name (a toolbar's name) is required απαιτείται το name (το όνομα μιας γραμμής εργαλείων) +@msg to (the new name) is required απαιτείται το to (το νέο όνομα) +@msg name must be a toolbar's name το name πρέπει να είναι όνομα γραμμής εργαλείων Ignore All Παράβλεψη όλων Add to Dictionary Προσθήκη στο λεξικό No Suggestions Καμία πρόταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d1c6aa53af..b08fda6002 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7352,6 +7352,19 @@ breakText Glyphs Glifos Not Aligned to Pixel Grid No alineado con cuadrícula de píxeles @msg only paths and compound paths can be aligned to the pixel grid solo los trazados y los trazados compuestos se pueden alinear con la cuadrícula de píxeles @msg side is left or right, not `{s}` side es left o right, no `{s}` +@msg side is left or right, not `{v}` side es left o right, no `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order es un número entero de 0 a {others}, no `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (el nombre de una barra de herramientas) debe ser una cadena de texto +@msg no toolbar named `{name}` no hay ninguna barra de herramientas llamada `{name}` +@msg toolbar name can't be empty el nombre de la barra de herramientas no puede estar vacío +@msg a toolbar name has at most {MAX_NAME} characters el nombre de una barra de herramientas tiene como máximo {MAX_NAME} caracteres +@msg there is already a toolbar named `{name}` ya hay una barra de herramientas llamada `{name}` +@msg there is already a toolbar named `{to}` ya hay una barra de herramientas llamada `{to}` +@msg a workspace keeps at most {MAX} toolbars un espacio de trabajo guarda como máximo {MAX} barras de herramientas +@msg name (a toolbar's name) must be a string name (el nombre de una barra de herramientas) debe ser una cadena de texto +@msg name (a toolbar's name) is required Se requiere name (el nombre de una barra de herramientas) +@msg to (the new name) is required Se requiere to (el nuevo nombre) +@msg name must be a toolbar's name name debe ser el nombre de una barra de herramientas Ignore All Omitir todo Add to Dictionary Añadir al diccionario No Suggestions No hay sugerencias diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 45e47fd355..8b6189b4fe 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7443,6 +7443,19 @@ breakText Glyphs Merkit Not Aligned to Pixel Grid Ei tasattu pikseliruudukkoon @msg only paths and compound paths can be aligned to the pixel grid vain polut ja yhdistelmäpolut voi tasata pikseliruudukkoon @msg side is left or right, not `{s}` side on left tai right, ei `{s}` +@msg side is left or right, not `{v}` side on left tai right, ei `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order on kokonaisluku, vähintään 0 ja enintään {others}, ei `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar-arvon (työkalurivin nimi) on oltava merkkijono +@msg no toolbar named `{name}` ei työkaluriviä nimeltä `{name}` +@msg toolbar name can't be empty työkalurivin nimi ei voi olla tyhjä +@msg a toolbar name has at most {MAX_NAME} characters työkalurivin nimessä on enintään {MAX_NAME} merkkiä +@msg there is already a toolbar named `{name}` työkalurivi nimeltä `{name}` on jo olemassa +@msg there is already a toolbar named `{to}` työkalurivi nimeltä `{to}` on jo olemassa +@msg a workspace keeps at most {MAX} toolbars työtilassa on enintään {MAX} työkaluriviä +@msg name (a toolbar's name) must be a string name-arvon (työkalurivin nimi) on oltava merkkijono +@msg name (a toolbar's name) is required name (työkalurivin nimi) vaaditaan +@msg to (the new name) is required to (uusi nimi) vaaditaan +@msg name must be a toolbar's name name-arvon on oltava työkalurivin nimi Ignore All Ohita kaikki Add to Dictionary Lisää sanastoon No Suggestions Ei ehdotuksia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 057dce6872..ab1251d972 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7403,6 +7403,19 @@ breakText Glyphs Glyphes Not Aligned to Pixel Grid Non aligné sur la grille de pixels @msg only paths and compound paths can be aligned to the pixel grid seuls les tracés et les tracés transparents peuvent être alignés sur la grille de pixels @msg side is left or right, not `{s}` side vaut left ou right, pas `{s}` +@msg side is left or right, not `{v}` side vaut left ou right, pas `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order est un nombre entier de 0 à {others}, pas `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (le nom d’une barre d’outils) doit être une chaîne de caractères +@msg no toolbar named `{name}` aucune barre d’outils nommée `{name}` +@msg toolbar name can't be empty le nom de la barre d’outils ne peut pas être vide +@msg a toolbar name has at most {MAX_NAME} characters un nom de barre d’outils compte au plus {MAX_NAME} caractères +@msg there is already a toolbar named `{name}` il existe déjà une barre d’outils nommée `{name}` +@msg there is already a toolbar named `{to}` il existe déjà une barre d’outils nommée `{to}` +@msg a workspace keeps at most {MAX} toolbars un espace de travail contient au plus {MAX} barres d’outils +@msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne de caractères +@msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est requis +@msg to (the new name) is required to (le nouveau nom) est requis +@msg name must be a toolbar's name name doit être le nom d’une barre d’outils Ignore All Tout ignorer Add to Dictionary Ajouter au dictionnaire No Suggestions Aucune suggestion diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9d056e085a..75007a8a94 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8799,6 +8799,8 @@ theme Appearance अपीयरेंस @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` इंपोर्टर 1 से {MAX_EXTENSIONS} `extensions` घोषित करता है @msg an importer always gets an import's budget: leave `budget` out इंपोर्टर को हमेशा इंपोर्ट का बजट मिलता है: `budget` छोड़ दें @msg side is left or right, not `{s}` side left या right होना चाहिए, `{s}` नहीं +@msg side is left or right, not `{v}` side left या right होना चाहिए, `{v}` नहीं +@msg order is a whole number from 0 to {others}, not `{v}` order 0 से {others} तक की पूर्ण संख्या होनी चाहिए, `{v}` नहीं Ignore All सभी को अनदेखा करें Add to Dictionary शब्दकोश में जोड़ें No Suggestions कोई सुझाव नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c2f1a52cd9..3c10d8b8e5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7392,6 +7392,19 @@ breakText Glyphs Glifák Not Aligned to Pixel Grid Pixelrácshoz nem igazított @msg only paths and compound paths can be aligned to the pixel grid csak útvonalak és összetett útvonalak igazíthatók a pixelrácshoz @msg side is left or right, not `{s}` a side értéke left vagy right lehet, nem `{s}` +@msg side is left or right, not `{v}` a side értéke left vagy right lehet, nem `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` az order értéke 0 és {others} közötti egész szám lehet, nem `{v}` +@msg toolbar (a toolbar's name) must be a string a toolbar értéke (egy eszköztár neve) szöveg lehet +@msg no toolbar named `{name}` nincs ilyen nevű eszköztár: `{name}` +@msg toolbar name can't be empty az eszköztár neve nem lehet üres +@msg a toolbar name has at most {MAX_NAME} characters egy eszköztár neve legfeljebb {MAX_NAME} karakter lehet +@msg there is already a toolbar named `{name}` már van ilyen nevű eszköztár: `{name}` +@msg there is already a toolbar named `{to}` már van ilyen nevű eszköztár: `{to}` +@msg a workspace keeps at most {MAX} toolbars egy munkaterület legfeljebb {MAX} eszköztárat tartalmazhat +@msg name (a toolbar's name) must be a string a name értéke (egy eszköztár neve) szöveg lehet +@msg name (a toolbar's name) is required a name (egy eszköztár neve) kötelező +@msg to (the new name) is required a to (az új név) kötelező +@msg name must be a toolbar's name a name értéke egy eszköztár neve lehet Ignore All Az összes kihagyása Add to Dictionary Hozzáadás a szótárhoz No Suggestions Nincs javaslat diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 71de1ce91c..6b92f126d6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7104,6 +7104,19 @@ breakText Glyphs 字形 Not Aligned to Pixel Grid ピクセルグリッドに未整合 @msg only paths and compound paths can be aligned to the pixel grid ピクセルグリッドに整合できるのはパスと複合パスのみです @msg side is left or right, not `{s}` side は left または right です(`{s}` ではありません) +@msg side is left or right, not `{v}` side は left または right です(`{v}` ではありません) +@msg order is a whole number from 0 to {others}, not `{v}` order は 0 から {others} までの整数です(`{v}` ではありません) +@msg toolbar (a toolbar's name) must be a string toolbar(ツールバーの名前)は文字列にしてください +@msg no toolbar named `{name}` `{name}` という名前のツールバーが見つかりません +@msg toolbar name can't be empty ツールバー名を空にすることはできません +@msg a toolbar name has at most {MAX_NAME} characters ツールバー名は {MAX_NAME} 文字以内です +@msg there is already a toolbar named `{name}` `{name}` という名前のツールバーはすでにあります +@msg there is already a toolbar named `{to}` `{to}` という名前のツールバーはすでにあります +@msg a workspace keeps at most {MAX} toolbars ワークスペースに置けるツールバーは {MAX} 個までです +@msg name (a toolbar's name) must be a string name(ツールバーの名前)は文字列にしてください +@msg name (a toolbar's name) is required name(ツールバーの名前)を指定してください +@msg to (the new name) is required to(新しい名前)を指定してください +@msg name must be a toolbar's name name はツールバーの名前にしてください Ignore All すべて無視 Add to Dictionary 辞書に追加 No Suggestions 候補なし diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2cff51d94b..b611f62514 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7517,6 +7517,19 @@ font-script Japanese იაპონური Not Aligned to Pixel Grid პიქსელურ ბადეზე გაუსწორებელი @msg only paths and compound paths can be aligned to the pixel grid პიქსელურ ბადეზე მხოლოდ ტრაექტორიების და შედგენილი ტრაექტორიების გასწორებაა შესაძლებელი @msg side is left or right, not `{s}` side არის left ან right და არა `{s}` +@msg side is left or right, not `{v}` side არის left ან right და არა `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order არის მთელი რიცხვი 0-დან {others}-მდე და არა `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს +@msg no toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` არ არის +@msg toolbar name can't be empty ხელსაწყოთა ზოლის სახელი ცარიელი ვერ იქნება +@msg a toolbar name has at most {MAX_NAME} characters ხელსაწყოთა ზოლის სახელში მაქსიმუმ {MAX_NAME} სიმბოლოა +@msg there is already a toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` უკვე არსებობს +@msg there is already a toolbar named `{to}` ხელსაწყოთა ზოლი სახელით `{to}` უკვე არსებობს +@msg a workspace keeps at most {MAX} toolbars სამუშაო სივრცე ინახავს მაქსიმუმ {MAX} ხელსაწყოთა ზოლს +@msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს +@msg name (a toolbar's name) is required name (ხელსაწყოთა ზოლის სახელი) აუცილებელია +@msg to (the new name) is required to (ახალი სახელი) აუცილებელია +@msg name must be a toolbar's name name ხელსაწყოთა ზოლის სახელი უნდა იყოს Ignore All ყველას იგნორირება Add to Dictionary ლექსიკონში დამატება No Suggestions შემოთავაზებები არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4715a413f4..58f76a7228 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6999,6 +6999,19 @@ breakText Glyphs 글리프 Not Aligned to Pixel Grid 픽셀 격자에 정렬되지 않음 @msg only paths and compound paths can be aligned to the pixel grid 패스와 컴파운드 패스만 픽셀 격자에 정렬할 수 있습니다 @msg side is left or right, not `{s}` side는 left 또는 right입니다(`{s}` 아님) +@msg side is left or right, not `{v}` side는 left 또는 right입니다(`{v}` 아님) +@msg order is a whole number from 0 to {others}, not `{v}` order는 0부터 {others}까지의 정수입니다(`{v}` 아님) +@msg toolbar (a toolbar's name) must be a string toolbar(도구 막대 이름)은 문자열이어야 합니다 +@msg no toolbar named `{name}` `{name}` 도구 막대가 없습니다 +@msg toolbar name can't be empty 도구 막대 이름은 비워 둘 수 없습니다 +@msg a toolbar name has at most {MAX_NAME} characters 도구 막대 이름은 최대 {MAX_NAME}자입니다 +@msg there is already a toolbar named `{name}` `{name}` 도구 막대가 이미 있습니다 +@msg there is already a toolbar named `{to}` `{to}` 도구 막대가 이미 있습니다 +@msg a workspace keeps at most {MAX} toolbars 작업 영역에는 도구 막대를 최대 {MAX}개까지 둘 수 있습니다 +@msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 +@msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 +@msg to (the new name) is required to(새 이름)가 필요합니다 +@msg name must be a toolbar's name name은 도구 막대 이름이어야 합니다 Ignore All 모두 무시 Add to Dictionary 사전에 추가 No Suggestions 제안 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 94957fb782..5991c9e12f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7445,6 +7445,19 @@ breakText Glyphs Glyphs Align New Objects to Pixel Grid Nieuwe objecten uitlijnen op pixelraster Not Aligned to Pixel Grid Niet uitgelijnd op pixelraster @msg side is left or right, not `{s}` side is left of right, niet `{s}` +@msg side is left or right, not `{v}` side is left of right, niet `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order is een geheel getal van 0 tot en met {others}, niet `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (de naam van een werkbalk) moet een string zijn +@msg no toolbar named `{name}` geen werkbalk met de naam `{name}` +@msg toolbar name can't be empty de naam van een werkbalk mag niet leeg zijn +@msg a toolbar name has at most {MAX_NAME} characters een werkbalknaam heeft hoogstens {MAX_NAME} tekens +@msg there is already a toolbar named `{name}` er is al een werkbalk met de naam `{name}` +@msg there is already a toolbar named `{to}` er is al een werkbalk met de naam `{to}` +@msg a workspace keeps at most {MAX} toolbars een werkruimte bevat hoogstens {MAX} werkbalken +@msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn +@msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist +@msg to (the new name) is required to (de nieuwe naam) is vereist +@msg name must be a toolbar's name name moet de naam van een werkbalk zijn Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: # Script Console diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8dc8336089..9f6f7d71a2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7497,6 +7497,19 @@ shape Open Открытый Not Aligned to Pixel Grid Не выровненные по пиксельной сетке @msg only paths and compound paths can be aligned to the pixel grid по пиксельной сетке можно выровнять только контуры и составные контуры @msg side is left or right, not `{s}` side — это left или right, а не `{s}` +@msg side is left or right, not `{v}` side принимает значение left или right, а не `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order должен быть целым числом от 0 до {others}, а не `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (имя панели инструментов) должен быть строкой +@msg no toolbar named `{name}` нет панели инструментов с именем `{name}` +@msg toolbar name can't be empty имя панели инструментов не может быть пустым +@msg a toolbar name has at most {MAX_NAME} characters имя панели инструментов содержит не более {MAX_NAME} символов +@msg there is already a toolbar named `{name}` панель инструментов с именем `{name}` уже есть +@msg there is already a toolbar named `{to}` панель инструментов с именем `{to}` уже есть +@msg a workspace keeps at most {MAX} toolbars рабочая среда хранит не более {MAX} панелей инструментов +@msg name (a toolbar's name) must be a string name (имя панели инструментов) должен быть строкой +@msg name (a toolbar's name) is required Необходимо указать name (имя панели инструментов) +@msg to (the new name) is required Необходимо указать to (новое имя) +@msg name must be a toolbar's name name должен быть именем панели инструментов Ignore All Пропустить все Add to Dictionary Добавить в словарь No Suggestions Нет вариантов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cfb9d9734b..355a08e109 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8846,6 +8846,8 @@ digits Hindi Hindi Not Aligned to Pixel Grid Inte justerade mot pixelrutnät @msg only paths and compound paths can be aligned to the pixel grid bara banor och sammansatta banor kan justeras mot pixelrutnätet @msg side is left or right, not `{s}` side är left eller right, inte `{s}` +@msg side is left or right, not `{v}` side är left eller right, inte `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order är ett heltal från 0 till {others}, inte `{v}` Ignore All Ignorera alla Add to Dictionary Lägg till i ordlistan No Suggestions Inga förslag diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 705fc68db2..5391732421 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3201,6 +3201,98 @@ fn wrongly_shaped_plugin_commands_errors_are_translated() { } } +/// The errors of the custom toolbar commands (Window › Toolbars, New Toolbar and Manage Toolbars, +/// `window.toolbar.dock` and `window.toolbar.float`) have an `@msg` row in every complete-message +/// catalog, and the status bar shows each one in the interface language with the toolbar's name, +/// the key and the values given kept; the error the command returns stays English. +#[test] +fn custom_toolbar_command_errors_are_translated() { + use serde_json::json; + let scanned = message_literals(); + let templates = [ + "toolbar (a toolbar's name) must be a string", + "no toolbar named `{name}`", + "toolbar name can't be empty", + "a toolbar name has at most {MAX_NAME} characters", + "there is already a toolbar named `{name}`", + "there is already a toolbar named `{to}`", + "a workspace keeps at most {MAX} toolbars", + "name (a toolbar's name) must be a string", + "name (a toolbar's name) is required", + "to (the new name) is required", + "name must be a toolbar's name", + "side is left or right, not `{s}`", + "side is left or right, not `{v}`", + "order is a whole number from 0 to {others}, not `{v}`", + "no dialog open", + "`{key}` must be true or false", + "x and y must both be numbers", + ]; + for template in templates { + assert!(scanned.contains(template), "the scan lists {template}"); + } + let mut missing = vec![]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: std::collections::BTreeSet<&str> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, _)| src.as_str()).collect(); + missing.extend(templates.iter().filter(|t| !rows.contains(*t)).map(|t| format!("{code}: {t}"))); + } + assert!(missing.is_empty(), "{} toolbar errors have no @msg row:\n{}", missing.len(), missing.join("\n")); + + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + for name in ["Mine", "Pens"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + app.run("window.toolbar.dock", json!({"name": "Pens", "side": "left"})).unwrap(); + let cases = [ + ("window.toolbar.new", json!({"name": 5}), "name (a toolbar's name) must be a string", vec![]), + ("window.toolbar.new", json!({"name": " "}), "toolbar name can't be empty", vec![]), + ("window.toolbar.new", json!({"name": "x".repeat(201)}), "a toolbar name has at most 200 characters", vec!["200"]), + ("window.toolbar.new", json!({"name": "Mine"}), "there is already a toolbar named `Mine`", vec!["`Mine`"]), + ("window.toolbar.rename", json!({"name": "Mine", "to": "Pens"}), "there is already a toolbar named `Pens`", vec!["`Pens`"]), + ("window.toolbar.rename", json!({"name": "Mine"}), "to (the new name) is required", vec![]), + ("window.toolbar.custom", json!({}), "name (a toolbar's name) is required", vec![]), + ("window.toolbar.custom", json!({"name": "Nope"}), "no toolbar named `Nope`", vec!["`Nope`"]), + ("window.toolbar.custom", json!({"name": "Mine", "show": "yes"}), "`show` must be true or false", vec!["`show`"]), + ("window.toolbar.duplicate", json!({"name": 3}), "name must be a toolbar's name", vec![]), + ("toolbar.addTool", json!({"tool": "pen", "toolbar": 5}), "toolbar (a toolbar's name) must be a string", vec![]), + ("window.toolbar.dock", json!({"name": "Mine", "side": "up"}), "side is left or right, not `up`", vec!["`up`"]), + ("window.toolbar.dock", json!({"name": "Mine", "side": 3}), "side is left or right, not `3`", vec!["`3`"]), + ( + "window.toolbar.dock", + json!({"name": "Mine", "side": "left", "order": 9}), + "order is a whole number from 0 to 1, not `9`", + vec!["1", "`9`"], + ), + ("window.toolbar.float", json!({"name": "Mine", "x": "a", "y": 1}), "x and y must both be numbers", vec![]), + ]; + let mut errors: Vec<(String, Vec<&str>)> = vec![]; + for (id, params, want, kept) in cases { + let e = app.run(id, params.clone()).unwrap_err(); + assert_eq!(e, want, "{id} {params}"); + errors.push((e, kept)); + } + // New Toolbar's OK with no dialog open, and a workspace that holds as many toolbars as it keeps. + errors.push((crate::custom_toolbars::confirm(&mut app).unwrap_err(), vec![])); + for i in app.ui.custom_toolbars.len()..crate::custom_toolbars::MAX { + app.run("window.toolbar.new", json!({ "name": format!("T{i}") })).unwrap(); + } + for (id, params) in [("window.toolbar.new", json!({"name": "Extra"})), ("window.toolbar.duplicate", json!({"name": "Mine"}))] { + let e = app.run(id, params).unwrap_err(); + assert_eq!(e, "a workspace keeps at most 64 toolbars", "{id}"); + errors.push((e, vec!["64"])); + } + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, kept) in &errors { + let shown = message(lang, e); + assert_ne!(shown, *e, "{code}: shown in English"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {e} -> {shown}"); + } + } +} + /// The warnings of an Image Trace with keepColors, which the status bar shows and the scan above /// doesn't read, are translated in each language of [`COMPLETE_MESSAGES`], with the colors kept. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2b3e843ba3..5aa7a15dc7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7364,6 +7364,19 @@ breakText Glyphs Glifler Not Aligned to Pixel Grid Piksel Izgarasına Hizalanmamış @msg only paths and compound paths can be aligned to the pixel grid piksel ızgarasına yalnızca yollar ve bileşik yollar hizalanabilir @msg side is left or right, not `{s}` side left veya right olmalıdır, `{s}` değil +@msg side is left or right, not `{v}` side left veya right olmalıdır, `{v}` değil +@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayı olmalıdır, `{v}` değil +@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır +@msg no toolbar named `{name}` `{name}` adlı araç çubuğu yok +@msg toolbar name can't be empty araç çubuğu adı boş olamaz +@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter olabilir +@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var +@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var +@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar +@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır +@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gerekli +@msg to (the new name) is required to (yeni ad) gerekli +@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır Ignore All Tümünü Yoksay Add to Dictionary Sözlüğe Ekle No Suggestions Öneri Yok diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d8469bce53..ebc22ed778 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7019,6 +7019,19 @@ breakText Glyphs Glyph Not Aligned to Pixel Grid Chưa căn theo lưới pixel @msg only paths and compound paths can be aligned to the pixel grid chỉ đường dẫn và đường dẫn phức mới căn theo lưới pixel được @msg side is left or right, not `{s}` side là left hoặc right, không phải `{s}` +@msg side is left or right, not `{v}` side là left hoặc right, không phải `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order là số nguyên từ 0 đến {others}, không phải `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (tên một thanh công cụ) phải là chuỗi +@msg no toolbar named `{name}` không có thanh công cụ tên `{name}` +@msg toolbar name can't be empty tên thanh công cụ không được để trống +@msg a toolbar name has at most {MAX_NAME} characters tên thanh công cụ có tối đa {MAX_NAME} ký tự +@msg there is already a toolbar named `{name}` đã có thanh công cụ tên `{name}` +@msg there is already a toolbar named `{to}` đã có thanh công cụ tên `{to}` +@msg a workspace keeps at most {MAX} toolbars một không gian làm việc giữ tối đa {MAX} thanh công cụ +@msg name (a toolbar's name) must be a string name (tên một thanh công cụ) phải là chuỗi +@msg name (a toolbar's name) is required name (tên một thanh công cụ) là bắt buộc +@msg to (the new name) is required to (tên mới) là bắt buộc +@msg name must be a toolbar's name name phải là tên của một thanh công cụ Ignore All Bỏ qua tất cả Add to Dictionary Thêm vào từ điển No Suggestions Không có gợi ý diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a0d987fe69..901c15e451 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7057,6 +7057,19 @@ breakText Glyphs 字符 Not Aligned to Pixel Grid 未對齊像素格點 @msg only paths and compound paths can be aligned to the pixel grid 只有路徑和複合路徑可以對齊像素格點 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` +@msg side is left or right, not `{v}` side 應為 left 或 right,而不是 `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order 應為 0 到 {others} 之間的整數,而不是 `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (工具列的名稱) 必須是字串 +@msg no toolbar named `{name}` 沒有名為 `{name}` 的工具列 +@msg toolbar name can't be empty 工具列名稱不能是空的 +@msg a toolbar name has at most {MAX_NAME} characters 工具列名稱最多 {MAX_NAME} 個字元 +@msg there is already a toolbar named `{name}` 已經有名為 `{name}` 的工具列 +@msg there is already a toolbar named `{to}` 已經有名為 `{to}` 的工具列 +@msg a workspace keeps at most {MAX} toolbars 一個工作區最多保留 {MAX} 個工具列 +@msg name (a toolbar's name) must be a string name (工具列的名稱) 必須是字串 +@msg name (a toolbar's name) is required 需要 name (工具列的名稱) +@msg to (the new name) is required 需要 to (新名稱) +@msg name must be a toolbar's name name 必須是工具列的名稱 Edit Custom Dictionary 編輯自訂字典 Entry: 項目: # Script Console diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 296bd84b2b..4d684612e3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -882,6 +882,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). + - The status bar shows the errors of the toolbars made with New Toolbar (a missing, empty, too long or taken name, the 64-toolbar limit, a `side` or `order` that `window.toolbar.dock` does not take, and New Toolbar's dialog and Manage Toolbars) in every language that translates every message, with the toolbar's name, the parameter key and the value given kept as they are; the error the command returns stays English (`custom_toolbar_command_errors_are_translated`). - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. From c7e6b5426e0e3b8025a7dbe6383c26dc6c901f87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:26:52 -0800 Subject: [PATCH 02/63] i18n: drop toolbar rows that main already has Main added the custom toolbar messages to the cs, fr, ko, nl and zh-hant catalogs, so the branch's copies of the same 13 rows in each are removed. --- crates/ui-egui/src/i18n/cs.tsv | 13 ------------- crates/ui-egui/src/i18n/fr.tsv | 13 ------------- crates/ui-egui/src/i18n/ko.tsv | 13 ------------- crates/ui-egui/src/i18n/nl.tsv | 13 ------------- crates/ui-egui/src/i18n/zh-hant.tsv | 13 ------------- 5 files changed, 65 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f0e677e551..d95879fc03 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7417,19 +7417,6 @@ breakText Glyphs Glyfy Not Aligned to Pixel Grid Nezarovnané na mřížku obrazových bodů @msg only paths and compound paths can be aligned to the pixel grid na mřížku obrazových bodů lze zarovnat jen cesty a složené cesty @msg side is left or right, not `{s}` side je left nebo right, ne `{s}` -@msg side is left or right, not `{v}` side je left nebo right, ne `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order je celé číslo od 0 do {others}, ne `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (název panelu nástrojů) musí být řetězec -@msg no toolbar named `{name}` panel nástrojů s názvem `{name}` neexistuje -@msg toolbar name can't be empty název panelu nástrojů nesmí být prázdný -@msg a toolbar name has at most {MAX_NAME} characters název panelu nástrojů má nejvýše {MAX_NAME} znaků -@msg there is already a toolbar named `{name}` panel nástrojů s názvem `{name}` už existuje -@msg there is already a toolbar named `{to}` panel nástrojů s názvem `{to}` už existuje -@msg a workspace keeps at most {MAX} toolbars pracovní prostor obsahuje nejvýše {MAX} panelů nástrojů -@msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec -@msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné -@msg to (the new name) is required to (nový název) je povinné -@msg name must be a toolbar's name name musí být název panelu nástrojů Ignore All Ignorovat vše Add to Dictionary Přidat do slovníku No Suggestions Žádné návrhy diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 579cc008b1..3dfd5ad5d9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7412,19 +7412,6 @@ breakText Glyphs Glyphes Not Aligned to Pixel Grid Non aligné sur la grille de pixels @msg only paths and compound paths can be aligned to the pixel grid seuls les tracés et les tracés transparents peuvent être alignés sur la grille de pixels @msg side is left or right, not `{s}` side vaut left ou right, pas `{s}` -@msg side is left or right, not `{v}` side vaut left ou right, pas `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order est un nombre entier de 0 à {others}, pas `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (le nom d’une barre d’outils) doit être une chaîne de caractères -@msg no toolbar named `{name}` aucune barre d’outils nommée `{name}` -@msg toolbar name can't be empty le nom de la barre d’outils ne peut pas être vide -@msg a toolbar name has at most {MAX_NAME} characters un nom de barre d’outils compte au plus {MAX_NAME} caractères -@msg there is already a toolbar named `{name}` il existe déjà une barre d’outils nommée `{name}` -@msg there is already a toolbar named `{to}` il existe déjà une barre d’outils nommée `{to}` -@msg a workspace keeps at most {MAX} toolbars un espace de travail contient au plus {MAX} barres d’outils -@msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne de caractères -@msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est requis -@msg to (the new name) is required to (le nouveau nom) est requis -@msg name must be a toolbar's name name doit être le nom d’une barre d’outils Ignore All Tout ignorer Add to Dictionary Ajouter au dictionnaire No Suggestions Aucune suggestion diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a694df6890..8af8d3f53d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7008,19 +7008,6 @@ breakText Glyphs 글리프 Not Aligned to Pixel Grid 픽셀 격자에 정렬되지 않음 @msg only paths and compound paths can be aligned to the pixel grid 패스와 컴파운드 패스만 픽셀 격자에 정렬할 수 있습니다 @msg side is left or right, not `{s}` side는 left 또는 right입니다(`{s}` 아님) -@msg side is left or right, not `{v}` side는 left 또는 right입니다(`{v}` 아님) -@msg order is a whole number from 0 to {others}, not `{v}` order는 0부터 {others}까지의 정수입니다(`{v}` 아님) -@msg toolbar (a toolbar's name) must be a string toolbar(도구 막대 이름)은 문자열이어야 합니다 -@msg no toolbar named `{name}` `{name}` 도구 막대가 없습니다 -@msg toolbar name can't be empty 도구 막대 이름은 비워 둘 수 없습니다 -@msg a toolbar name has at most {MAX_NAME} characters 도구 막대 이름은 최대 {MAX_NAME}자입니다 -@msg there is already a toolbar named `{name}` `{name}` 도구 막대가 이미 있습니다 -@msg there is already a toolbar named `{to}` `{to}` 도구 막대가 이미 있습니다 -@msg a workspace keeps at most {MAX} toolbars 작업 영역에는 도구 막대를 최대 {MAX}개까지 둘 수 있습니다 -@msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 -@msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 -@msg to (the new name) is required to(새 이름)가 필요합니다 -@msg name must be a toolbar's name name은 도구 막대 이름이어야 합니다 Ignore All 모두 무시 Add to Dictionary 사전에 추가 No Suggestions 제안 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d83896807d..c8b777d01b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9272,19 +9272,6 @@ breakText Glyphs Glyphs Align New Objects to Pixel Grid Nieuwe objecten uitlijnen op pixelraster Not Aligned to Pixel Grid Niet uitgelijnd op pixelraster @msg side is left or right, not `{s}` side is left of right, niet `{s}` -@msg side is left or right, not `{v}` side is left of right, niet `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order is een geheel getal van 0 tot en met {others}, niet `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (de naam van een werkbalk) moet een string zijn -@msg no toolbar named `{name}` geen werkbalk met de naam `{name}` -@msg toolbar name can't be empty de naam van een werkbalk mag niet leeg zijn -@msg a toolbar name has at most {MAX_NAME} characters een werkbalknaam heeft hoogstens {MAX_NAME} tekens -@msg there is already a toolbar named `{name}` er is al een werkbalk met de naam `{name}` -@msg there is already a toolbar named `{to}` er is al een werkbalk met de naam `{to}` -@msg a workspace keeps at most {MAX} toolbars een werkruimte bevat hoogstens {MAX} werkbalken -@msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn -@msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist -@msg to (the new name) is required to (de nieuwe naam) is vereist -@msg name must be a toolbar's name name moet de naam van een werkbalk zijn Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: # Script Console diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3a35d60161..264a252f18 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7067,19 +7067,6 @@ breakText Glyphs 字符 Not Aligned to Pixel Grid 未對齊像素格點 @msg only paths and compound paths can be aligned to the pixel grid 只有路徑和複合路徑可以對齊像素格點 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` -@msg side is left or right, not `{v}` side 應為 left 或 right,而不是 `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order 應為 0 到 {others} 之間的整數,而不是 `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (工具列的名稱) 必須是字串 -@msg no toolbar named `{name}` 沒有名為 `{name}` 的工具列 -@msg toolbar name can't be empty 工具列名稱不能是空的 -@msg a toolbar name has at most {MAX_NAME} characters 工具列名稱最多 {MAX_NAME} 個字元 -@msg there is already a toolbar named `{name}` 已經有名為 `{name}` 的工具列 -@msg there is already a toolbar named `{to}` 已經有名為 `{to}` 的工具列 -@msg a workspace keeps at most {MAX} toolbars 一個工作區最多保留 {MAX} 個工具列 -@msg name (a toolbar's name) must be a string name (工具列的名稱) 必須是字串 -@msg name (a toolbar's name) is required 需要 name (工具列的名稱) -@msg to (the new name) is required 需要 to (新名稱) -@msg name must be a toolbar's name name 必須是工具列的名稱 Edit Custom Dictionary 編輯自訂字典 Entry: 項目: # Script Console From d50b48bcd2d20b808fde9af59ae4a93dc575f1c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:06:45 -0800 Subject: [PATCH 03/63] Graphs: Expand Appearance skips a design's art instead of restoring it Expand Appearance of a graph or series group no longer expands the art of a graph design in a series and then puts the earlier copy back. It leaves that art out while expanding the rest. - The art's own raster effects are no longer rendered into images that stay in the document after the art is put back. - A geometry effect, color adjustment or raster effect of the graph or series group around the art now applies to the art with the rest of the group. Before, the earlier copy put back did not have it. - In Safe Mode, a plug-in effect in the art is checked when an effect of a group around it, inside the selection, draws the art with that group. docs/mcp.md states that an effect of the group reaches its design art. --- crates/engine/src/cmd/effectcmd.rs | 65 ++++++++++++++----------- crates/engine/src/cmd/graph/tests.rs | 49 +++++++++++++++++++ crates/engine/tests/plugin_safe_mode.rs | 46 +++++++++++++++++ docs/mcp.md | 6 +-- 4 files changed, 135 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 9d86449bb9..8229ed55c3 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -927,15 +927,16 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { /// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that /// id): those made from its own fills and strokes, or with `all` every member. The other members /// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are -/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a -/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they -/// have before that. Returns what each of those other members' expansions lists, by the member's -/// new id. +/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids +/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the +/// pieces with the ids they have before that. Returns what each of those other members' expansions +/// lists, by the member's new id. fn expand_pieces( d: &mut Document, m: &mut Node, all: bool, brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], stroke_art: effects::StrokeArt, ) -> std::collections::HashMap> { let id = m.id; @@ -951,7 +952,7 @@ fn expand_pieces( if all || c.id == id { effects::expand_art(d, c, stroke_art); } else if has_seeded(c) && repeats_an_id(c, &seen) { - listed = Some(expand_in_place(d, c, brushes)); + listed = Some(expand_in_place(d, c, brushes, skip)); } fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default()); if let Some(listed) = listed { @@ -1007,9 +1008,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { type Listed = (NodeId, usize); /// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`. -fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec { +fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec { let mut listed = vec![]; - if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) { + if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) { *c = e; } listed @@ -1033,9 +1034,15 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections: /// geometry effects are baked, raster effects become an embedded image, and the object keeps its /// transparency. pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) { + expand_node_except(d, id, brushes, &[], out); +} + +/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry +/// effect of a group or layer around one still reshapes it with the rest of its members. +fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) { let Some(n) = d.node(id).cloned() else { return }; let mut listed = vec![]; - let m = expanded_node(d, n, brushes, &mut listed); + let m = expanded_node(d, n, brushes, skip, &mut listed); out.extend(listed.into_iter().map(|(id, _)| id)); if let Some(mut m) = m { // Art made from type takes its emoji's pixels into the document. @@ -1048,10 +1055,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when /// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk -/// of the expanded `n`, `n`'s first when its own does. -fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) -> Option { +/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded. +fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) -> Option { let id = n.id; - if !expandable(&n) { + if skip.contains(&id) || !expandable(&n) { return None; } // Colour adjustments: the colours inside become the adjusted ones (an embedded image a @@ -1088,7 +1095,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br for (i, c) in m.children_mut().into_iter().flatten().enumerate() { let c = Arc::make_mut(c); if i == 0 { - expanded = expand_in_place(d, c, brushes); + expanded = expand_in_place(d, c, brushes, skip); fresh_ids_listed(d, c, &mut seen, &mut expanded); } else { effects::fresh_ids(d, c, &mut seen); @@ -1129,7 +1136,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); + members = expand_pieces(d, &mut m, false, brushes, skip, &mut stroke_art); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) @@ -1150,7 +1157,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; expand_nested_instances(d, &mut m, 1, &mut budget); - expand_pieces(d, &mut m, true, brushes, &mut stroke_art); + expand_pieces(d, &mut m, true, brushes, skip, &mut stroke_art); m }) }; @@ -1184,7 +1191,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br match members.remove(&c.id) { Some(listed) => out.extend(listed), None => { - if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, out) { *c = Arc::new(e); changed = true; } @@ -1229,9 +1236,19 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // geometry it hasn't changed. if vectorcraft_plugins::safe_mode::active() { // A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a - // series. + // series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it + // with that group. let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots); - let designs = super::appearance::design_art_in(&d, &roots); + let designs: Vec = super::appearance::design_art_in(&d, &roots) + .into_iter() + .filter(|art| { + !d.ancestry(*art).is_some_and(|up| { + let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len()); + up.get(from..up.len().saturating_sub(1)) + .is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(|g| g.appearance.effects.iter().any(|e| e.visible))) + }) + }) + .collect(); if !designs.is_empty() { let view = d.to_mut(); for id in designs { @@ -1249,7 +1266,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); let ids = s.edit("Expand Appearance", |d, _| { let before = d.clone(); - // The art of graph designs in the graphs and series among the roots stays as the graph draws it. + // The art of graph designs in the graphs and series among the roots is not expanded: the graph draws it again + // from the design. let designs = super::appearance::design_art_in(d, &roots); // A dimension selected with the art it measures keeps its own lines and label: it is out // of the document while the art expands. @@ -1260,16 +1278,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let mut out = vec![]; let threaded = super::threads::frames(d); for id in &roots { - expand_node(d, *id, &brushes, &mut out); - } - for id in &designs { - if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) { - *slot = was.clone(); - } - } - if !designs.is_empty() { - // A mark that expands into a group stays listed: only what lies in the restored art is left out. - out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a)))); + expand_node_except(d, *id, &brushes, &designs, &mut out); } super::dimension::put_back(d, lifted); // A dimension whose source was replaced stays where it was, no longer linked. diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 7b7f9974af..c5801b85be 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -586,6 +586,55 @@ fn expand_appearance_leaves_a_graph_designs_art() { assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty())); } +/// `effect` with `params`, as `effect.apply` gives it to an object. +fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect { + let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap(); + s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone() +} + +/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an +/// image of that effect to the document. +#[test] +fn expand_appearance_lists_no_design_art_and_rasterizes_none() { + let (mut s, id, copy, _, mark) = design_art(); + let shadow = an_effect(&mut s, "stylize.dropShadow", json!({})); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap(); + let copy_was = look(&s, copy); + let images = |s: &Session| s.doc().unwrap().doc.images.len(); + let before = images(&s); + s.execute("select.set", &json!({"ids": [mark.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let per_mark = images(&s) - before; + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(expanded["ids"], json!([mark.0])); + assert_eq!(look(&s, copy), copy_was); + assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image"); +} + +/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the +/// marks. +#[test] +fn expand_appearance_moves_design_art_with_its_series_groups_effect() { + let (mut s, id, copy, _, _) = design_art(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let group = series(&n, 0).id; + let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50})); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift); + let left = |s: &Session| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0 + }; + let was = left(&s); + assert_eq!(series(&n, 0).children().unwrap()[0].id, copy); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s)); +} + /// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by /// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design. #[test] diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 2c5fc1c307..8829c056b3 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -463,6 +463,52 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { s.execute("effect.expandAppearance", &json!({})).unwrap(); } +/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only +/// when an effect of the series group draws that art with the group. +#[test] +fn expand_appearance_in_safe_mode_checks_design_art_its_series_group_draws() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.graph", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.graph", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Plug"})).unwrap(); + s.execute("graph.column", &json!({"id": graph, "seriesIndexes": [0], "design": "Plug"})).unwrap(); + let series = |s: &Session, index: u32| { + let d = &s.doc().unwrap().doc; + let n = d.node(vectorcraft_engine::doc::NodeId(graph)).unwrap(); + n.children().unwrap().iter().find(|c| c.extras().series_index == Some(index)).unwrap().id + }; + let (art_series, other_series) = (series(&s, 0), series(&s, 1)); + // A mark in the other series has an effect to expand. + let mark = s.doc().unwrap().doc.node(other_series).unwrap().children().unwrap()[0].id; + s.execute("effect.apply", &json!({"effect": "distort.puckerBloat", "ids": [mark.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + safe_mode::set_active(None); + s.execute("edit.undo", &json!({})).unwrap(); + // With a Transform effect on the art's series group, expanding the group draws the art's plug-in effect. + let shift = { + let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "ids": [t], "params": {"moveH": 5}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.effects[0].clone() + }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(art_series).unwrap().appearance.effects.push(shift); + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); +} + /// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop /// Expand Appearance: the dimension is left as it is, its effect included, and the art expands. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e186501302..5bc56a95c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -817,9 +817,9 @@ inside a series group other than a path directly in it, a legend swatch's includ reached through `target: "contents"`. These commands leave that art out, edit the other objects they are given, and are an error when all their objects are design art: the `appearance.*` commands listed above, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, move or remove an effect, -`effect.expandAppearance` (which also leaves the art inside a selected graph or series group as it was, unless an -effect of that group turns the whole group into other art, and is disabled when only design art is selected or -given), `threeD.mapGraphic`, +`effect.expandAppearance` (which also leaves the art inside a selected graph or series group as it was, except that +an effect of that group which reshapes or replaces the whole group bakes into that art too, and is disabled when only +design art is selected or given), `threeD.mapGraphic`, `graphicStyle.apply`, `graphicStyle.addFromLibrary` with `apply`, `graphicStyle.breakLink`, `transparency.set`, the `paint.freeform.*` commands that edit points and lines, and `appearance.copyFrom` as the target. `appearance.transfer` with design art as its `target`, or as its `source` without `copy`, is an error. From 37cb0e3f5b42bdb43fa73da6831152ec4d87ab78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:55:17 -0800 Subject: [PATCH 04/63] i18n: drop the ja and hu toolbar error rows that main now carries main added the same 13 custom-toolbar `@msg` rows to ja.tsv and hu.tsv, so the branch's copies made `bundled_catalogs_are_consistent` fail with a duplicate key. Keep main's rows and remove the branch's. --- crates/ui-egui/src/i18n/hu.tsv | 13 ------------- crates/ui-egui/src/i18n/ja.tsv | 13 ------------- 2 files changed, 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1f1bb6cd89..bea893c5ff 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7404,19 +7404,6 @@ breakText Glyphs Glifák Not Aligned to Pixel Grid Pixelrácshoz nem igazított @msg only paths and compound paths can be aligned to the pixel grid csak útvonalak és összetett útvonalak igazíthatók a pixelrácshoz @msg side is left or right, not `{s}` a side értéke left vagy right lehet, nem `{s}` -@msg side is left or right, not `{v}` a side értéke left vagy right lehet, nem `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` az order értéke 0 és {others} közötti egész szám lehet, nem `{v}` -@msg toolbar (a toolbar's name) must be a string a toolbar értéke (egy eszköztár neve) szöveg lehet -@msg no toolbar named `{name}` nincs ilyen nevű eszköztár: `{name}` -@msg toolbar name can't be empty az eszköztár neve nem lehet üres -@msg a toolbar name has at most {MAX_NAME} characters egy eszköztár neve legfeljebb {MAX_NAME} karakter lehet -@msg there is already a toolbar named `{name}` már van ilyen nevű eszköztár: `{name}` -@msg there is already a toolbar named `{to}` már van ilyen nevű eszköztár: `{to}` -@msg a workspace keeps at most {MAX} toolbars egy munkaterület legfeljebb {MAX} eszköztárat tartalmazhat -@msg name (a toolbar's name) must be a string a name értéke (egy eszköztár neve) szöveg lehet -@msg name (a toolbar's name) is required a name (egy eszköztár neve) kötelező -@msg to (the new name) is required a to (az új név) kötelező -@msg name must be a toolbar's name a name értéke egy eszköztár neve lehet Ignore All Az összes kihagyása Add to Dictionary Hozzáadás a szótárhoz No Suggestions Nincs javaslat diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6c4b6ff9c4..6b59f5a370 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8920,19 +8920,6 @@ breakText Glyphs 字形 Not Aligned to Pixel Grid ピクセルグリッドに未整合 @msg only paths and compound paths can be aligned to the pixel grid ピクセルグリッドに整合できるのはパスと複合パスのみです @msg side is left or right, not `{s}` side は left または right です(`{s}` ではありません) -@msg side is left or right, not `{v}` side は left または right です(`{v}` ではありません) -@msg order is a whole number from 0 to {others}, not `{v}` order は 0 から {others} までの整数です(`{v}` ではありません) -@msg toolbar (a toolbar's name) must be a string toolbar(ツールバーの名前)は文字列にしてください -@msg no toolbar named `{name}` `{name}` という名前のツールバーが見つかりません -@msg toolbar name can't be empty ツールバー名を空にすることはできません -@msg a toolbar name has at most {MAX_NAME} characters ツールバー名は {MAX_NAME} 文字以内です -@msg there is already a toolbar named `{name}` `{name}` という名前のツールバーはすでにあります -@msg there is already a toolbar named `{to}` `{to}` という名前のツールバーはすでにあります -@msg a workspace keeps at most {MAX} toolbars ワークスペースに置けるツールバーは {MAX} 個までです -@msg name (a toolbar's name) must be a string name(ツールバーの名前)は文字列にしてください -@msg name (a toolbar's name) is required name(ツールバーの名前)を指定してください -@msg to (the new name) is required to(新しい名前)を指定してください -@msg name must be a toolbar's name name はツールバーの名前にしてください Ignore All すべて無視 Add to Dictionary 辞書に追加 No Suggestions 候補なし From 4b9d56154068f203b5474bb814571deb29b12972 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:37:24 -0800 Subject: [PATCH 05/63] Graphs: paint edits of a design's art alone leave the new-art paint as it is With only the art of a graph design in a series given or selected, paint.editGradient still set the default fill or stroke and the remembered paint, paint.swap swapped the default fill and stroke, paint.default reset them, and paint.invert and paint.complement with an item remembered the art's color. Each now returns without changing anything. An empty selection still edits the defaults as before. --- crates/engine/src/cmd/gradient.rs | 4 +++ crates/engine/src/cmd/graph/tests.rs | 37 ++++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 20 +++++++++++++-- docs/mcp.md | 4 ++- 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 291aa1b59f..c6534c6367 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -579,6 +579,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { }; let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; + // Only design art was given or selected: nothing changes, the defaults and the remembered paint included. + if selected && ids.is_empty() { + return Ok(json!({"ids": []})); + } let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| { if index.is_none() diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index f8cf0af4ab..6a2e3cd3ad 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -507,6 +507,43 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() { assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient"); } +/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the +/// paint for new art and the remembered colors as they are. +#[test] +fn paint_edits_of_design_art_alone_leave_the_defaults() { + let (mut s, _, _, art, _) = design_art(); + let fill = top_row(&s, art, true); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors)); + let commands = [ + ("paint.editGradient", json!({"kind": "linear"})), + ("paint.editGradient", json!({"kind": "radial", "stroke": true})), + ("paint.swap", json!({})), + ("paint.default", json!({})), + ("paint.invert", json!({"item": fill, "stroke": false})), + ("paint.complement", json!({"item": fill, "stroke": false})), + ]; + for (cmd, p) in &commands { + let was = defaults(&s); + let mut q = p.clone(); + q["ids"] = json!([art.0]); + s.execute(cmd, &q).unwrap(); + assert_eq!(defaults(&s), was, "{cmd}, given"); + // Selecting the art makes the defaults take its paint. + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let was = defaults(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(defaults(&s), was, "{cmd}, selected"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + // With nothing selected, the swap still swaps the defaults. + let was = defaults(&s); + s.execute("paint.swap", &json!({})).unwrap(); + assert_ne!(defaults(&s), was); +} + /// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects /// sets only theirs. #[test] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index a37c407041..73c92ac113 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -966,7 +966,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option } fn swap(s: &mut Session, p: &Value) -> Result { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?); + let targets = paint_targets(s, p)?; + let given = !targets.is_empty(); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // Only design art was given or selected: nothing changes, the defaults included. + if given && ids.is_empty() { + return ok(); + } if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -1001,7 +1007,13 @@ fn swap(s: &mut Session, p: &Value) -> Result { } fn default_paint(s: &mut Session, p: &Value) -> Result { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?); + let targets = paint_targets(s, p)?; + let given = !targets.is_empty(); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // Only design art was given or selected: nothing changes, the defaults included. + if given && ids.is_empty() { + return ok(); + } if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -1073,6 +1085,10 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( let (r, shown_item) = match item { ItemTarget::Item { index, .. } => { let ids = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); + // Only design art was given or selected: nothing changes, the remembered colors included. + if ids.is_empty() { + return Ok(json!({ "changed": 0 })); + } let mut changed = 0; edit_items(s, &ids, item, cmd, label, !stroke, |n, i| { let paint = diff --git a/docs/mcp.md b/docs/mcp.md index 3ec471eb84..a60a9dea96 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -832,7 +832,9 @@ design art is selected or given), `threeD.mapGraphic`, `appearance.transfer` with design art as its `target`, or as its `source` without `copy`, is an error. `paint.setFill`, `paint.setStroke`, `paint.swap`, `paint.default`, `paint.invert` and `paint.complement` with an `item`, `stroke.set`, `stroke.weightUp`, `stroke.weightDown`, `stroke.setAdvanced`, `paint.editGradient`, -`paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When the first selected object is design art, the commands +`paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When all their objects are design art, +`paint.editGradient`, `paint.swap`, `paint.default`, and `paint.invert` and `paint.complement` with an `item` also leave +the paint for new art and the remembered colors as they are. When the first selected object is design art, the commands do not use the Appearance panel's active row. To change the art, edit the design with `graph.design`. The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke From 7e2246f6d44ccce605175cb9e448dcddc577182d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:26:01 -0800 Subject: [PATCH 06/63] i18n: Danish rows for the custom toolbar errors --- crates/ui-egui/src/i18n/da.tsv | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..5c3dd27d34 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7457,6 +7457,19 @@ breakText Glyphs Glyffer Align New Objects to Pixel Grid Juster nye objekter efter pixelgitter Not Aligned to Pixel Grid Ikke justeret efter pixelgitter @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` +@msg side is left or right, not `{v}` side er left eller right, ikke `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order er et heltal fra 0 til {others}, ikke `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (navnet på en værktøjslinje) skal være en streng +@msg no toolbar named `{name}` ingen værktøjslinje med navnet `{name}` +@msg toolbar name can't be empty navnet på en værktøjslinje må ikke være tomt +@msg a toolbar name has at most {MAX_NAME} characters navnet på en værktøjslinje har højst {MAX_NAME} tegn +@msg there is already a toolbar named `{name}` der findes allerede en værktøjslinje med navnet `{name}` +@msg there is already a toolbar named `{to}` der findes allerede en værktøjslinje med navnet `{to}` +@msg a workspace keeps at most {MAX} toolbars et arbejdsområde gemmer højst {MAX} værktøjslinjer +@msg name (a toolbar's name) must be a string name (navnet på en værktøjslinje) skal være en streng +@msg name (a toolbar's name) is required name (navnet på en værktøjslinje) er påkrævet +@msg to (the new name) is required to (det nye navn) er påkrævet +@msg name must be a toolbar's name name skal være navnet på en værktøjslinje Edit Custom Dictionary Redigér egen ordliste Entry: Opslag: # Script Console From f6ecf49a1926eda8b5802baef60e15dea119aca6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:07:37 -0800 Subject: [PATCH 07/63] Graphs: Invert, Complement and stroke weights of a design's art alone leave the new-art defaults With only the art of a graph design in a series given or selected, paint.invert and paint.complement without an item recolored that art and remembered its new color, and stroke.set with a weight set the stroke weight for new art. Invert and Complement now leave the art out, as they do with an item, also when they are given the whole graph or a series group, and with only design art they change nothing. stroke.set with only design art leaves the weight for new art as it is. An item the art has no row of that kind for is still an error in the commands that leave the art out, as on any other object, and so is a bad aligned or target param. Without stroke, paint.editGradient and paint.setGradientGeom read the kind of an item named on design art alone from that art's row. --- crates/engine/src/cmd/appearance.rs | 19 +++++++++++- crates/engine/src/cmd/gradient.rs | 4 +-- crates/engine/src/cmd/graph/tests.rs | 46 +++++++++++++++++++++++++++- crates/engine/src/cmd/overprint.rs | 17 +++++++--- crates/engine/src/cmd/paint.rs | 19 ++++++++++-- crates/engine/src/cmd/stroke.rs | 13 +++++--- docs/mcp.md | 8 ++--- 7 files changed, 106 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 38668bd814..95b5936af5 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -451,6 +451,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec) -> Vec ids } +/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's +/// art has no row of that kind for is still an error of `cmd`, as on any other object. +pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec, item: ItemTarget, fill: bool, cmd: &str) -> Result> { + let d = &s.doc()?.doc; + for (id, it) in ids.iter().zip(item.per_target(s, &ids)) { + if let (Some(it), Some(n)) = (it, d.node(*id)) + && super::graph::is_design_art(d, *id) + { + it.resolve(&n.appearance, fill, cmd)?; + } + } + Ok(drop_design_art(d, ids)) +} + /// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that /// [`super::graph::is_design_art`] accepts. pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec { @@ -633,7 +647,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo } let ItemTarget::Item { index, .. } = item else { return Ok(default) }; let d = &s.doc()?.doc; - let ids = drop_design_art(d, appearance_targets(s, p)?); + let all = appearance_targets(s, p)?; + // The art of a graph design is left out, unless it is all there is: the item is then a row of that art. + let kept = drop_design_art(d, all.clone()); + let ids = if kept.is_empty() { all } else { kept }; Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index c6534c6367..89b8daa342 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then // not one for new art. let selected = !ids.is_empty(); - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { None => None, @@ -768,7 +768,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); } - let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets); + let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?; let model = super::paint::new_color_model(s, &Value::Null); edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| { if index.is_none() diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 6a2e3cd3ad..a34ac0f724 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() { /// it, and edit the other objects they are given. #[test] fn paint_commands_leave_a_graph_designs_art_out() { - let (mut s, _, copy, art, mark) = design_art(); + let (mut s, graph, copy, art, mark) = design_art(); let fill = top_row(&s, art, true); let commands = [ ("stroke.set", json!({"weight": 5})), @@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() { ("paint.swap", json!({})), ("paint.default", json!({})), ("paint.invert", json!({"item": fill, "stroke": false})), + ("paint.invert", json!({})), ]; let (copy_was, art_was) = (look(&s, copy), look(&s, art)); for (cmd, p) in &commands { @@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() { s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); s.execute("stroke.set", &json!({"weight": 5})).unwrap(); assert_eq!(look(&s, art), art_was); + // Given the whole graph, Invert recolors the marks and leaves the art. + let mark_was = look(&s, mark); + s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap(); + assert_eq!(look(&s, art), art_was); + assert_ne!(look(&s, mark), mark_was); // A freeform gradient point is refused on the art alone. refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]})); } @@ -524,6 +530,10 @@ fn paint_edits_of_design_art_alone_leave_the_defaults() { ("paint.default", json!({})), ("paint.invert", json!({"item": fill, "stroke": false})), ("paint.complement", json!({"item": fill, "stroke": false})), + ("paint.invert", json!({})), + ("paint.complement", json!({"stroke": true})), + ("stroke.set", json!({"weight": 7})), + ("stroke.weightUp", json!({})), ]; for (cmd, p) in &commands { let was = defaults(&s); @@ -538,6 +548,40 @@ fn paint_edits_of_design_art_alone_leave_the_defaults() { assert_eq!(defaults(&s), was, "{cmd}, selected"); s.execute("select.set", &json!({"ids": []})).unwrap(); } + // A bad `item`, `aligned` or `target` is still an error with only design art given. + for bad in [ + json!({"ids": [art.0], "item": "top"}), + json!({"ids": [art.0], "item": fill, "aligned": "yes"}), + json!({"ids": [art.0], "item": fill, "target": "nowhere"}), + ] { + assert!(s.execute("paint.invert", &bad).is_err(), "{bad}"); + } + // So is an `item` the art has no row for, in each command that leaves the art out. + let steps = s.doc().unwrap().history.undo.len(); + for (cmd, p) in [ + ("paint.invert", json!({})), + ("stroke.set", json!({"weight": 2})), + ("stroke.weightUp", json!({})), + ("stroke.setAdvanced", json!({"swapArrows": true})), + ("paint.editGradient", json!({"kind": "linear"})), + ("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})), + ("object.setOverprint", json!({"fill": true})), + ] { + let mut q = p.clone(); + q["ids"] = json!([art.0]); + q["item"] = json!(99); + assert!(s.execute(cmd, &q).is_err(), "{cmd}"); + } + // The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing. + let stroke_row = top_row(&s, art, false); + for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] { + let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" }; + let mut q = p.clone(); + q["ids"] = json!([art.0]); + q["item"] = json!(stroke_row); + s.execute(cmd, &q).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps); // With nothing selected, the swap still swaps the defaults. let was = defaults(&s); s.execute("paint.swap", &json!({})).unwrap(); diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 781a8242ce..cbc639f1ce 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -126,14 +126,21 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result> { .collect() } -/// Each kind's item target and objects: (fill?, item, ids). -fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator) -> Result)>> { +/// Each kind's item target and objects: (fill?, item, ids). With `edit`, an explicit item that the graph design art left +/// out has no row of that kind for is an error, as when the edit resolves it on the other objects. +fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator, edit: bool) -> Result)>> { let item = item_target(s, p, cmd)?; kinds .into_iter() .map(|fill| { let it = item.of_kind(s, fill); - Ok((fill, it, super::appearance::drop_design_art(&s.doc()?.doc, it.targets(s, p)?))) + let ids = it.targets(s, p)?; + let ids = if edit { + super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? + } else { + super::appearance::drop_design_art(&s.doc()?.doc, ids) + }; + Ok((fill, it, ids)) }) .collect() } @@ -159,7 +166,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec), bool); /// `object.setOverprint` aims. pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result> { let kinds = kinds(p, cmd, keys)?; - Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))?.into_iter().zip(kinds.iter().map(|k| k.1)).collect()) + Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect()) } /// Apply `jobs` to `d`, adding the objects changed to `changed`. @@ -198,7 +205,7 @@ fn attributes(s: &Session, p: &Value) -> Result { let d = &s.doc()?.doc; let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() }; super::attributes::fill_info(d, &mut info); - for (fill, item, ids) in aims(s, p, C, [true, false])? { + for (fill, item, ids) in aims(s, p, C, [true, false], false)? { let mut all = ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten(); let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first)); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 73c92ac113..d42ecaf1df 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1082,9 +1082,17 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( return Ok(json!({ "changed": changed as usize })); } let item = item_target(s, p, cmd)?.of_kind(s, !stroke); + // Read before the check below, so that a bad param (such as `target`, or an explicit `item` the art has no row + // for) is still an error. + let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?; + let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + // Only design art was given or selected: nothing changes, the defaults and remembered colors included. + if ids.is_empty() { + return Ok(json!({ "changed": 0 })); + } let (r, shown_item) = match item { ItemTarget::Item { index, .. } => { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); + let ids = targets; // Only design art was given or selected: nothing changes, the remembered colors included. if ids.is_empty() { return Ok(json!({ "changed": 0 })); @@ -1099,12 +1107,17 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( (json!({ "changed": changed }), Some(index)) } // The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles. + // Design art inside a given graph or series group is left out too. ItemTarget::Top => { - let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::>()}); + let leaves = targets; + if leaves.is_empty() { + return Ok(json!({ "changed": 0 })); + } + let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": leaves.iter().map(|i| i.0).collect::>()}); (super::colorcmds::recolor(s, &q, cmd, label, f)?, None) } }; - let shown_ids = if shown_item.is_some() { ids } else { leaf_targets(s, &ids)? }; + let shown_ids = if shown_item.is_some() { ids } else { super::appearance::drop_design_art(&s.doc()?.doc, leaf_targets(s, &ids)?) }; if let Some(shown) = shown_ids.first().and_then(|id| s.doc().ok()?.doc.node(*id).map(|n| proxy_paint(n, stroke, shown_item))) { s.remember_paint(&shown); } diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index f268eee9c8..1e9c290ed6 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { let item = item_target(s, p, C)?.of_kind(s, false); let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? }; let new_art = no_targets(&ids, p); + let given = !ids.is_empty(); // The art of a graph design in a series keeps the design's stroke. - ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; + // With only design art, the weight for new art stays as it is too. + let only_design_art = given && ids.is_empty(); if item == ItemTarget::Top { // Images and symbol instances take no stroke from the panel. let d = &s.doc()?.doc; @@ -327,7 +330,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { })?; // Commit the new-art template only after the complete request is validated // and the selected artwork edit has succeeded. - if let Some(w) = change.weight { + if let Some(w) = change.weight + && !only_design_art + { s.paint.stroke_width = w; } if new_art && let Some(st) = s.new_art_stroke_mut() { @@ -370,7 +375,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { } return Ok(json!({"objects": 0})); } - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?; let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" }; edit_items(s, &ids, item, c, label, false, |n, index| { if index.is_none() @@ -515,7 +520,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { let ids = item.targets(s, p)?; let new_art = no_targets(&ids, p); // The art of a graph design in a series keeps the design's stroke. - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; let arrows_and_profile = |st: &mut StrokeLayer| { if let Some(sc) = scale { st.arrow_scale = sc; diff --git a/docs/mcp.md b/docs/mcp.md index a60a9dea96..49569acfc1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -830,11 +830,11 @@ design art is selected or given), `threeD.mapGraphic`, `graphicStyle.apply`, `graphicStyle.addFromLibrary` with `apply`, `graphicStyle.breakLink`, `transparency.set`, the `paint.freeform.*` commands that edit points and lines, and `appearance.copyFrom` as the target. `appearance.transfer` with design art as its `target`, or as its `source` without `copy`, is an error. -`paint.setFill`, `paint.setStroke`, `paint.swap`, `paint.default`, `paint.invert` and `paint.complement` with an -`item`, `stroke.set`, `stroke.weightUp`, `stroke.weightDown`, `stroke.setAdvanced`, `paint.editGradient`, +`paint.setFill`, `paint.setStroke`, `paint.swap`, `paint.default`, `paint.invert`, `paint.complement`, +`stroke.set`, `stroke.weightUp`, `stroke.weightDown`, `stroke.setAdvanced`, `paint.editGradient`, `paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When all their objects are design art, -`paint.editGradient`, `paint.swap`, `paint.default`, and `paint.invert` and `paint.complement` with an `item` also leave -the paint for new art and the remembered colors as they are. When the first selected object is design art, the commands +`paint.editGradient`, `paint.swap`, `paint.default`, `paint.invert`, `paint.complement` and `stroke.set` also leave +the paint and stroke weight for new art and the remembered colors as they are. When the first selected object is design art, the commands do not use the Appearance panel's active row. To change the art, edit the design with `graph.design`. The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke From 119ce7942bd14467b9e870a43d3e69b82daa7482 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:42:17 -0800 Subject: [PATCH 08/63] PDF export: an image whose colors can't be converted is left out with a warning When the Output settings convert colors, an image whose pixels can't be decoded or written in the destination's colors was written as it was, in its own colors: a CMYK image with more pixels than CMYK inks are read for, or a color image the writer could embed but the decoder could not read. In PDF/X-1a that could also write a color space the standard forbids. Such an image is now left out with the warning "an image couldn't be converted to the Output destination and is missing from the picture". Gray images, whose pixels are not converted, and files that convert no colors keep the image as before. An image that can't be written at all still gets the warning that it couldn't be decoded. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/pdf/src/export/exporter.rs | 4 +++ crates/pdf/src/export/images.rs | 17 ++++++++-- crates/pdf/src/images.rs | 48 +++++++++++++++++++---------- crates/pdf/src/tests/cmykimages.rs | 32 +++++++++++++++++++ crates/pdf/src/tests/compression.rs | 30 ++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 1 + 8 files changed, 117 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index da6da069e9..affd39c416 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and one whose pixels can't be converted is left out with a warning; printer's marks are not converted), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index f102e0a0ab..a116f8bc2a 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -18,6 +18,10 @@ pub(super) const MAX_PATTERN_DEPTH: u32 = 4; /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning for an image left out because its colors can't be converted as the Output +/// settings ask, although it could be written in its own colors. +pub(super) const UNCONVERTED: &str = "an image couldn't be converted to the Output destination and is missing from the picture"; + /// The warning for an image whose placement cannot be written. pub(super) const UNWRITABLE_IMAGE: &str = "an image couldn't be written and is missing from the picture"; diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index af686e1857..19d4314553 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -1,4 +1,4 @@ -use super::exporter::{UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; +use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect, Size, Surface, cmyk, krilla}; use krilla::color::device_n::{Colorant, DeviceNSpace, Process}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; @@ -124,7 +124,9 @@ impl Exporter<'_> { /// settings say ([`crate::images::recode`], [`crate::images::recode_cmyk`] for CMYK images); /// cached by key (and size when images are resampled). With `interpolate` (and the export's /// own setting), viewers may smooth it. `None`, with [`UNDECODED`] among the warnings, for an - /// image that is missing, can't be decoded or is in [`Self::left_out`]. + /// image that is missing, can't be decoded or is in [`Self::left_out`]; `None`, with + /// [`UNCONVERTED`], for one whose colors the Output settings convert but that can only be + /// written in its own ([`crate::images::Recoded::unconverted`]). fn load_image(&mut self, im: &vectorcraft_doc::ImageObject, size: (f64, f64), interpolate: bool) -> Option { let key = im.key.as_str(); let c = self.compression; @@ -139,6 +141,7 @@ impl Exporter<'_> { let doc = self.doc; let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); + let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { @@ -153,9 +156,17 @@ impl Exporter<'_> { if let Some(w) = r.warning { self.warn(w); } + if r.unconverted { + // The source image would be written in its own colors: it is left out, with a + // warning that names the conversion when it could have been written. + unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some(); + return None; + } r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)) }); - if img.is_none() { + if unconverted { + self.warn(UNCONVERTED); + } else if img.is_none() { self.warn(UNDECODED); } self.images.insert(cache, img.clone()); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 5204e4f396..90eca71f67 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -306,6 +306,9 @@ pub(crate) struct Recoded { pub image: Option, /// Set when the image isn't compressed as asked. pub warning: Option<&'static str>, + /// Set when the colors were to be converted but the image couldn't be decoded or written + /// with them: the source image, kept as it is, would be in its own colors. + pub unconverted: bool, } /// Is `img` (a grey image) only black and white? @@ -373,7 +376,9 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile /// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces). -/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is. +/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is, and +/// is [`Recoded::unconverted`] when `convert` was to convert its colors (any image whose header +/// can't be read, as it may be in color). pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -382,24 +387,26 @@ pub(crate) fn recode( convert: Option<&Pixels>, profiles: bool, ) -> Recoded { - let keep = Recoded { image: None, warning: None }; + let keep = Recoded { image: None, warning: None, unconverted: convert.is_some() }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; - // What the header declares is decoded within the image allowance, not whatever it asks for. - if decoder.set_limits(limits()).is_err() { - return keep; - } - let dims = decoder.dimensions(); use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + // What the header declares is decoded within the image allowance, not whatever it asks for. + // Grey pixels aren't converted. + if decoder.set_limits(limits()).is_err() { + return Recoded { unconverted: convert.is_some() && !grey, ..keep }; + } + let dims = decoder.dimensions(); let (kind, pixels) = if grey { // Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it. let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono)); if kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead { - return Recoded { image: None, warning: g.instead }; + return Recoded { image: None, warning: g.instead, unconverted: false }; } - let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep }; + // Grey pixels aren't converted. + let Ok(img) = DynamicImage::from_decoder(decoder) else { return Recoded { unconverted: false, ..keep } }; (if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img)) } else { (Kind::Color, None) @@ -407,9 +414,9 @@ pub(crate) fn recode( let rule = rule(c, kind); let convert = convert.filter(|_| kind == Kind::Color); if kept(&rule, dims, size, jpeg) && convert.is_none() { - return Recoded { image: None, warning: rule.instead }; + return Recoded { image: None, warning: rule.instead, unconverted: false }; } - let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + let Some(img) = pixels.or_else(|| decoded(bytes)) else { return Recoded { unconverted: convert.is_some(), ..keep } }; // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; @@ -441,7 +448,8 @@ pub(crate) fn recode( to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice)) }); let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc)); - Recoded { image, warning: rule.instead } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, unconverted } } /// A colorized image's coverage (one sample a pixel, `w` × `h`, see @@ -472,6 +480,7 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec, size: (f64, f64), c /// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its /// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc` /// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it. +/// With `convert`, an image whose inks can't be read or written is [`Recoded::unconverted`]. pub(crate) fn recode_cmyk( blob: &ImageBlob, size: (f64, f64), @@ -492,16 +501,22 @@ pub(crate) fn recode_cmyk( let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) .then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) .flatten(); - return Recoded { image, warning: rule.instead }; + return Recoded { image, warning: rule.instead, unconverted: false }; } } + // Inks that can't be read can't be converted: the image is not to be kept as it is. + let unconverted = Recoded { image: None, warning: None, unconverted: true }; let Some(inks) = blob.cmyk() else { - return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }) }; + if convert.is_some() { + return unconverted; + } + return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), unconverted: false }; }; let (width, height) = sized(&rule, (inks.width, inks.height), size); let (inks, alpha) = match resampled_inks(inks, alpha, &rule, (width, height)) { Ok(r) => r, - Err(warning) => return Recoded { image: None, warning }, + Err(_) if convert.is_some() => return unconverted, + Err(warning) => return Recoded { image: None, warning, unconverted: false }, }; let (samples, space) = match convert { Some(p) => p.convert(&inks), @@ -510,7 +525,8 @@ pub(crate) fn recode_cmyk( // JPEG needs opaque pixels. let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc)); let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc)); - Recoded { image, warning: rule.instead } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, unconverted } } /// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any. diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4719beec70..22b8636752 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -585,6 +585,38 @@ fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() { } } +/// A CMYK JPEG whose inks can't be read (it declares more pixels than CMYK images are decoded +/// with, though fewer than the writer embeds) is written with its own numbers only when they are +/// kept: when the Output settings convert its colors it is left out with a warning, in every +/// standard. +#[test] +fn a_cmyk_jpeg_whose_inks_cant_be_read_is_left_out_when_its_colors_are_converted() { + let mut jpg = cmyk_jpeg(&flat([0, 102, 255, 0], 4), 2, 2); + // Height and width of the SOF0 segment (after its marker, length and precision): 8200 × 8200. + let sof = jpg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); + jpg[sof + 5..sof + 9].copy_from_slice(&[0x20, 0x08, 0x20, 0x08]); + let blob = ImageBlob::new("image/jpeg", jpg); + assert!(blob.is_cmyk() && blob.cmyk().is_none()); + let d = image_doc(blob, 2, 2); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let kept = written(&out.bytes); + assert!(kept.len() == 1 && kept[0].space == "DeviceCMYK", "kept as it is: {kept:?}"); + let unconverted = "an image couldn't be converted to the Output destination and is missing from the picture"; + for s in [ + json!({"output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"output": {"conversion": "destination", "destination": SRGB}}), + json!({"standard": "pdfX1a", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfX4", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfA2b", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + ] { + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + assert!(written(&out.bytes).is_empty(), "{s}"); + assert!(out.warnings.iter().any(|w| w == unconverted), "{s}: {:?}", out.warnings); + let other = out.warnings.iter().any(|w| w.contains("couldn't be decoded") || w.contains("written as it is")); + assert!(!other, "{s}: {:?}", out.warnings); + } +} + /// The profile each transparency group of written PDF `bytes` blends in: its ICC-based space's /// profile, or `None` for DeviceCMYK. fn group_profiles(bytes: &[u8]) -> Vec>> { diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 400bc0b0a8..fafb642fbe 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -270,6 +270,36 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert!(r.image.is_none(), "kept as it is"); } +/// When the Output settings convert colors, a color image that can't be decoded can't be kept as +/// it is: it is unconverted, and so is one whose header can't be read. A grey one, whose pixels +/// aren't converted, and any image without a conversion are kept as they are. +#[test] +fn a_color_image_that_cant_be_decoded_for_a_conversion_is_unconverted() { + let d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let settings: PdfSettings = + serde_json::from_value(json!({"output": {"conversion": "destination", "destination": vectorcraft_color::cms::GENERIC_CMYK}})).unwrap(); + let out = crate::output::ColorOut::new(&d, &settings).unwrap(); + assert!(out.pixels().is_some()); + let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); + let cut = |img: DynamicImage| { + let mut png = encoded(img, ImageFormat::Png); + png.truncate(png.len() / 2); + png + }; + let cases = [ + ("RGB", cut(colour()), true), + ("unreadable", vec![1, 2, 3], true), + ("grey", cut(colour().grayscale()), false), + ("grey declaring more than the allowance", declared_png(60_000, 60_000), false), + ]; + for (what, bytes, unconverted) in cases { + let r = crate::images::recode(&bytes, (72.0, 72.0), &c, false, out.pixels(), true); + assert!(r.image.is_none(), "{what}"); + assert_eq!(r.unconverted, unconverted, "{what}"); + assert!(!crate::images::recode(&bytes, (72.0, 72.0), &c, false, None, true).unconverted, "{what}, no conversion"); + } +} + /// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in /// all, with an empty tag table, every byte after the tag count different from its neighbors. fn icc_profile(space: &[u8; 4], len: usize) -> Vec { diff --git a/docs/mcp.md b/docs/mcp.md index d4e03892e9..6028dbcb1e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5650,7 +5650,9 @@ the colour bars are process, spot and black-tint patches. Layers whose Print opt The Output and Advanced sections convert colours and write real text. `output: {conversion, destination}` converts every colour into the destination profile's model (`destination`; CMYK of another profile too) or only the colours of the other model (`preserveNumbers`: colours already in it keep their numbers); grey stays grey, images are converted -too and printer's marks are not. The destination is any profile `edit.colorSettings` lists (default: the document's +too and printer's marks are not. An image whose colors are to be converted but whose pixels can't be decoded or +written that way is left out with the warning "an image couldn't be converted to the Output destination and is +missing from the picture", rather than written in its own colors. The destination is any profile `edit.colorSettings` lists (default: the document's for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cad5851e98..b0a8cdfb52 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1864,6 +1864,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). + - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but can't be decoded. Gray images, whose pixels are not converted, and images in a file that converts no colors are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`). From 80d82612bdc164d21085f3476c02fb39b7b26416 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:43:20 -0800 Subject: [PATCH 09/63] i18n: drop the tr toolbar error rows that main now carries main added Turkish rows for the custom toolbar command errors, so the branch's copies made bundled_catalogs_are_consistent fail on a duplicate @msg row. --- crates/ui-egui/src/i18n/tr.tsv | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6a197927d6..4a6b37a170 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9316,19 +9316,6 @@ breakText Glyphs Glifler Not Aligned to Pixel Grid Piksel Izgarasına Hizalanmamış @msg only paths and compound paths can be aligned to the pixel grid piksel ızgarasına yalnızca yollar ve bileşik yollar hizalanabilir @msg side is left or right, not `{s}` side left veya right olmalıdır, `{s}` değil -@msg side is left or right, not `{v}` side left veya right olmalıdır, `{v}` değil -@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayı olmalıdır, `{v}` değil -@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır -@msg no toolbar named `{name}` `{name}` adlı araç çubuğu yok -@msg toolbar name can't be empty araç çubuğu adı boş olamaz -@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter olabilir -@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var -@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var -@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar -@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır -@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gerekli -@msg to (the new name) is required to (yeni ad) gerekli -@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır Ignore All Tümünü Yoksay Add to Dictionary Sözlüğe Ekle No Suggestions Öneri Yok From 63aeb358c953a3219c85b70dc65ac6e372af5e06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:05:43 -0800 Subject: [PATCH 10/63] Graphs: proxy recolors keep a group's own paint and spread checks on design art alone paint.invert and paint.complement without an item recolor a given group's own fills and strokes with the objects inside it again, except with target "contents", and leave the art of graph designs inside it as it is. A given member of a compound path stands for the compound path. paint.editGradient with a spread or a negative aspect for design art alone no longer checks it against the kind of the default gradient, so it changes nothing instead of failing. A bad value is still an error. --- crates/doc/src/recolor.rs | 8 +++++ crates/engine/src/cmd/appearance.rs | 2 +- crates/engine/src/cmd/colorcmds.rs | 13 ++++++++- crates/engine/src/cmd/gradient.rs | 4 +-- crates/engine/src/cmd/graph/tests.rs | 42 +++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 27 +++++++++++++---- crates/engine/src/tests/paintproxy.rs | 13 +++++++++ 7 files changed, 100 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/recolor.rs b/crates/doc/src/recolor.rs index 0efa82296a..f25340b29f 100644 --- a/crates/doc/src/recolor.rs +++ b/crates/doc/src/recolor.rs @@ -16,6 +16,11 @@ pub trait ColorVisitor { fn color(&mut self, c: Color) -> Color; /// The key of embedded image `key` recoloured, `None` when it stays as it is. fn image(&mut self, key: &str) -> Option; + /// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside + /// it as they are. + fn enters(&mut self, _n: &Node) -> bool { + true + } } /// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh @@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi } _ => { for c in n.children_mut().into_iter().flatten() { + if !v.enters(c) { + continue; + } let mut m = (**c).clone(); let k = recolor_node(&mut m, reach, v); if k > 0 { diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 95b5936af5..17df7dab8a 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -389,7 +389,7 @@ pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], id } /// Whether the `target` param asks for the contents of groups and layers (see the module docs). -fn targets_contents(p: &Value) -> Result { +pub(crate) fn targets_contents(p: &Value) -> Result { match p.get("target") { None | Some(Value::Null) => Ok(false), Some(v) => match v.as_str() { diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 8377822094..9006b1f4be 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> { patterns: HashMap>, new_images: Vec<(String, ImageBlob)>, new_patterns: Vec, + /// Objects inside the recolored ones that keep their colors, with everything inside them. + skip: HashSet, changed: usize, } @@ -236,6 +238,7 @@ impl<'a> Recolor<'a> { patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], + skip: HashSet::new(), changed: 0, } } @@ -254,7 +257,7 @@ impl<'a> Recolor<'a> { /// A pass that maps colors as this one does, with nothing recolored yet. fn again(&self) -> Self { - Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) } + Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) } } /// The entries of `objects` (ids, each with a flag) whose object this pass would change, other @@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> { fn image(&mut self, key: &str) -> Option { self.pass.image(self.d, key) } + fn enters(&mut self, n: &Node) -> bool { + !self.pass.skip.contains(&n.id) + } } pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f)) } +/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are. +pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet) -> Result { + run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) }) +} + /// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel. fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) }) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 89b8daa342..fbbb992fa8 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { _ => None, }); let for_default = match p.get("aspect").and_then(Value::as_f64) { - Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => { + Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => { let mut q = p.clone(); q["aspect"] = json!(-a); std::borrow::Cow::Owned(q) @@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // A spread for selected gradients leaves a freeform default (which has no ends) as it is. let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad()); let for_default = match for_default { - q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => { + q if spreads && selected && default_kind == Some(GradientKind::Freeform) => { let mut q = q.into_owned(); if let Some(o) = q.as_object_mut() { o.remove("spread"); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index a34ac0f724..45673cc1fa 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -588,6 +588,48 @@ fn paint_edits_of_design_art_alone_leave_the_defaults() { assert_ne!(defaults(&s), was); } +/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the +/// default fill is; a bad value is still an error. +#[test] +fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() { + let (mut s, _, _, art, _) = design_art(); + for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] { + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": default})).unwrap(); + let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len()); + let mut q = p.clone(); + q["ids"] = json!([art.0]); + s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}")); + assert_eq!(format!("{:?}", s.paint), was, "{default}"); + assert_eq!(look(&s, art), art_was, "{default}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}"); + } + assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err()); +} + +/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a +/// graph design as it is. With `target: "contents"` the group's own fill stays as it is. +#[test] +fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() { + let (mut s, graph, _, art, mark) = design_art(); + s.execute("select.set", &json!({"ids": [graph.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + let row = top_row(&s, group, true); + s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap(); + let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items); + let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark)); + s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap(); + assert_ne!(own(&s), own_was, "the group's own fill"); + assert_ne!(look(&s, mark), mark_was); + assert_eq!(look(&s, art), art_was); + let (own_was, mark_was) = (own(&s), look(&s, mark)); + s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap(); + assert_eq!(own(&s), own_was, "target: contents"); + assert_ne!(look(&s, mark), mark_was); + assert_eq!(look(&s, art), art_was); +} + /// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects /// sets only theirs. #[test] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index d42ecaf1df..7aa96e7db4 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1107,14 +1107,31 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( (json!({ "changed": changed }), Some(index)) } // The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles. - // Design art inside a given graph or series group is left out too. + // A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other + // objects change as their paint targets do (a compound path's member stands for the compound path). Design art + // inside a given graph or series group is left out. ItemTarget::Top => { - let leaves = targets; - if leaves.is_empty() { + let contents = super::appearance::targets_contents(p)?; + let mut roots = vec![]; + for id in &ids { + let group = !contents + && s.doc()?.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape()); + if group { + roots.push(*id); + } else { + roots.extend(leaf_targets(s, &[*id])?); + } + } + let d = &s.doc()?.doc; + let mut seen = std::collections::HashSet::new(); + roots.retain(|id| seen.insert(*id)); + let roots = super::appearance::drop_design_art(d, roots); + if roots.is_empty() { return Ok(json!({ "changed": 0 })); } - let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": leaves.iter().map(|i| i.0).collect::>()}); - (super::colorcmds::recolor(s, &q, cmd, label, f)?, None) + let art = super::appearance::design_art_in(d, &roots).into_iter().collect(); + let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::>()}); + (super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?, None) } }; let shown_ids = if shown_item.is_some() { ids } else { super::appearance::drop_design_art(&s.doc()?.doc, leaf_targets(s, &ids)?) }; diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index b270826e7a..e10f2df6d8 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -706,3 +706,16 @@ fn a_marker_designs_art_in_a_series_keeps_its_paint() { s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap(); assert_eq!(design_strokes(&s), before, "the design's art keeps its paint"); } + +/// Invert given a member of a compound path inverts the compound path's fill, which the member stands for. +#[test] +fn invert_of_a_compound_member_inverts_the_compound_path() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let comp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [comp.0], "color": "#ff0000"})).unwrap(); + let member = node(&s, comp).children().into_iter().flatten().next().unwrap().id; + s.execute("paint.invert", &json!({"ids": [member.0]})).unwrap(); + assert_eq!(node(&s, comp).appearance.fill_paint().color().unwrap().to_hex(), "#00ffff"); +} From 27704b477ea01b72740a7ffbb6e353b5d202967b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:45:11 -0800 Subject: [PATCH 11/63] fmt: wrap the proxy recolor group check --- crates/engine/src/cmd/paint.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 1c9d7928ef..57ba4b1f0b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1114,8 +1114,9 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( let contents = super::appearance::targets_contents(p)?; let mut roots = vec![]; for id in &ids { - let group = !contents - && s.doc()?.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape()); + let n = s.doc()?.doc.node(*id); + let group = + !contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape()); if group { roots.push(*id); } else { From 49635e9b5fea5c8a320788e4267f5cb90414dd3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:47:15 -0800 Subject: [PATCH 12/63] Docs: paint.invert and paint.complement on a group recolor its own fills or strokes --- crates/engine/src/cmd/paint.rs | 2 +- docs/mcp.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 57ba4b1f0b..085482da16 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), diff --git a/docs/mcp.md b/docs/mcp.md index b61c4a97ed..a7d2cf2f3f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -611,7 +611,9 @@ For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new- For a filled shape or path without an outline, pass an explicit `fill` and `stroke: "none"`. Lines start with no fill and a visible stroke. The Fill/Stroke proxy commands run through `run_command`: `paint.invert` and `paint.complement` recolor the active -proxy, including a grayscale image's colorized fill, while keeping each color's model. `paint.lastColor` / +proxy, including a grayscale image's colorized fill, while keeping each color's model. Given a group without an +Appearance item, they recolor the active proxy's fills or strokes of the objects inside it and of the group itself; +`target: "contents"` leaves the group's own fills or strokes as they are. `paint.lastColor` / `paint.lastGradient` re-apply the last solid color or gradient, and `paint.recent` returns the recent colors that every paint command (and the eyedropper) feeds: up to 30, newest first and each once, kept across documents for the session. `paint.proxies` returns what the proxies show: the fill and stroke, which one is active, and whether the selected From ffd959680f7f2d5a17c85113fbc6a3f8f667c03f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:46:27 -0800 Subject: [PATCH 13/63] Graphs: copies of design art made by a series group's Transform effect keep their effects on Expand Appearance Expand Appearance leaves the art of a graph design in a series as it is. A Transform effect of a series group that makes copies gave each copy new ids, so the copies were expanded and their own effects, such as a drop shadow, became embedded images. The new ids of those copies are now left out too; the series group's own effect still bakes into them. --- crates/engine/src/cmd/effectcmd.rs | 32 ++++++++++++++++++++++------ crates/engine/src/cmd/graph/tests.rs | 26 ++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 9cb3f46a0d..915163ee55 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -982,14 +982,16 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { /// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are /// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids /// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the -/// pieces with the ids they have before that. Returns what each of those other members' expansions -/// lists, by the member's new id. +/// pieces with the ids they have before that. `kept` gets the new id of each object in them that +/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by +/// the member's new id. fn expand_pieces( d: &mut Document, m: &mut Node, all: bool, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], + kept: &mut Vec, stroke_art: effects::StrokeArt, ) -> std::collections::HashMap> { let id = m.id; @@ -1007,7 +1009,21 @@ fn expand_pieces( } else if has_seeded(c) && repeats_an_id(c, &seen) { listed = Some(expand_in_place(d, c, brushes, skip)); } + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); + } fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default()); + if !was.is_empty() { + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + } if let Some(listed) = listed { expanded.insert(c.id, listed); } @@ -1091,7 +1107,8 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b } /// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry -/// effect of a group or layer around one still reshapes it with the rest of its members. +/// effect of a group or layer around one still reshapes it with the rest of its members, and the +/// copies of it that such an effect makes are left as they are too. fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) { let Some(n) = d.node(id).cloned() else { return }; let mut listed = vec![]; @@ -1178,6 +1195,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. let mut members = std::collections::HashMap::new(); + // New ids of the copies of objects `skip` lists among those members. + let mut kept = vec![]; let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -1189,7 +1208,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, skip, &mut stroke_art); + members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) @@ -1210,7 +1229,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; expand_nested_instances(d, &mut m, 1, &mut budget); - expand_pieces(d, &mut m, true, brushes, skip, &mut stroke_art); + expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art); m }) }; @@ -1232,6 +1251,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } } if container { + let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) }; // The place of each member in the walk of `n`: after `n` and the members before it. let mut at = 1; for c in n.children_mut().into_iter().flatten() { @@ -1244,7 +1264,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br match members.remove(&c.id) { Some(listed) => out.extend(listed), None => { - if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, out) { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) { *c = Arc::new(e); changed = true; } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 07b5ba2b8f..a6aea80408 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -768,6 +768,32 @@ fn expand_appearance_moves_design_art_with_its_series_groups_effect() { assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s)); } +/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand +/// Appearance bakes the series group's effect, as the art they copy does. +#[test] +fn expand_appearance_leaves_the_effects_of_design_art_copies() { + let (mut s, id, copy, _, _) = design_art(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let group = series(&n, 0).id; + let shadow = an_effect(&mut s, "stylize.dropShadow", json!({})); + let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2})); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(copy).unwrap().appearance.effects.push(shadow); + doc.node_mut(group).unwrap().appearance.effects.push(copies); + let shadows = |s: &Session| { + let mut count = 0; + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count()); + count + }; + let images = |s: &Session| s.doc().unwrap().doc.images.len(); + let before = images(&s); + assert_eq!(shadows(&s), 1); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows"); + assert_eq!(images(&s), before, "no shadow becomes an image"); +} + /// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by /// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design. #[test] From 7cc604a003294991548b29df2aad47f3294193b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:46:28 -0800 Subject: [PATCH 14/63] Attributes: overprint reads the art of graph designs in series again The merge of main dropped the art from attributes.info's overprint read, so overprintFill and overprintStroke came back null with only that art selected. The edits still leave the art out. --- crates/engine/src/cmd/overprint.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 0da36a3270..e8957691ec 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -126,8 +126,9 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result> { .collect() } -/// Each kind's item target and objects: (fill?, item, ids). With `edit`, an explicit item that the graph design art left -/// out has no row of that kind for is an error, as when the edit resolves it on the other objects. +/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series +/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit +/// resolves it on the other objects. Without it, the art is read with the other objects. fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator, edit: bool) -> Result)>> { let item = item_target(s, p, cmd)?; kinds @@ -135,11 +136,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator .map(|fill| { let it = item.of_kind(s, fill); let ids = it.targets(s, p)?; - let ids = if edit { - super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? - } else { - super::appearance::drop_design_art(&s.doc()?.doc, ids) - }; + let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids }; Ok((fill, it, ids)) }) .collect() From d5b2318b75538b9f92426a89073dafdb0e12cc22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:46:29 -0800 Subject: [PATCH 15/63] Docs: one paragraph for the commands that leave graph design art out The merge of main left two copies of the paragraph. The merged one keeps the rows and effects given with aligned: true, and the commands that leave the defaults for new art as they are. --- docs/mcp.md | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 0dc3e847c4..c2c30b0a01 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -836,25 +836,6 @@ inside a series group other than a path directly in it, a legend swatch's includ reached through `target: "contents"`. These commands leave that art out, edit the other objects they are given, and are an error when all their objects are design art: the `appearance.*` commands listed above, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, move or remove an effect, -`effect.expandAppearance` (which also leaves the art inside a selected graph or series group as it was, unless an -effect of that group turns the whole group into other art, and is disabled when only design art is selected or -given), `threeD.mapGraphic`, -`graphicStyle.apply`, `graphicStyle.addFromLibrary` with `apply`, `graphicStyle.breakLink`, `transparency.set`, the -`paint.freeform.*` commands that edit points and lines, and `appearance.copyFrom` as the target. -`appearance.transfer` with design art as its `target`, or as its `source` without `copy`, is an error. -`paint.setFill`, `paint.setStroke`, `paint.swap`, `paint.default`, `paint.invert` and `paint.complement` with an -`item`, `stroke.set`, `stroke.weightUp`, `stroke.weightDown`, `stroke.setAdvanced`, `paint.editGradient`, -`paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When the first selected object is design art, the commands -do not use the Appearance panel's active row. When the first object given is design art, rows and effects given with -`aligned: true` are rows of its stack in `appearance.setItem`, `appearance.removeItem`, `appearance.duplicateItem`, -`transparency.set` with an `item`, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, -move or remove an effect: each other object edits the row or effect equal to it, and an object without one is left as -it is. When no object has one, `appearance.setItem` and `appearance.removeItem` leave the document as it is, as they do -for a row no object has, and the other commands are an error. `appearance.moveItem`, `effect.move` and -`appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects', and -`appearance.duplicateItem` with `to` is also an error when two or more other objects are given, as it is without the -art. To change the art, edit the design with `graph.design`. - `effect.expandAppearance` (which also leaves the art inside a selected graph or series group as it was, except that an effect of that group which reshapes or replaces the whole group bakes into that art too, and is disabled when only design art is selected or given), `threeD.mapGraphic`, @@ -866,7 +847,15 @@ design art is selected or given), `threeD.mapGraphic`, `paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When all their objects are design art, `paint.editGradient`, `paint.swap`, `paint.default`, `paint.invert`, `paint.complement` and `stroke.set` also leave the paint and stroke weight for new art and the remembered colors as they are. When the first selected object is design art, the commands -do not use the Appearance panel's active row. To change the art, edit the design with `graph.design`. +do not use the Appearance panel's active row. When the first object given is design art, rows and effects given with +`aligned: true` are rows of its stack in `appearance.setItem`, `appearance.removeItem`, `appearance.duplicateItem`, +`transparency.set` with an `item`, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, +move or remove an effect: each other object edits the row or effect equal to it, and an object without one is left as +it is. When no object has one, `appearance.setItem` and `appearance.removeItem` leave the document as it is, as they do +for a row no object has, and the other commands are an error. `appearance.moveItem`, `effect.move` and +`appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects', and +`appearance.duplicateItem` with `to` is also an error when two or more other objects are given, as it is without the +art. To change the art, edit the design with `graph.design`. The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke of a path directly in a series: a weight set with `stroke.set`, `stroke.weightUp` or `stroke.weightDown`; a gradient From a3674845972c86da69a93de657f9f58cd47ba9fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 21:31:56 -0800 Subject: [PATCH 16/63] Properties: a Graph section opens Graph Type and Graph Data for a selected graph With one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section. Graph Type... and Graph Data... open the dialogs of Object > Graph > Type... and Data.... Column... shows when every series it would change draws columns or bars, and Marker... when every one draws lines, scatter points or radar lines; both open their Object > Graph dialogs. The section lives in panels/properties/graph.rs. --- 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/panels/properties.rs | 2 + crates/ui-egui/src/panels/properties/graph.rs | 99 +++++++++++++++++ crates/ui-egui/src/panels/properties/tests.rs | 105 ++++++++++++++++++ docs/target-app-parity.md | 1 + 32 files changed, 263 insertions(+) create mode 100644 crates/ui-egui/src/panels/properties/graph.rs diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 948b295e17..6fd3094e3b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1365,6 +1365,8 @@ font-technology Variable Променливи Graph Диаграма Graph Data Данни за диаграма Graph Type Тип диаграма + Graph Type… Тип диаграма… + Graph Data… Данни за диаграма… Graph Design Дизайн на диаграма Graph Marker Маркер на диаграма New Design Нов дизайн diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f8d6fa263b..6e5081e2b1 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3568,6 +3568,8 @@ theme Appearance Izgled Create Graph Kreiraj grafikon Graph Data Podaci grafikona Graph Type Vrsta grafikona + Graph Type… Vrsta grafikona… + Graph Data… Podaci grafikona… Vector Halftone Vektorski polutonovi spot spot Text Tekst diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3ed3ca8331..b27b888ff6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1896,6 +1896,8 @@ digits Malayalam Malaiàlam Graph Design Disseny del gràfic Graph Marker Marcador del gràfic Graph Type Tipus de gràfic + Graph Type… Tipus de gràfic… + Graph Data… Dades del gràfic… Graphic Gràfic Graphic Pen Ploma gràfica Graphic Pen… Ploma gràfica… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..7d9255ae4a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3622,6 +3622,8 @@ theme Appearance Motiv Create Graph Vytvořit graf Graph Data Data grafu Graph Type Typ grafu + Graph Type… Typ grafu… + Graph Data… Data grafu… Vector Halftone Vektorový polotón spot přímá Text Text diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fd0b7c042e..6f345c26eb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3962,6 +3962,8 @@ theme Appearance Udseende Create Graph Opret graf Graph Data Grafdata Graph Type Graftype + Graph Type… Graftype… + Graph Data… Grafdata… Vector Halftone Vektorraster spot spot Text Tekst diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..e47b71b0ca 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1410,6 +1410,8 @@ file-filter Templates Vorlagen Graph Diagramm Graph Data Diagrammdaten Graph Type Diagrammtyp + Graph Type… Diagrammtyp… + Graph Data… Diagrammdaten… Graph Design Diagrammdesign Graph Marker Diagrammmarkierung New Design Neues Design diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b1b7b4d039..54cf2ec839 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1340,6 +1340,8 @@ font-technology Variable Μεταβλητές Graph Γράφημα Graph Data Δεδομένα γραφήματος Graph Type Τύπος γραφήματος + Graph Type… Τύπος γραφήματος… + Graph Data… Δεδομένα γραφήματος… Graph Design Σχεδίαση γραφήματος Graph Marker Δείκτης γραφήματος New Design Νέο σχέδιο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b3c675f7b..79b2a5eb19 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1419,6 +1419,8 @@ font-technology Variable Variables Graph Gráfico Graph Data Datos del gráfico Graph Type Tipo de gráfico + Graph Type… Tipo de gráfico… + Graph Data… Datos del gráfico… Graph Design Diseño de gráfico Graph Marker Marcador de gráfico New Design Nuevo diseño diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e77a617c52..1d873a1e32 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3560,6 +3560,8 @@ theme Appearance Ulkoasu Create Graph Luo kaavio Graph Data Kaavion tiedot Graph Type Kaavion tyyppi + Graph Type… Kaavion tyyppi… + Graph Data… Kaavion tiedot… Vector Halftone Vektorirasteri spot spotti Text Teksti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..588f1d6701 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1413,6 +1413,8 @@ font-technology Variable Variables Graph Graphe Graph Data Données du graphe Graph Type Type de graphe + Graph Type… Type de graphe… + Graph Data… Données du graphe… Graph Design Conception de graphe Graph Marker Marqueur de graphe New Design Nouvelle conception diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c96900b2b..3e12ecfc21 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1538,6 +1538,8 @@ Graph Design ગ્રાફ ડિઝાઇન Graph Marker ગ્રાફ માર્કર Graph Type ગ્રાફ પ્રકાર + Graph Type… ગ્રાફ પ્રકાર… + Graph Data… ગ્રાફ ડેટા… Graphic Pen… ગ્રાફિક પેન… Graphic Style ગ્રાફિક સ્ટાઇલ Graphic Style Libraries ગ્રાફિક સ્ટાઇલ લાઇબ્રેરીઓ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..c4739db04e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2113,6 +2113,8 @@ antiAlias Sharp शार्प Graph Design ग्राफ़ डिजाइन Graph Marker ग्राफ़ मार्कर Graph Type ग्राफ़ टाइप + Graph Type… ग्राफ़ टाइप… + Graph Data… ग्राफ़ डेटा… Graphic ग्राफिक Graphic Pen ग्राफ़िक पेन Graphic Pen… ग्राफ़िक पेन… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..9df28cffb6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1764,6 +1764,8 @@ file-filter Templates Sablonok Graph Diagram Graph Data Diagramadatok Graph Type Diagramtípus + Graph Type… Diagramtípus… + Graph Data… Diagramadatok… Select Segments Szakaszok kijelölése Artistic Művészi Film Grain… Filmszemcse… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f3dcca3874..6a237d7f8e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3353,6 +3353,8 @@ theme Appearance Tampilan Create Graph Buat grafik Graph Data Data grafik Graph Type Jenis grafik + Graph Type… Jenis grafik… + Graph Data… Data grafik… Vector Halftone Halftone vektor spot spot Text Teks diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..cd7d4a569e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1440,6 +1440,8 @@ file-filter Templates Modelli Graph Grafico Graph Data Dati grafico Graph Type Tipo di grafico + Graph Type… Tipo di grafico… + Graph Data… Dati grafico… Graph Design Design del grafico Graph Marker Indicatore del grafico New Design Nuovo design diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..17a6b629e1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3856,6 +3856,8 @@ file-filter Templates テンプレート Gradient (. or Shift+.) グラデーション (. または Shift+.) Graph Data グラフデータ Graph Type グラフの種類 + Graph Type… グラフの種類… + Graph Data… グラフデータ… Graph Design グラフのデザイン Graph Marker グラフのマーカー New Design 新規デザイン diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 794e5454a9..0cb324b42e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3199,6 +3199,8 @@ theme Appearance იერსახე Create Graph გრაფიკის შექმნა Graph Data გრაფიკის მონაცემები Graph Type გრაფიკის ტიპი + Graph Type… გრაფიკის ტიპი… + Graph Data… გრაფიკის მონაცემები… Vector Halftone ვექტორული ნახევარტონი spot სპოტ Text ტექსტი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..946ecd8a62 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3844,6 +3844,8 @@ file-filter Templates 템플릿 Gradient (. or Shift+.) 그레이디언트 (. 또는 Shift+.) Graph Data 그래프 데이터 Graph Type 그래프 유형 + Graph Type… 그래프 유형… + Graph Data… 그래프 데이터… Graph Design 그래프 디자인 Graph Marker 그래프 마커 New Design 새 디자인 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..6366a9e537 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3871,6 +3871,8 @@ theme Appearance Vormgeving Create Graph Diagram maken Graph Data Diagramgegevens Graph Type Diagramtype + Graph Type… Diagramtype… + Graph Data… Diagramgegevens… Vector Halftone Vectorhalftoon spot spot Text Tekst diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..e6c851862e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3501,6 +3501,8 @@ theme Appearance Wygląd Create Graph Utwórz wykres Graph Data Dane wykresu Graph Type Typ wykresu + Graph Type… Typ wykresu… + Graph Data… Dane wykresu… Vector Halftone Półton wektorowy spot dodatkowy Text Tekst diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..b87ba4d725 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4964,6 +4964,8 @@ axis Both Ambos Gradient (. or Shift+.) Gradiente (. ou Shift+.) Graph Data Dados do Gráfico Graph Type Tipo de Gráfico + Graph Type… Tipo de Gráfico… + Graph Data… Dados do Gráfico… New Design Novo Design Delete Design Excluir Design Paste Design Colar Design diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 106343cddd..1bc01a2b57 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1429,6 +1429,8 @@ file-filter Templates Шаблоны Graph Диаграмма Graph Data Данные диаграммы Graph Type Тип диаграммы + Graph Type… Тип диаграммы… + Graph Data… Данные диаграммы… Graph Design Дизайн диаграммы Graph Marker Маркер диаграммы New Design Новый дизайн diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..461d06d19c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1378,6 +1378,8 @@ font-technology Variable Variabla Graph Diagram Graph Data Diagramdata Graph Type Diagramtyp + Graph Type… Diagramtyp… + Graph Data… Diagramdata… Graph Design Diagramdesign Graph Marker Diagrammarkör New Design Ny design diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..58c8911190 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1352,6 +1352,8 @@ font-technology Variable Değişken Graph Grafik Graph Data Grafik Verileri Graph Type Grafik Türü + Graph Type… Grafik Türü… + Graph Data… Grafik Verileri… Graph Design Grafik Tasarımı Graph Marker Grafik İşaretleyici New Design Yeni Tasarım diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..b343a43f91 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1434,6 +1434,8 @@ file-filter Templates Шаблони Graph Діаграма Graph Data Дані діаграми Graph Type Тип діаграми + Graph Type… Тип діаграми… + Graph Data… Дані діаграми… Graph Design Дизайн діаграми Graph Marker Маркер діаграми New Design Новий дизайн diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1460910197..267e822072 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1684,6 +1684,8 @@ file-filter Templates Mẫu Chop Design Cắt thiết kế Scale Design Co giãn thiết kế Graph Type Loại biểu đồ + Graph Type… Loại biểu đồ… + Graph Data… Dữ liệu biểu đồ… Graphic Đồ họa Graphic Style Kiểu đồ họa Graphic Style Libraries Thư viện 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 3fe2f9e009..d630d1f627 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1369,6 +1369,8 @@ file-filter Templates 模板 Graph 图表 Graph Data 图表数据 Graph Type 图表类型 + Graph Type… 图表类型… + Graph Data… 图表数据… Graph Design 图表设计 Graph Marker 图表标记 New Design 新建设计 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..2c0f6a4adb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1404,6 +1404,8 @@ file-filter Templates 範本 Graph 圖表 Graph Data 圖表資料 Graph Type 圖表類型 + Graph Type… 圖表類型… + Graph Data… 圖表資料… Graph Design 圖表設計 Graph Marker 圖表標記 New Design 新增設計 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 6195de4b24..d4314302f5 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -69,6 +69,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { objects_on_path_section(app, ui, &oop); divider(ui); } + graph::section(app, ui); if matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Text(_))) { type_sections(app, ui); divider(ui); @@ -1037,6 +1038,7 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { } pub(crate) mod dynamic_text; +pub(crate) mod graph; pub(crate) mod vertical_align; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/properties/graph.rs b/crates/ui-egui/src/panels/properties/graph.rs new file mode 100644 index 0000000000..fe86d6e0ac --- /dev/null +++ b/crates/ui-egui/src/panels/properties/graph.rs @@ -0,0 +1,99 @@ +//! The Properties panel's Graph section, for one selected graph or series of one graph picked with +//! Group Selection: Graph Type… and Graph Data… open the dialogs of Object › Graph › Type… and +//! Data… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html) +//! opens Graph Type from the Properties panel). Column… shows when every series it would change +//! draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; +//! both run the same route as their Object › Graph items. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Document, GraphKind, MAX_GRAPH_SERIES, NodeId}; + +use crate::VectorcraftApp; +use crate::widgets::{self, divider, section_header}; + +/// The Graph section's optional buttons for the selection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Shown { + /// Column… takes the series it would change. + pub(crate) column: bool, + /// Marker… takes the series it would change. + pub(crate) marker: bool, +} + +/// What the Graph section shows for the selection; `None` unless everything selected is one graph +/// or lies inside the same graph. +pub(crate) fn shown(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let doc = &st.doc; + let mut graph = None; + for id in &st.selection.objects { + let g = graph_of(doc, *id)?; + if graph.is_some_and(|x| x != g) { + return None; + } + graph = Some(g); + } + let graph = graph?; + let spec = doc.node(graph)?.extras().graph.as_deref()?; + let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, MAX_GRAPH_SERIES); + // The series Column… and Marker… change: those picked with Group Selection when the selection is + // only series, else every series (as `graph.column` and `graph.marker` pick them). + let picked: Option> = st.selection.objects.iter().map(|id| series_of(doc, graph, *id).filter(|i| *i < count)).collect(); + let series = picked.unwrap_or_else(|| (0..count).collect()); + let kinds: Vec = series.iter().map(|i| spec.series_kind(*i)).collect(); + let all = |ks: &[GraphKind]| !kinds.is_empty() && kinds.iter().all(|k| ks.contains(k)); + Some(Shown { + column: all(&[GraphKind::Column, GraphKind::StackedColumn, GraphKind::Bar, GraphKind::StackedBar]), + marker: all(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]), + }) +} + +/// The graph `id` is or lies in. +fn graph_of(doc: &Document, id: NodeId) -> Option { + let mut cur = Some(id); + while let Some(c) = cur { + if doc.node(c).is_some_and(|n| n.extras().graph.is_some()) { + return Some(c); + } + cur = doc.parent_of(c); + } + None +} + +/// The index of the series of `graph` that `id` is or lies in; `None` for the graph itself, its +/// axes and its legend. +fn series_of(doc: &Document, graph: NodeId, id: NodeId) -> Option { + let mut cur = id; + loop { + let parent = doc.parent_of(cur)?; + if parent == graph { + return doc.node(cur)?.extras().series_index.and_then(|i| usize::try_from(i).ok()); + } + cur = parent; + } +} + +/// The Graph section for the selection, with the divider after it; nothing without a graph. +pub(crate) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(s) = shown(app) else { return }; + section_header(ui, tl!("Graph")); + let mut buttons = vec![(tl!("Graph Type…"), "graph.setType"), (tl!("Graph Data…"), "graph.setData")]; + if s.column { + buttons.push((tl!("Column…"), "graph.column")); + } + if s.marker { + buttons.push((tl!("Marker…"), "graph.marker")); + } + let w = (ui.available_width() - 6.0) / 2.0; + for pair in buttons.chunks(2) { + ui.horizontal(|ui| { + for (label, id) in pair { + if widgets::flat_button(ui, label, w).clicked() { + crate::menus::invoke(app, id, json!({})); + } + } + }); + } + divider(ui); +} diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 9300619765..b8f702be83 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -2014,3 +2014,108 @@ fn dynamic_text_rows_follow_the_selected_area_type() { app.run("text.thread.create", json!({})).unwrap(); assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.enabled)), Some((Some(false), false))); } + +/// A document with a graph of `kind` and three series, selected → the graph's id. +fn graph_doc(app: &mut VectorcraftApp, kind: &str, x: f64) -> u64 { + if app.session.active().is_none() { + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + } + let csv = ",a,b,c\nQ1,1,2,3\nQ2,3,4,5"; + app.run("graph.create", json!({"type": kind, "x": x, "y": 0, "width": 200, "height": 150, "csv": csv})).unwrap()["id"].as_u64().unwrap() +} + +/// The ids of graph `graph`'s series groups, in series order. +fn series_groups(app: &VectorcraftApp, graph: u64) -> Vec { + let st = app.session.active().unwrap(); + let mut groups: Vec<(u32, u64)> = st + .doc + .node(vectorcraft_doc::NodeId(graph)) + .and_then(vectorcraft_doc::Node::children) + .into_iter() + .flatten() + .filter_map(|c| c.extras().series_index.map(|i| (i, c.id.0))) + .collect(); + groups.sort_unstable(); + groups.into_iter().map(|(_, id)| id).collect() +} + +/// One selected column graph has a Graph section with Graph Type…, Graph Data… and Column…, and +/// each button opens its Object › Graph dialog for the graph. +#[test] +fn one_selected_graph_has_a_graph_section_whose_buttons_open_the_graph_dialogs() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + graph_doc(&mut app, "column", 0.0); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: true, marker: false })); + let ctx = egui::Context::default(); + let texts = frame(&mut app, &ctx, vec![]); + for label in ["Graph", "Graph Type…", "Graph Data…", "Column…"] { + assert!(texts.iter().any(|(t, _)| t == label), "no {label:?} in {texts:?}"); + } + assert!(!texts.iter().any(|(t, _)| t == "Marker…"), "{texts:?}"); + let press = |app: &mut VectorcraftApp, label: &str| { + let texts = panel_frame(app, &ctx, vec![], graph::section); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")); + let b = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + panel_frame(app, &ctx, vec![Event::PointerMoved(at), b(true)], graph::section); + panel_frame(app, &ctx, vec![b(false)], graph::section); + app.ui.dialog.take().unwrap_or_else(|| panic!("{label:?} opened no dialog")) + }; + let d = press(&mut app, "Graph Type…"); + assert_eq!((d.kind.as_str(), d.str("__command")), ("command", "graph.setType".to_string())); + assert_eq!(d.str("type"), "column"); + assert_eq!(press(&mut app, "Graph Data…").kind, crate::dialogs::graph_data::KIND); + assert_eq!(press(&mut app, "Column…").kind, crate::dialogs::graph_design::COLUMN); +} + +/// Column… shows when every series it would change draws columns or bars, Marker… when every one +/// draws lines, scatter points or radar lines: series picked with Group Selection count on their +/// own, and a combined graph selected whole shows neither. +#[test] +fn the_graph_sections_column_and_marker_follow_the_series_they_would_change() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let g = graph_doc(&mut app, "column", 0.0); + app.run("graph.setType", json!({"seriesIndexes": [1], "type": "line"})).unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: false }), "column and line series"); + let groups = series_groups(&app, g); + assert_eq!(groups.len(), 3, "{groups:?}"); + app.run("select.set", json!({"ids": [groups[1]]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: true }), "the line series"); + app.run("select.set", json!({"ids": [groups[0], groups[2]]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: true, marker: false }), "the column series"); + app.run("select.set", json!({"ids": [groups[0], groups[1]]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: false }), "one of each"); + for (kind, shown) in [ + ("line", (false, true)), + ("scatter", (false, true)), + ("radar", (false, true)), + ("bar", (true, false)), + ("pie", (false, false)), + ("area", (false, false)), + ] { + let id = graph_doc(&mut app, kind, 300.0); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(graph::shown(&app).map(|s| (s.column, s.marker)), Some(shown), "{kind}"); + app.run("edit.clear", json!({})).unwrap(); + } +} + +/// The Graph section shows only while everything selected is one graph or lies in it. +#[test] +fn the_graph_section_needs_one_graph_selected() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let a = graph_doc(&mut app, "column", 0.0); + let b = graph_doc(&mut app, "column", 300.0); + let rect = app.run("shape.rectangle", json!({"x": 600, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + for (ids, what) in [(vec![rect], "a rectangle"), (vec![a, rect], "a graph and a rectangle"), (vec![a, b], "two graphs")] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + assert_eq!(graph::shown(&app), None, "{what}"); + let texts = frame(&mut app, &egui::Context::default(), vec![]); + assert!(!texts.iter().any(|(t, _)| t == "Graph Type…"), "{what}: {texts:?}"); + } + let groups = series_groups(&app, a); + app.run("select.set", json!({"ids": [groups[0], groups[1]]})).unwrap(); + assert!(graph::shown(&app).is_some(), "two series of one graph"); + app.run("select.set", json!({"ids": [groups[0], series_groups(&app, b)[0]]})).unwrap(); + assert_eq!(graph::shown(&app), None, "series of two graphs"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4424700be..f2d51f543c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -620,6 +620,7 @@ since 2026-10-01. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. +- **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section whose Graph Type… and Graph Data… buttons open the dialogs of Object › Graph › Type… and Data… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. From 72dc2968aa5e9f0bb7e28aca3c7b9a06231b8169 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:00:51 -0800 Subject: [PATCH 17/63] PDF export: the progress line names the images an sRGB destination keeps when they can't be decoded --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 746cc7f5cd..21f426d331 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1882,7 +1882,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but can't be decoded. Gray images, whose pixels are not converted, and images in a file that converts no colors are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). + - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but can't be decoded. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - PDF export with Output › Convert to Destination and an sRGB destination converts a gray or RGB image that carries an ICC profile from that profile to sRGB, with the color settings' rendering intent, and writes it without the profile, as the conversion applies to every color ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): 8-bit and 16-bit TIFFs (16 bits a sample from PDF 1.5 on when not resampled or recompressed), PNGs, JPEGs (kept as JPEG) and resampled images. A JPEG in an sRGB profile keeps its JPEG data, a black-and-white image whose converted levels are gray is written as grayscale, and without conversion every image keeps its profile. An image whose profile the color engine can't read, or whose pixels can't be decoded, is not converted: it keeps its profile, with a warning (`crates/pdf/src/tests/compression.rs`). From becc085044362def7060093aaacd284892df9d49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:24:30 -0800 Subject: [PATCH 18/63] =?UTF-8?q?Docs:=20cite=20the=20help=20page=20for=20?= =?UTF-8?q?Graph=20Type=E2=80=A6=20alone=20in=20the=20Properties=20Graph?= =?UTF-8?q?=20section=20line?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cited page describes picking Graph Type in the Properties panel and does not mention Graph Data. The line now cites it next to Graph Type… only and states that the Graph Data… button is VectorCraft's own. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f2d51f543c..72e89573cc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -620,7 +620,7 @@ since 2026-10-01. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. -- **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section whose Graph Type… and Graph Data… buttons open the dialogs of Object › Graph › Type… and Data… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. Scores unchanged. +- **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section. Its Graph Type… button opens the dialog of Object › Graph › Type… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Its Graph Data… button opens the dialog of Object › Graph › Data…; this button is VectorCraft's own. Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. From bd19ed162393d12d703407c56ef4cf904ecf0292 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:28:41 -0800 Subject: [PATCH 19/63] =?UTF-8?q?Variables:=20Import=E2=80=A6=20in=20the?= =?UTF-8?q?=20panel=20menu=20reads=20a=20CSV=20or=20an=20XML=20data=20sour?= =?UTF-8?q?ce?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Variables panel menu gets Import…, which opens one file dialog for CSV, TSV, TXT and XML files. `variable.import {path}` picks the reader by the file's extension, in any case: a .csv, .tsv or .txt file is read as Import Data Sets… reads it, and an .xml file as Load Variable Library… reads it. Any other extension, or none, is refused before the file is read. Import Data Sets… and Load Variable Library… stay in the menu. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/variablecmds.rs | 26 +++++++++++ crates/engine/src/tests/variables.rs | 63 ++++++++++++++++++++++++++ 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/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/variables.rs | 23 ++++++++++ docs/mcp.md | 5 ++ docs/target-app-parity.md | 1 + 29 files changed, 142 insertions(+) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index a73c16448b..8c0d80dee0 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -11,6 +11,7 @@ //! visibility, `@` for image, 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. +//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension. //! Agents reach every command through `run_command`, like all engine commands. use std::collections::{BTreeMap, BTreeSet}; @@ -697,6 +698,22 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result { apply_dataset(s, &name) } +/// The Variables panel's Import…: a data source file read by its extension, a CSV, TSV or TXT +/// file as `dataset.import` reads it and an XML file as `variable.loadLibrary` reads it. The +/// result is that command's, with `format` set to `csv` or `xml`. +fn variable_import(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.import"; + let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; + let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (format, mut out) = match ext.as_deref() { + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), + Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), + }; + out["format"] = json!(format); + Ok(out) +} + pub fn specs() -> Vec { vec![ cmd!( @@ -872,6 +889,15 @@ pub fn specs() -> Vec { has_doc, dataset_import ), + cmd!( + "variable.import", + "Import…", + ["Window", "Variables"], + None, + "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + has_doc, + variable_import + ), cmd!( query "dataset.export", "Export Data Sets…", diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index bb5b73b2f2..92582142d5 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2316,6 +2316,69 @@ fn a_variable_library_defines_text_variables_and_data_sets() { assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 2); } +/// The Variables panel's Import… reads a data source by its extension, in any case: a .csv, .tsv +/// or .txt file as Import Data Sets… reads it, and an .xml file as Load Variable Library… reads it. +/// Any other extension, or none, is refused before the file is read. +#[test] +fn variable_import_reads_a_data_source_by_its_extension() { + let dir = Folder::new("vars-import"); + let mut s = session(); + let t = text(&mut s, "Alice"); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + + for name in ["rows.csv", "rows.TSV", "rows.txt"] { + let path = dir.file(name); + write(&path, b"Name\nAnn\nBob\n"); + let r = s.execute("variable.import", &json!({"path": path})).unwrap(); + assert_eq!((r["format"].clone(), r["names"].clone()), (json!("csv"), json!(["Data Set 1", "Data Set 2"])), "{name}"); + } + s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(plain(&s, t), "Bob"); + + let xml = r#"

Charlie

"#; + let path = dir.file("library.Xml"); + write(&path, xml.as_bytes()); + let r = s.execute("variable.import", &json!({"path": path})).unwrap(); + assert_eq!((r["format"].clone(), r["names"].clone(), r["deleted"].clone()), (json!("xml"), json!(["Row 1"]), json!([]))); + // The library declares the bound text variable, so its binding stays. + s.execute("dataset.select", &json!({"name": "Row 1"})).unwrap(); + assert_eq!(plain(&s, t), "Charlie"); + + // The extension picks the reader: CSV text in an .xml file goes to the library reader, which + // refuses it, and a library in a .csv file goes to the CSV reader. + let csv_in_xml = dir.file("rows.xml"); + write(&csv_in_xml, b"Name\nAnn\n"); + let e = s.execute("variable.import", &json!({"path": csv_in_xml})).unwrap_err().to_string(); + assert!(e.contains("variable.loadLibrary"), "{e}"); + let xml_in_csv = dir.file("library.csv"); + write(&xml_in_csv, xml.as_bytes()); + let e = s.execute("variable.import", &json!({"path": xml_in_csv})).unwrap_err().to_string(); + assert!(e.contains("dataset.import"), "{e}"); + + // Other extensions, or none, are refused before the file is read, so a missing file gives the + // same error; the data sets stay as they were. + let refused = "Import reads a data source file ending in .csv, .tsv, .txt or .xml"; + for (name, exists) in [("rows.json", true), ("rows", true), ("rows.csv.bak", true), ("missing.ai", false)] { + let path = dir.file(name); + if exists { + write(&path, b"Name\nAnn\n"); + } + let e = s.execute("variable.import", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains(refused), "{name}: {e}"); + } + let names: Vec = s.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); + assert_eq!(names, ["Row 1"]); + + // `path` is required, and the command takes no other parameter. + for bad in [json!({}), json!({"path": 3})] { + let e = s.execute("variable.import", &bad).unwrap_err().to_string(); + assert!(e.contains("missing `path`"), "{bad}: {e}"); + } + let e = s.execute("variable.import", &json!({"path": dir.file("rows.csv"), "csv": "Name\nX\n"})).unwrap_err().to_string(); + assert!(e.contains("unknown parameter `csv`"), "{e}"); +} + /// Load Variable Library replaces the document's variables and data sets: every variable goes with /// its bindings and values, a variable of another kind with a library variable's name included, /// and every data set goes, the active one included. A text variable the library also declares diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0b2d6e1bbb..18f3890676 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2440,6 +2440,7 @@ digits Malayalam Malaiàlam Load Variable Library Carrega la biblioteca de variables Load Variable Library… Carrega la biblioteca de variables… Save Variable Library… Desa la biblioteca de variables… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Importa» llegeix un fitxer d’origen de dades amb l’extensió .csv, .tsv, .txt o .xml @msg a variable library holds text variables, and the document has none una biblioteca de variables conté variables de text, i el document no en té cap @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variable `{name}` no es pot desar en una biblioteca de variables: canvieu-li el nom perquè comenci amb una lletra o `_`, sense espais ni símbols que no siguin `-`, `_` i `.` @msg data set `{name}` holds a control character, which a variable library can't hold el conjunt de dades `{name}` conté un caràcter de control, que una biblioteca de variables no pot contenir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6dae58344c..3bc940bc17 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6231,6 +6231,7 @@ mark-style Japanese Japonské Export Data Sets… Exportovat sady dat… Load Variable Library… Načíst knihovnu proměnných… Save Variable Library… Uložit knihovnu proměnných… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „Importovat“ čte soubor zdroje dat s příponou .csv, .tsv, .txt nebo .xml @msg a variable library holds text variables, and the document has none knihovna proměnných obsahuje textové proměnné a dokument žádné nemá @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` proměnnou `{name}` nelze uložit do knihovny proměnných: přejmenujte ji tak, aby začínala písmenem nebo `_` a neobsahovala mezery ani jiné symboly než `-`, `_` a `.` @msg data set `{name}` holds a control character, which a variable library can't hold sada dat `{name}` obsahuje řídicí znak, který knihovna proměnných nemůže obsahovat diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fdeef326c4..a340ceb49f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6262,6 +6262,7 @@ mark-style Japanese Japansk Export Data Sets… Eksportér datasæt… Load Variable Library… Indlæs variabelbibliotek… Save Variable Library… Gem variabelbibliotek… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml »Importér« læser en datakildefil med filtypenavnet .csv, .tsv, .txt eller .xml @msg a variable library holds text variables, and the document has none et variabelbibliotek indeholder tekstvariabler, og dokumentet har ingen @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variablen `{name}` kan ikke gemmes i et variabelbibliotek: omdøb den, så den begynder med et bogstav eller `_`, uden mellemrum eller andre symboler end `-`, `_` og `.` @msg data set `{name}` holds a control character, which a variable library can't hold datasættet `{name}` indeholder et kontroltegn, som et variabelbibliotek ikke kan indeholde diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fdd65a9e5d..19226ed0ee 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5814,6 +5814,7 @@ effect Soft Weich Export Data Sets… Datensätze exportieren… Load Variable Library… Variablenbibliothek laden… Save Variable Library… Variablenbibliothek speichern… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „Importieren“ liest eine Datenquelldatei mit der Endung .csv, .tsv, .txt oder .xml @msg a variable library holds text variables, and the document has none eine Variablenbibliothek enthält Textvariablen, und das Dokument hat keine @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` die Variable `{name}` kann nicht in einer Variablenbibliothek gespeichert werden: Benennen Sie sie so um, dass sie mit einem Buchstaben oder `_` beginnt, ohne Leerzeichen oder andere Symbole als `-`, `_` und `.` @msg data set `{name}` holds a control character, which a variable library can't hold der Datensatz `{name}` enthält ein Steuerzeichen, das eine Variablenbibliothek nicht enthalten kann diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ae9082d5e3..dc1df4fdb6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6088,6 +6088,7 @@ effect Points Σημεία Export Data Sets… Εξαγωγή συνόλων δεδομένων… Load Variable Library… Φόρτωση βιβλιοθήκης μεταβλητών… Save Variable Library… Αποθήκευση βιβλιοθήκης μεταβλητών… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Η «Εισαγωγή» διαβάζει αρχείο προέλευσης δεδομένων με κατάληξη .csv, .tsv, .txt ή .xml @msg a variable library holds text variables, and the document has none μια βιβλιοθήκη μεταβλητών περιέχει μεταβλητές κειμένου και το έγγραφο δεν έχει καμία @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` η μεταβλητή `{name}` δεν μπορεί να αποθηκευτεί σε βιβλιοθήκη μεταβλητών: μετονομάστε την ώστε να ξεκινά με γράμμα ή `_`, χωρίς κενά ή σύμβολα εκτός από `-`, `_` και `.` @msg data set `{name}` holds a control character, which a variable library can't hold το σύνολο δεδομένων `{name}` περιέχει χαρακτήρα ελέγχου, τον οποίο δεν μπορεί να περιέχει μια βιβλιοθήκη μεταβλητών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c5f5e5382c..21b25b332e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6176,6 +6176,7 @@ mark-style Japanese Japonesas Export Data Sets… Exportar conjuntos de datos… Load Variable Library… Cargar biblioteca de variables… Save Variable Library… Guardar biblioteca de variables… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Importar» lee un archivo de origen de datos con extensión .csv, .tsv, .txt o .xml @msg a variable library holds text variables, and the document has none una biblioteca de variables contiene variables de texto y el documento no tiene ninguna @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variable `{name}` no se puede guardar en una biblioteca de variables: cámbiele el nombre para que empiece por una letra o `_`, sin espacios ni símbolos distintos de `-`, `_` y `.` @msg data set `{name}` holds a control character, which a variable library can't hold el conjunto de datos `{name}` contiene un carácter de control, que una biblioteca de variables no puede contener diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1b6a99adf0..1203b47eb0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6099,6 +6099,7 @@ mark-style Japanese Japanilainen Export Data Sets… Vie tietojoukot… Load Variable Library… Lataa muuttujakirjasto… Save Variable Library… Tallenna muuttujakirjasto… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml ”Tuo” lukee tietolähdetiedoston, jonka tunniste on .csv, .tsv, .txt tai .xml @msg a variable library holds text variables, and the document has none muuttujakirjasto sisältää tekstimuuttujia, eikä asiakirjassa ole yhtään @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` muuttujaa `{name}` ei voi tallentaa muuttujakirjastoon: nimeä se uudelleen niin, että se alkaa kirjaimella tai merkillä `_` eikä sisällä välilyöntejä tai muita symboleja kuin `-`, `_` ja `.` @msg data set `{name}` holds a control character, which a variable library can't hold tietojoukko `{name}` sisältää ohjausmerkin, jota muuttujakirjasto ei voi sisältää diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6506935c22..4d07892f35 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6226,6 +6226,7 @@ theme Appearance Apparence Export Data Sets… Exporter des jeux de données… Load Variable Library… Charger une bibliothèque de variables… Save Variable Library… Enregistrer une bibliothèque de variables… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml « Importer » lit un fichier de source de données d’extension .csv, .tsv, .txt ou .xml @msg a variable library holds text variables, and the document has none une bibliothèque de variables contient des variables de texte, et le document n’en a aucune @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variable `{name}` ne peut pas être enregistrée dans une bibliothèque de variables : renommez-la pour qu’elle commence par une lettre ou `_`, sans espaces ni symboles autres que `-`, `_` et `.` @msg data set `{name}` holds a control character, which a variable library can't hold le jeu de données `{name}` contient un caractère de contrôle, qu’une bibliothèque de variables ne peut pas contenir diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 781830cc28..20bb54b8cb 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4263,6 +4263,7 @@ antiAlias Sharp शार्प Save Transparency Flattener Preset ट्रांसपेरेंसी फ़्लैटनर प्रीसेट सेव करें Save Transparency Flattener Preset… ट्रांसपेरेंसी फ़्लैटनर प्रीसेट सेव करें… Save Variable Library… वेरिएबल लाइब्रेरी सेव करें… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "इम्पोर्ट करें" .csv, .tsv, .txt या .xml एक्सटेंशन वाली डेटा स्रोत फ़ाइल पढ़ता है Save… सेव… Saved सेव किए गए SAVED सेव किए गए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e4326a9ff8..ab03cb62c6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6214,6 +6214,7 @@ imageTrace Outline Körvonal Export Data Sets… Adatkészletek exportálása… Load Variable Library… Változókönyvtár betöltése… Save Variable Library… Változókönyvtár mentése… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Az „Importálás” .csv, .tsv, .txt vagy .xml kiterjesztésű adatforrásfájlt olvas be @msg a variable library holds text variables, and the document has none a változókönyvtár szöveges változókat tartalmaz, a dokumentumban pedig nincs ilyen @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` a(z) `{name}` változó nem menthető változókönyvtárba: nevezze át úgy, hogy betűvel vagy `_` jellel kezdődjön, szóközök és a `-`, `_` és `.` jeltől eltérő szimbólumok nélkül @msg data set `{name}` holds a control character, which a variable library can't hold a(z) `{name}` adatkészlet vezérlőkaraktert tartalmaz, amelyet a változókönyvtár nem tartalmazhat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f96f82a849..47569e906f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5851,6 +5851,7 @@ lighting Light Luce Export Data Sets… Esporta set di dati… Load Variable Library… Carica libreria di variabili… Save Variable Library… Salva libreria di variabili… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Importa» legge un file di origine dati con estensione .csv, .tsv, .txt o .xml @msg a variable library holds text variables, and the document has none una libreria di variabili contiene variabili di testo e il documento non ne ha @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variabile `{name}` non può essere salvata in una libreria di variabili: rinominala in modo che inizi con una lettera o `_`, senza spazi né simboli diversi da `-`, `_` e `.` @msg data set `{name}` holds a control character, which a variable library can't hold il set di dati `{name}` contiene un carattere di controllo, che una libreria di variabili non può contenere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 262e6972fe..e5b363d862 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5895,6 +5895,7 @@ lighting Light ライト Export Data Sets… データセットを書き出し… Load Variable Library… 変数ライブラリを読み込み… Save Variable Library… 変数ライブラリを保存… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml 「読み込み」は拡張子が .csv、.tsv、.txt、.xml のデータソースファイルを読み込みます @msg a variable library holds text variables, and the document has none 変数ライブラリにはテキスト変数を保存しますが、このドキュメントにはテキスト変数がありません @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 変数 `{name}` は変数ライブラリに保存できません: 英字または `_` で始まり、スペースや `-`、`_`、`.` 以外の記号を含まない名前に変更してください @msg data set `{name}` holds a control character, which a variable library can't hold データセット `{name}` に変数ライブラリに保存できない制御文字が含まれています diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a04a958a2e..320a9cf8b8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5893,6 +5893,7 @@ imageTrace Outline კონტური Export Data Sets… მონაცემთა ნაკრებების ექსპორტი… Load Variable Library… ცვლადების ბიბლიოთეკის ჩატვირთვა… Save Variable Library… ცვლადების ბიბლიოთეკის შენახვა… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „იმპორტი“ კითხულობს მონაცემთა წყაროს ფაილს გაფართოებით .csv, .tsv, .txt ან .xml @msg a variable library holds text variables, and the document has none ცვლადების ბიბლიოთეკა ტექსტურ ცვლადებს შეიცავს, დოკუმენტს კი არცერთი არ აქვს @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` ცვლადი `{name}` ვერ შეინახება ცვლადების ბიბლიოთეკაში: გადაარქვით სახელი ისე, რომ იწყებოდეს ასოთი ან `_`-ით, ჰარეების და `-`, `_` და `.`-ის გარდა სხვა სიმბოლოების გარეშე @msg data set `{name}` holds a control character, which a variable library can't hold მონაცემთა ნაკრები `{name}` შეიცავს მმართველ სიმბოლოს, რომელსაც ცვლადების ბიბლიოთეკა ვერ შეინახავს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index acd3d0b457..e3f1ad09c0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5812,6 +5812,7 @@ lighting Light 광원 Export Data Sets… 데이터 세트 내보내기… Load Variable Library… 변수 라이브러리 불러오기… Save Variable Library… 변수 라이브러리 저장… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "가져오기"는 확장자가 .csv, .tsv, .txt 또는 .xml인 데이터 소스 파일을 읽습니다 @msg a variable library holds text variables, and the document has none 변수 라이브러리에는 텍스트 변수가 들어가는데 문서에 텍스트 변수가 없습니다 @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 변수 `{name}`은(는) 변수 라이브러리에 저장할 수 없습니다: 문자나 `_`로 시작하고 공백이나 `-`, `_`, `.` 이외의 기호가 없도록 이름을 바꾸세요 @msg data set `{name}` holds a control character, which a variable library can't hold 데이터 세트 `{name}`에 변수 라이브러리에 담을 수 없는 제어 문자가 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ee7a311d10..6e87020841 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8056,6 +8056,7 @@ mark-style Japanese Japans Export Data Sets… Gegevenssets exporteren… Load Variable Library… Variabelenbibliotheek laden… Save Variable Library… Variabelenbibliotheek opslaan… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml ‘Importeren’ leest een gegevensbronbestand met de extensie .csv, .tsv, .txt of .xml @msg a variable library holds text variables, and the document has none een variabelenbibliotheek bevat tekstvariabelen, en het document heeft er geen @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variabele `{name}` kan niet in een variabelenbibliotheek worden opgeslagen: geef haar een naam die met een letter of `_` begint, zonder spaties of andere symbolen dan `-`, `_` en `.` @msg data set `{name}` holds a control character, which a variable library can't hold gegevensset `{name}` bevat een stuurteken, dat een variabelenbibliotheek niet kan bevatten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f41112b942..1d0c64eb1e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6085,6 +6085,7 @@ mark-style Japanese Japońskie Export Data Sets… Eksportuj zestawy danych… Load Variable Library… Wczytaj bibliotekę zmiennych… Save Variable Library… Zapisz bibliotekę zmiennych… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „Importuj” wczytuje plik źródła danych z rozszerzeniem .csv, .tsv, .txt lub .xml @msg a variable library holds text variables, and the document has none biblioteka zmiennych zawiera zmienne tekstowe, a dokument nie ma żadnej @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` nie można zapisać zmiennej `{name}` w bibliotece zmiennych: zmień jej nazwę tak, aby zaczynała się literą lub `_`, bez spacji i symboli innych niż `-`, `_` i `.` @msg data set `{name}` holds a control character, which a variable library can't hold zestaw danych `{name}` zawiera znak sterujący, którego biblioteka zmiennych nie może zawierać diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0fcefc1e1e..d6d66e60ee 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1040,6 +1040,7 @@ antiAlias Sharp Nítido Export Data Sets… Exportar Conjuntos de Dados… Load Variable Library… Carregar Biblioteca de Variáveis… Save Variable Library… Salvar Biblioteca de Variáveis… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "Importar" lê um arquivo de fonte de dados com extensão .csv, .tsv, .txt ou .xml @msg a variable library holds text variables, and the document has none uma biblioteca de variáveis contém variáveis de texto, e o documento não tem nenhuma @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` a variável `{name}` não pode ser salva em uma biblioteca de variáveis: renomeie-a para começar com uma letra ou `_`, sem espaços nem símbolos além de `-`, `_` e `.` @msg data set `{name}` holds a control character, which a variable library can't hold o conjunto de dados `{name}` contém um caractere de controle, que uma biblioteca de variáveis não pode conter diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2a7c29582c..3b26fb5937 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5838,6 +5838,7 @@ lighting Light Свет Export Data Sets… Экспортировать наборы данных… Load Variable Library… Загрузить библиотеку переменных… Save Variable Library… Сохранить библиотеку переменных… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Импорт» читает файл источника данных с расширением .csv, .tsv, .txt или .xml @msg a variable library holds text variables, and the document has none библиотека переменных содержит текстовые переменные, а в документе их нет @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` переменную `{name}` нельзя сохранить в библиотеке переменных: переименуйте её так, чтобы имя начиналось с буквы или `_` и не содержало пробелов и символов, кроме `-`, `_` и `.` @msg data set `{name}` holds a control character, which a variable library can't hold набор данных `{name}` содержит управляющий символ, который не может храниться в библиотеке переменных diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2d212bb0af..f7484f3d57 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6083,6 +6083,7 @@ theme Appearance Utseende Export Data Sets… Exportera datauppsättningar… Load Variable Library… Läs in variabelbibliotek… Save Variable Library… Spara variabelbibliotek… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml ”Importera” läser en datakällfil med filändelsen .csv, .tsv, .txt eller .xml @msg a variable library holds text variables, and the document has none ett variabelbibliotek innehåller textvariabler, och dokumentet har inga @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variabeln `{name}` kan inte sparas i ett variabelbibliotek: byt namn på den så att den börjar med en bokstav eller `_`, utan mellanslag eller andra symboler än `-`, `_` och `.` @msg data set `{name}` holds a control character, which a variable library can't hold datauppsättningen `{name}` innehåller ett kontrolltecken, som ett variabelbibliotek inte kan innehålla diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d31ea8a542..96b346eed9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6336,6 +6336,7 @@ theme Appearance Görünüm Kashidas Keşide Load Variable Library… Değişken Kitaplığı Yükle… Save Variable Library… Değişken Kitaplığını Kaydet… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "İthalat" uzantısı .csv, .tsv, .txt veya .xml olan bir veri kaynağı dosyasını okur @msg a variable library holds text variables, and the document has none değişken kitaplığı metin değişkenleri içerir ve belgede hiç metin değişkeni yok @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` `{name}` değişkeni değişken kitaplığına kaydedilemiyor: adını bir harf veya `_` ile başlayacak, boşluk ya da `-`, `_` ve `.` dışında simge içermeyecek şekilde değiştirin @msg data set `{name}` holds a control character, which a variable library can't hold `{name}` veri kümesi, değişken kitaplığının tutamayacağı bir denetim karakteri içeriyor diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9fe962d27e..ac3ac3a707 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5831,6 +5831,7 @@ lighting Light Світло Export Data Sets… Експортувати набори даних… Load Variable Library… Завантажити бібліотеку змінних… Save Variable Library… Зберегти бібліотеку змінних… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Імпорт» читає файл джерела даних із розширенням .csv, .tsv, .txt або .xml @msg a variable library holds text variables, and the document has none бібліотека змінних містить текстові змінні, а в документі їх немає @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` змінну `{name}` не можна зберегти в бібліотеці змінних: перейменуйте її так, щоб ім’я починалося з літери або `_` і не містило пробілів і символів, крім `-`, `_` і `.` @msg data set `{name}` holds a control character, which a variable library can't hold набір даних `{name}` містить керівний символ, який бібліотека змінних не може містити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index c8fd7e1ef4..5e011fd7a6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5836,6 +5836,7 @@ theme Appearance Giao diện Export Data Sets… Xuất tập dữ liệu… Load Variable Library… Tải thư viện biến số… Save Variable Library… Lưu thư viện biến số… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "Nhập" đọc tệp nguồn dữ liệu có phần mở rộng .csv, .tsv, .txt hoặc .xml @msg a variable library holds text variables, and the document has none thư viện biến số chứa các biến số văn bản, và tài liệu không có biến số văn bản nào @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` không thể lưu biến số `{name}` vào thư viện biến số: hãy đổi tên để bắt đầu bằng một chữ cái hoặc `_`, không có khoảng trắng hay ký hiệu nào ngoài `-`, `_` và `.` @msg data set `{name}` holds a control character, which a variable library can't hold tập dữ liệu `{name}` chứa ký tự điều khiển mà thư viện biến số không thể chứa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f61830a3c0..0d7d1839e3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6073,6 +6073,7 @@ lighting Light 光源 Export Data Sets… 导出数据集… Load Variable Library… 载入变量库… Save Variable Library… 保存变量库… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml “导入”读取扩展名为 .csv、.tsv、.txt 或 .xml 的数据源文件 @msg a variable library holds text variables, and the document has none 变量库包含文本变量,而文档中没有文本变量 @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 无法将变量 `{name}` 保存到变量库中:请重命名,使其以字母或 `_` 开头,且不含空格或 `-`、`_`、`.` 以外的符号 @msg data set `{name}` holds a control character, which a variable library can't hold 数据集 `{name}` 包含变量库无法保存的控制字符 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d1de78624d..1fbfd80977 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5907,6 +5907,7 @@ lighting Light 光源 Export Data Sets… 匯出資料集… Load Variable Library… 載入變數資料庫… Save Variable Library… 儲存變數資料庫… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml 「匯入」讀取副檔名為 .csv、.tsv、.txt 或 .xml 的資料來源檔案 @msg a variable library holds text variables, and the document has none 變數資料庫包含文字變數,但文件中沒有文字變數 @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 無法將變數 `{name}` 儲存到變數資料庫:請重新命名,使其以字母或 `_` 開頭,且不含空格或 `-`、`_`、`.` 以外的符號 @msg data set `{name}` holds a control character, which a variable library can't hold 資料集 `{name}` 包含變數資料庫無法儲存的控制字元 diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 3ab5fc2484..a7559e927e 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -321,6 +321,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { delete_active_dataset(app); } ui.separator(); + // One file dialog for either kind of data source; the extension picks the reader. + if widgets::menu_item(ui, tl!("Import…"), true, false) { + crate::picks::button(app, import_data_source); + } if widgets::menu_item(ui, tl!("Import Data Sets…"), true, false) { crate::picks::button(app, import_datasets); } @@ -344,6 +348,23 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Variables panel: Import… opens one file dialog for a CSV, TSV, TXT or XML file and runs +/// `variable.import` on the chosen file, which reads it by its extension. +fn import_data_source(app: &mut VectorcraftApp) { + let pick = crate::FilePick { + filters: vec![ + crate::FilePick::filter("Data sources", &["csv", "tsv", "txt", "xml"]), + crate::FilePick::filter("CSV", &["csv", "tsv", "txt"]), + crate::FilePick::filter("XML", &["xml"]), + ], + ..Default::default() + }; + let Some(path) = crate::picks::open(app, &pick) else { return }; + if let Err(e) = app.run("variable.import", json!({"path": path})) { + app.status(e); + } +} + /// Variables panel: Import Data Sets… opens a file dialog for a comma- or tab-separated file and runs `dataset.import` on the chosen file. fn import_datasets(app: &mut VectorcraftApp) { let pick = crate::FilePick { filters: vec![crate::FilePick::filter("CSV", &["csv", "tsv", "txt"])], ..Default::default() }; @@ -469,6 +490,8 @@ mod tests { "Update Data Set", "Rename Data Set…", "Delete Data Set", + "Import…", + "Import Data Sets…", "Load Variable Library…", "Save Variable Library…", "Select Bound Object", diff --git a/docs/mcp.md b/docs/mcp.md index b89c6481fd..b5a143d316 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3498,6 +3498,11 @@ already walks Image Trace. Short agent entry points: image value that isn't a file's absolute path, and past `variable.loadLibrary`'s caps (256 variables, 1,000 data sets, 8 MiB). Without `path` the reply is `{xml, variables, datasets}`; with it, the file is written and the reply is `{path, variables, datasets}`. +- Import a data source: `variable.import {path}` (the Variables panel menu's Import…) reads a data source file by its + extension, in any case: a `.csv`, `.tsv` or `.txt` file as `dataset.import {path}` reads it, and an `.xml` file as + `variable.loadLibrary {path}` reads it, with that command's refusals, undo step and reply, plus `format` (`csv` or + `xml`). A path with any other extension, or none, is refused before the file is read. The panel menu's Import Data + Sets… and Load Variable Library… stay. - Batch: `action.batch {commands, source?: folder|datasets, folder?, destination?: none|saveAndClose|folder, destinationFolder?, overrideOpen?, overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an action on every file in a folder or every data set (the Actions panel menu's Batch…). Override Save and Override diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8b5cb97e8..f0faedb7fa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -830,6 +830,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: Import… in the Variables panel menu (`variable.import`) opens one file dialog for a data source and reads it by its extension: a CSV, TSV or TXT file as Import Data Sets… reads it, and an XML file as Load Variable Library… reads it. Other extensions are refused. - 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. - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). From 5ed83e0daa20af6d7520685b4e8052503da5c4e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:39:46 -0800 Subject: [PATCH 20/63] Gradients: an aligned row of a graph design's art alone is still checked by paint.editGradient With only the art of a graph design in a series given, paint.editGradient returned before it checked an explicit aligned item, so a row the art lacks, or one no other object has, was accepted instead of refused. The row is now checked first, as paint.setFill does. --- crates/engine/src/cmd/gradient.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index b7eb7235f6..00575695d4 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -579,12 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { }; let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; + let of = super::appearance::reference_of(s, p, item, C)?; // Only design art was given or selected: nothing changes, the defaults and the remembered paint included. if selected && ids.is_empty() { + // An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error. + edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?; return Ok(json!({"ids": []})); } let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); - let of = super::appearance::reference_of(s, p, item, C)?; let shown_at = super::appearance::first_edited(s, item, of, &ids); // The objects returned: with a design's art, those with a row equal to the art's. let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| { From 6d87660fd07306c1ac0e304032ad62dbafce3a33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:55:20 -0800 Subject: [PATCH 21/63] 3D (Classic): the lighting sphere moves, adds and deletes lights on the Lighting tab The Lighting tab of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) now shows the lighting sphere, in the 3D and Materials panel and in the options dialog, while the surface is Diffuse or Plastic. A light drags to a new Rotation and Height, a press selects it, and the button below the sphere moves it behind or in front of the object. Add Light places a new light at the front center and Delete Light keeps at least one light. The classic effects shade without light color, so their suns are drawn white. --- crates/ui-egui/src/dialogs/revolve/tests.rs | 45 +++++++--- crates/ui-egui/src/dialogs/revolve_lights.rs | 19 ++-- crates/ui-egui/src/dialogs/three_d_classic.rs | 14 +-- crates/ui-egui/src/panels/tests_three_d.rs | 86 ++++++++++++++++++- docs/effects-parity.md | 2 +- docs/three-d.md | 11 ++- 6 files changed, 149 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index fd802f83f0..b298752a5e 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -52,6 +52,22 @@ impl Harness { } } + /// Scrolls the dialog's body to its end with the wheel over `text`, and lets the scroll finish. + fn scroll_to_end(&mut self, text: &str) { + let p = self.rect(text).center(); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -4000.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + self.frame(vec![Event::PointerMoved(p), wheel]); + for _ in 0..60 { + self.frame(vec![]); + } + } + fn rect(&self, text: &str) -> Rect { self.texts.iter().find(|(s, _)| s == text).map(|(_, r)| *r).unwrap_or_else(|| panic!("missing text {text:?}")) } @@ -338,17 +354,12 @@ fn classic_extrude_bevel_shows_its_options_and_applies_as_one_step() { } h.click(h.rect("Lighting").center()); h.settle(); - for text in [ - "Surface", - "Plastic", - "Light Intensity", - "Ambient Light", - "Highlight Intensity", - "Highlight Size", - "Blend Steps", - "Shading Color", - "Draw Hidden Faces", - ] { + for text in ["Surface", "Plastic", "Move Light to Back", "Light Intensity"] { + h.rect(text); + } + // The lighting sphere makes the tab taller than the dialog's body, which scrolls. + h.scroll_to_end("Light Intensity"); + for text in ["Ambient Light", "Highlight Intensity", "Highlight Size", "Blend Steps", "Shading Color", "Draw Hidden Faces"] { h.rect(text); } assert!(h.ctx.read_response(Id::unique(("revolve-reset", "highlightSize"))).unwrap().enabled()); @@ -399,7 +410,11 @@ fn classic_revolve_shows_its_options_and_applies_as_one_step() { } h.click(h.rect("Lighting").center()); h.settle(); - for text in ["Surface", "Plastic", "Light Intensity", "Ambient Light", "Highlight Size", "Blend Steps", "Shading Color"] { + for text in ["Surface", "Plastic", "Move Light to Back", "Light Intensity"] { + h.rect(text); + } + h.scroll_to_end("Light Intensity"); + for text in ["Ambient Light", "Highlight Size", "Blend Steps", "Shading Color"] { h.rect(text); } assert!(!h.texts.iter().any(|(t, _)| t == "Draw Hidden Faces"), "every face is drawn"); @@ -437,7 +452,11 @@ fn classic_rotate_shows_its_options_and_applies_as_one_step() { assert!(!h.texts.iter().any(|(t, _)| t == "Object" || t == "Depth" || t == "Angle"), "no Object tab"); h.click(h.rect("Lighting").center()); h.settle(); - for text in ["Surface", "Diffuse", "Light Intensity", "Ambient Light", "Blend Steps", "Shading Color"] { + for text in ["Surface", "Diffuse", "Move Light to Back", "Light Intensity"] { + h.rect(text); + } + h.scroll_to_end("Light Intensity"); + for text in ["Ambient Light", "Blend Steps", "Shading Color"] { h.rect(text); } assert!( diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 1a4116b7ee..3d522b624a 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -1,6 +1,8 @@ //! The lighting widget on the 3D and Materials panel's Lighting tab for Extrude & Bevel, Revolve, -//! Inflate and Rotate: a sphere that shows each of the effect's lights +//! Inflate and Rotate, and on the Lighting tab of the 3D (Classic) effects in both the panel and the +//! options dialog: a sphere that shows each of the effect's lights //! at its Rotation and Height, a filled sun in front of the object and a hollow one behind it. +//! The 3D (Classic) effects' lights have no color, so their suns are white. //! Dragging a light moves it on its side of the object, a press selects it in the list of lights, //! and the button below the sphere moves the selected light to the back or the front of the object. //! Each light takes the keyboard focus, where the arrow keys move it, and has a name for screen @@ -82,15 +84,20 @@ fn round(n: f64) -> f64 { } /// The effect's lights: each light of its list, or its single light, with the effect's defaults for -/// the settings a light leaves out or the selected effects hold with different values (null). +/// the settings a light leaves out or the selected effects hold with different values (null). A 3D +/// (Classic) effect's lights are white whatever color a list light carries, since it shades +/// without light color. pub(crate) fn lights(d: &Dialog) -> Vec { - let defaults = vectorcraft_effects::default_params(&d.str("__effect")).unwrap_or(json!({})); + let effect = d.str("__effect"); + let colored = !vectorcraft_effects::is_classic_three_d(&effect); + let defaults = vectorcraft_effects::default_params(&effect).unwrap_or(json!({})); let list = explicit_lights(d).cloned().unwrap_or_else(|| vec![light_record(d)]); list.iter() .map(|light| { let value = |key: &str, field: &str| light.get(key).filter(|v| !v.is_null()).or_else(|| defaults.get(field)).cloned().unwrap_or(Value::Null); - let [r, g, b] = value("color", "lightColor") + let color = if colored { value("color", "lightColor") } else { Value::Null }; + let [r, g, b] = color .as_str() .filter(|s| s.len() == 7 && s.starts_with('#')) .and_then(vectorcraft_color::Color::from_hex) @@ -143,10 +150,12 @@ pub(super) fn show(ui: &mut egui::Ui, d: &mut Dialog) { let order = (0..lights.len()).filter(|&i| i != current).chain([current]); let mut moved = None; let enabled = ui.is_enabled(); + // The panel and a 3D (Classic) options dialog can both show the sphere at once. + let panel = d.bool("__panel"); for index in order { let light = lights.get(index).copied().unwrap_or(first); let at = center + light.offset() * radius; - let id = Id::unique(("three-d-lighting-widget", index)); + let id = Id::unique(("three-d-lighting-widget", panel, index)); let response = ui.interact(Rect::from_center_size(at, Vec2::splat((SUN + 4.0) * 2.0)), id, Sense::click_and_drag()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, enabled, light.name(index))); // A light the pointer took, or that the keyboard focus reached, becomes the selected light and diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 22c18df97e..22bfee1b02 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -1,7 +1,7 @@ //! The own controls of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) in the //! compact 3D dialog: the extrude and bevel options, or the revolve options, on the Object tab -//! (Rotate (Classic) has none), and the surface with its lights, highlight, blend steps, shading -//! color and Preserve Spot Colors on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D +//! (Rotate (Classic) has none), and the surface with its lighting sphere, lights, highlight, blend +//! steps, shading color and Preserve Spot Colors on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D //! effect shares. use serde_json::{Value, json}; @@ -40,16 +40,18 @@ pub(super) fn revolve_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { choice(ui, d, "edge", tl!("Axis side"), &sides); } -/// The surface, then for Diffuse and Plastic the lights, Ambient Light, the highlight (Plastic -/// only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps, Shading Color and -/// Preserve Spot Colors (unavailable while Shading Color is Custom); Draw Hidden Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and -/// Rotate (Classic)'s plane is seen from either side). +/// The surface, then for Diffuse and Plastic the lighting sphere, the lights, Ambient Light, the +/// highlight (Plastic only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps, +/// Shading Color and Preserve Spot Colors (unavailable while Shading Color is Custom); Draw Hidden +/// Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and Rotate +/// (Classic)'s plane is seen from either side). The sphere shows in the dialog as well as in the panel. pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) { let id = d.str("__effect"); let effect = if id == CLASSIC_ROTATE { CLASSIC_ROTATE } else { CLASSIC_EXTRUDE }; choice(ui, d, "surface", tl!("Surface"), &options_of(effect, "surface")); let surface = d.str("surface"); ui.add_enabled_ui(surface == "diffuse" || surface == "plastic", |ui| { + super::revolve_lights::show(ui, d); light_list(ui, d); let mut selected = selected_light(d); let before = light_record(&selected); diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 6146bc4852..b125e23f29 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -839,9 +839,15 @@ fn quick_actions_show_on_the_object_tab_only() { /// An app with an Extrude & Bevel square given `params`, and the panel on its Lighting tab with the /// accessibility tree on. fn lighting_app(params: Value) -> (VectorcraftApp, egui::Context) { + lighting_app_of("threeD.extrude", params) +} + +/// An app with a square given 3D effect `effect` with `params`, and the panel on its Lighting tab +/// with the accessibility tree on. +fn lighting_app_of(effect: &str, params: Value) -> (VectorcraftApp, egui::Context) { use crate::panels::tests_appearance::{click, frame_events, text_rect}; let mut app = app(); - app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": params})).unwrap(); + app.run("effect.apply", json!({"effect": effect, "item": null, "params": params})).unwrap(); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); ctx.enable_accesskit(); @@ -1026,6 +1032,84 @@ fn the_arrow_keys_move_the_light_pressed_last() { assert_eq!(rotations, [json!(0.0), json!(-179.0)]); } +/// The Lighting tab of Extrude & Bevel (Classic) has the lighting sphere: dragging its light is one +/// undo step, the button below it moves the light behind the object, Add Light adds a light at the +/// front center of the sphere, and Delete Light removes the selected light but never the last one. +#[test] +fn the_classic_lighting_tab_has_the_lighting_sphere() { + use crate::dialogs::revolve_lights::RADIUS; + use crate::panels::tests_appearance::{click, frame_events, text_rect}; + use vectorcraft_effects::CLASSIC_EXTRUDE; + let (mut app, ctx) = lighting_app_of(CLASSIC_EXTRUDE, json!({})); + let (name, from) = light_node(&mut app, &ctx, 1); + assert_eq!(name, "Light 1: Rotation 125.3°, Height 30.0°"); + let light = crate::dialogs::revolve_lights::lights(&crate::state::Dialog::new( + "x", + json!({"__effect": CLASSIC_EXTRUDE, "lightRotation": vectorcraft_three_d::DEFAULT_LIGHT.0, "lightHeight": 30.0}), + ))[0]; + let center = from - light.offset() * RADIUS; + let history = undo_len(&app); + let rim = center + egui::vec2(RADIUS, 0.0); + for event in [pointer(from, None), pointer(from, Some(true)), pointer(rim, None)] { + frame_events(&ctx, &mut app, vec![event], show); + } + assert_eq!(merged_light(&app), (0.0, 0.0), "the light follows the pointer while it is down"); + assert_eq!(undo_len(&app), history); + frame_events(&ctx, &mut app, vec![pointer(rim, Some(false))], show); + frame_events(&ctx, &mut app, vec![], show); + assert_eq!(undo_len(&app), history + 1); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Move Light to Back").center(), show); + assert_eq!(undo_len(&app), history + 2); + assert_eq!(effect(&app).1["lightBehind"], json!(true)); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Add Light").center(), show); + assert_eq!(undo_len(&app), history + 3); + let (name, _) = light_node(&mut app, &ctx, 2); + assert_eq!(name, "Light 2: Rotation 0.0°, Height 90.0°", "a new light is at the front center"); + let count = |app: &VectorcraftApp| effect(app).1["lights"].as_array().map_or(1, Vec::len); + assert_eq!(count(&app), 2); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Delete Light").center(), show); + assert_eq!(count(&app), 1); + assert_eq!(undo_len(&app), history + 4); + let (name, _) = light_node(&mut app, &ctx, 1); + assert_eq!(name, "Light 1: Rotation 0.0°, Height 0.0°, Light behind the object", "the selected light was deleted"); + // One light stays: Delete Light does nothing then. + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Delete Light").center(), show); + assert_eq!(count(&app), 1); + assert_eq!(undo_len(&app), history + 4); +} + +/// The 3D (Classic) options dialog shows the lighting sphere on its Lighting tab too, and the +/// sphere draws a 3D (Classic) effect's lights white, since those effects shade without light color. +#[test] +fn the_classic_options_dialog_has_the_lighting_sphere_with_white_lights() { + use crate::panels::tests_appearance::frame_events; + use vectorcraft_effects::{CLASSIC_REVOLVE, EXTRUDE}; + let mut app = app(); + app.run("effect.dialog", json!({"effect": CLASSIC_REVOLVE, "item": null})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("__gizmo".into(), json!("light")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let dialog = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], dialog); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialog(&mut app, ui)); + out.textures_delta.clear(); + let nodes: Vec<_> = out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default(); + assert!( + nodes.iter().any(|n| n.role() == egui::accesskit::Role::Slider && n.label() == Some("Light 1: Rotation 125.3°, Height 30.0°")), + "the dialog shows the sphere" + ); + let red = json!([{"color": "#ff0000", "rotation": 0.0, "height": 30.0}]); + let color = + |effect: &str| crate::dialogs::revolve_lights::lights(&crate::state::Dialog::new("x", json!({"__effect": effect, "lights": red})))[0].color; + assert_eq!(color(CLASSIC_REVOLVE), egui::Color32::WHITE); + assert_eq!(color(EXTRUDE), egui::Color32::from_rgb(255, 0, 0)); +} + #[test] fn changed_settings_lists_only_new_values() { let before = json!({"depth": 50.0, "cap": true, "bevel": "none"}); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 290148b89d..41758c9e75 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,7 +181,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); Map Art: none | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/three-d.md b/docs/three-d.md index 2861bee0b7..b07790d7be 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -342,8 +342,15 @@ is drawn larger, above the others. The widget sends the same settings as the Rotation, Height and Light behind the object controls (`effect.setParams`); there is no command of its own. The sphere's look, the 0.1° rounding and the arrow keys -are VectorCraft's own. The options dialogs keep the light rings on the artboard instead, and the Lighting tab -of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) has no lighting widget. +are VectorCraft's own. The options dialogs of Extrude & Bevel, Revolve, Inflate and Rotate keep the light rings +on the artboard instead. + +The Lighting tab of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) has the same sphere, in +the options dialog as well as in the panel, while the surface is Diffuse or Plastic, as the archived +[lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272) of +the classic 3D dialogs describe. Their lights have no color, so every sun is white. The light rings on the +artboard stay available in the dialog. **Add Light** adds a light at the front center of the sphere (Rotation +0°, Height 90°), and **Delete Light** removes the selected light and is unavailable while one light is left. ### Light settings From 147b744845d152ebca8bcd7adcb7d3143d98a6e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:10:52 -0800 Subject: [PATCH 22/63] Graph Data: dragging a column's edge sets that column's width In the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width, in the dialog or set as the `width` field, still sets every column. The dialog keeps the dragged widths in a `widths` field by column. --- crates/ui-egui/src/dialogs.rs | 5 + crates/ui-egui/src/dialogs/graph_data.rs | 237 +++++++++++++++++++---- docs/target-app-parity.md | 1 + 3 files changed, 209 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d958f18c1b..b67a27fa00 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -584,6 +584,7 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -598,10 +599,14 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { crate::prefs_dialog::note_set(d, &field, &value); } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); + let graph = (d.kind == graph_data::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { dxf_options::note_set(d, &field); } + if let Some(field) = graph { + graph_data::note_set(d, &field); + } } /// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ecfb0c303e..935ce60bd9 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -7,13 +7,15 @@ //! don't move the caret in the entry box). Pasting tab- or line-separated text fills the cells from //! the picked one. Import Data reads a tab-separated text file, Transpose row/column swaps rows and //! columns, Switch x/y swaps a scatter graph's y and x columns, Cell Style sets the number of -//! decimals the sheet shows and its columns' width, and Revert reads the graph's data again. Apply -//! (`graph.setData` with its series, categories and rows) redraws the graph and leaves the window -//! open. +//! decimals the sheet shows and the width of every column, dragging a column's right edge sets that +//! column's width (in whole digits, 0 to 20, as Cell Style), and Revert reads the graph's data +//! again. Apply (`graph.setData` with its series, categories and rows) redraws the graph and leaves +//! the window open. //! //! Fields: `grid` (rows of cell texts), `sel` ([row, column]), `entry` (the picked cell's text -//! being edited), `decimals` (null: as typed), `width` (digits), `__graph` (the graph's id) and -//! `__scatter`. +//! being edited), `decimals` (null: as typed), `width` (digits), `widths` (a column's own width in +//! digits by its index, null or missing: `width`; setting `width` empties it), `__graph` (the graph's +//! id) and `__scatter`. use serde_json::{Value, json}; use vectorcraft_doc::{MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES}; @@ -62,7 +64,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let entry = cell(&grid, 0, 1); app.ui.dialog = Some(Dialog::new( KIND, - json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "__graph": id, "__scatter": scatter }), + json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "widths": [], "__graph": id, "__scatter": scatter }), )); Ok(Value::Null) } @@ -355,7 +357,7 @@ fn import(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { } /// Draw the graph-data sheet: keyboard cell movement, block paste, import, transpose, switch-x/y -/// and revert actions, decimals and column width, and only the cells in view. +/// and revert actions, decimals and column widths, and only the cells in view. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let entry_id = egui::Id::unique("graph-data-entry"); if ui.memory(|m| m.has_focus(entry_id)) { @@ -436,36 +438,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::dim_label(ui, tl!("Column Width:")); let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7); if ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)).changed() { - d.fields.insert("width".into(), json!(w)); + set_width(d, w); } }); ui.add_space(6.0); - let at = sel(d); - let (rows, cols) = extent(d, at); - let decimals = d.fields.get("decimals").and_then(Value::as_u64); - let w = (d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0); - let mut clicked = None; - widgets::list_box(ui, |ui| { - // Only the cells in view are drawn: a graph's sheet can be 10,001 × 257. - egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| { - let (cw, ch) = (w + 1.0, ROW_H); - ui.set_min_size(egui::vec2(cols as f32 * cw, rows as f32 * ch)); - let origin = ui.max_rect().min; - let span = |lo: f32, hi: f32, size: f32, n: usize| ((lo / size).floor().max(0.0) as usize, ((hi / size).ceil().max(0.0) as usize).min(n)); - let (r0, r1) = span(view.min.y, view.max.y, ch, rows); - let (c0, c1) = span(view.min.x, view.max.x, cw, cols); - for r in r0..r1 { - for c in c0..c1 { - let rect = egui::Rect::from_min_size(origin + egui::vec2(c as f32 * cw, r as f32 * ch), egui::vec2(w, ch - 1.0)); - let text = shown(cell_at(d, r, c), decimals); - let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate(); - if ui.put(rect, b).clicked() && (r, c) != (0, 0) { - clicked = Some((r, c)); - } - } - } - }); - }); + let (clicked, resized) = sheet(ui, d); + if let Some((c, n)) = resized + && n != col_digits(d, c) + { + set_col_digits(d, c, n); + } if let Some(to) = clicked { pick(d, to); ui.memory_mut(|mem| mem.request_focus(entry_id)); @@ -479,6 +461,123 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// Cell Style's Column Width in digits. +fn width(d: &Dialog) -> u64 { + d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) +} + +/// A column's width in digits: its own when its edge was dragged, else Cell Style's. +fn col_digits(d: &Dialog, c: usize) -> u64 { + d.fields.get("widths").and_then(|w| w.get(c)).and_then(Value::as_u64).unwrap_or_else(|| width(d)).min(MAX_WIDTH) +} + +/// Cell Style's Column Width: every column `n` digits wide, the ones given their own width too. +fn set_width(d: &mut Dialog, n: u64) { + d.fields.insert("width".into(), json!(n.min(MAX_WIDTH))); + note_set(d, "width"); +} + +/// `ui.dialog.set` set `field`: a Column Width sets every column, as Cell Style's does. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if field == "width" { + d.fields.insert("widths".into(), json!([])); + } +} + +/// Set column `c`'s own width in digits (at most MAX_WIDTH). +fn set_col_digits(d: &mut Dialog, c: usize, n: u64) { + if c >= MAX_COLS { + return; + } + let widths = d.fields.entry("widths").or_insert_with(|| json!([])); + if !widths.is_array() { + *widths = json!([]); + } + let Some(widths) = widths.as_array_mut() else { return }; + if widths.len() <= c { + widths.resize(c + 1, Value::Null); + } + if let Some(w) = widths.get_mut(c) { + *w = json!(n.min(MAX_WIDTH)); + } +} + +/// A column `n` digits wide, in points on the sheet. +fn digits_px(n: u64) -> f32 { + (n.min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0) +} + +/// The width in digits nearest to `px` points, within Cell Style's 0 to MAX_WIDTH. +fn px_digits(px: f32) -> u64 { + if px.is_finite() { ((px - 10.0) / 7.0).round().clamp(0.0, MAX_WIDTH as f32) as u64 } else { 0 } +} + +/// The id of column `c`'s right edge on the sheet. +fn edge_id(c: usize) -> egui::Id { + egui::Id::unique(("graph-data-column-edge", c)) +} + +/// The cell clicked on the sheet ([row, column]), and the column whose edge is dragged with its width +/// in digits. +type SheetInput = (Option<(usize, usize)>, Option<(usize, u64)>); + +/// Draw the sheet's cells in view, each column at its own width. Returns the cell clicked, and the +/// column whose right edge is being dragged with the width in digits the pointer gives it. +fn sheet(ui: &mut egui::Ui, d: &Dialog) -> SheetInput { + let at = sel(d); + let (rows, cols) = extent(d, at); + let decimals = d.fields.get("decimals").and_then(Value::as_u64); + // Each column's left edge, and the sheet's width last: a column is its width and a 1-point gap. + let mut xs = Vec::with_capacity(cols + 1); + let mut x = 0.0; + xs.push(x); + for c in 0..cols { + x += digits_px(col_digits(d, c)) + 1.0; + xs.push(x); + } + let left = |c: usize| xs.get(c).copied().unwrap_or(x); + let (mut clicked, mut resized) = (None, None); + widgets::list_box(ui, |ui| { + // Only the cells in view are drawn: a graph's sheet can be 10,001 × 257. + egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| { + let ch = ROW_H; + ui.set_min_size(egui::vec2(x, rows as f32 * ch)); + let origin = ui.max_rect().min; + let (r0, r1) = ((view.min.y / ch).floor().max(0.0) as usize, ((view.max.y / ch).ceil().max(0.0) as usize).min(rows)); + // The columns that reach into the view. + let c0 = (0..cols).find(|&c| left(c + 1) > view.min.x).unwrap_or(cols); + let c1 = (c0..cols).find(|&c| left(c) >= view.max.x).unwrap_or(cols); + for r in r0..r1 { + for c in c0..c1 { + let size = egui::vec2(left(c + 1) - left(c) - 1.0, ch - 1.0); + let rect = egui::Rect::from_min_size(origin + egui::vec2(left(c), r as f32 * ch), size); + let text = shown(cell_at(d, r, c), decimals); + let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate(); + if ui.put(rect, b).clicked() && (r, c) != (0, 0) { + clicked = Some((r, c)); + } + } + } + // A column's right edge, over the rows in view: dragging it sets that column's width. The + // edge being dragged stays in the loop when it leaves the view, so the drag goes on. + let (top, bottom) = (origin.y + r0 as f32 * ch, origin.y + r1 as f32 * ch); + let dragged = ui.ctx().dragged_id().and_then(|id| (0..cols).find(|&c| edge_id(c) == id)).filter(|c| !(c0..c1).contains(c)); + for c in (c0..c1).chain(dragged) { + let gap = origin.x + left(c + 1) - 0.5; + let edge = egui::Rect::from_x_y_ranges(gap - 3.0..=gap + 3.0, top..=bottom); + let h = ui.interact(edge, edge_id(c), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeColumn); + if h.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn); + if let Some(p) = h.interact_pointer_pos() { + resized = Some((c, px_digits(p.x - origin.x - left(c)))); + } + } + } + }); + }); + (clicked, resized) +} + #[cfg(test)] mod tests { use serde_json::json; @@ -685,6 +784,76 @@ mod tests { assert_eq!(sel(app.ui.dialog.as_ref().unwrap()), (0, 1), "Up"); } + /// Dragging a column's right edge shows the column-resize pointer and sets that column's width in + /// whole digits, the columns after it moving along; the other columns keep Cell Style's width. + /// A drag past 20 digits stops at 20, and Cell Style's Column Width then sets every column. + #[test] + fn dragging_a_column_edge_sets_that_columns_width() { + let (mut app, _) = app_with(",a,b\nQ1,1,2", "column"); + open(&mut app).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.cursor_icon + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn")); + let drag = |app: &mut VectorcraftApp, c: usize, dx: f32| { + let at = edge(c).center(); + frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]); + for step in 1..=4 { + frame(app, vec![egui::Event::PointerMoved(at + egui::vec2(dx * step as f32 / 4.0, 0.0))]); + } + frame(app, vec![button(at + egui::vec2(dx, 0.0), false)]); + frame(app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + }; + let digits = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().unwrap(); + (0..4).map(|c| col_digits(d, c)).collect::>() + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // The window takes its place over the first frames: hover where the edge is now. + let hovered = (0..10).any(|_| frame(&mut app, vec![egui::Event::PointerMoved(edge(1).center())]) == egui::CursorIcon::ResizeColumn); + assert!(hovered, "hovering an edge shows the column-resize pointer"); + let (one, two) = (edge(1).center().x, edge(2).center().x); + // 70 points is 10 digits. + drag(&mut app, 1, 70.0); + assert_eq!(digits(&app), [7, 17, 7, 7]); + let moved = [edge(1).center().x - one, edge(2).center().x - two]; + assert!(moved.iter().all(|m| (m - 70.0).abs() < 0.01), "the columns after it move along: {moved:?}"); + drag(&mut app, 2, -500.0); + assert_eq!(digits(&app), [7, 17, 0, 7], "no narrower than 0 digits"); + drag(&mut app, 0, 500.0); + assert_eq!(digits(&app), [20, 17, 0, 7], "no wider than 20 digits"); + let d = app.ui.dialog.as_mut().unwrap(); + set_width(d, 9); + assert_eq!(digits(&app), [9; 4], "Cell Style sets every column"); + } + + #[test] + fn a_column_width_in_points_maps_to_whole_digits() { + for n in 0..=MAX_WIDTH { + assert_eq!(px_digits(digits_px(n)), n); + } + assert_eq!((px_digits(-40.0), px_digits(1e9), px_digits(f32::NAN)), (0, MAX_WIDTH, 0)); + let mut d = Dialog::new(KIND, json!({ "width": 7 })); + set_col_digits(&mut d, 3, 99); + set_col_digits(&mut d, MAX_COLS, 5); + assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (7, MAX_WIDTH)); + assert_eq!(d.fields["widths"].as_array().map(Vec::len), Some(4), "a column past the sheet is left alone"); + // `width` set by `ui.dialog.set` sets every column too, also when set back to the width before. + for w in [12, 7] { + crate::dialogs::set_field(&mut d, "width".into(), json!(w)); + assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (w, w)); + } + set_col_digits(&mut d, 1, 4); + assert_eq!((col_digits(&d, 1), col_digits(&d, 3)), (4, 7), "a drag after it gives that column its own width"); + } + /// How many buttons (the sheet's cells and the window's own) Graph Data draws in the second of two /// frames in a 1280 × 900 window, for a graph of `categories` rows of `series` values. fn buttons_drawn(categories: usize, series: usize) -> usize { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8b5cb97e8..f6ff79070a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -827,6 +827,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones. Every header cell is a variable, and the rows replace the document's data sets as Data Set 1, Data Set 2 and so on. An import error about a row's values gives the file line the row starts on. - Variables: Import Data Sets… (`dataset.import`) reads a UTF-16 file without a byte-order mark, instead of refusing it, when at least half of its two-byte units hold a NUL byte; it uses the byte order that reads its line breaks. - Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark. + - Graphs: in the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width still sets every column, the dragged ones included ([Adjust decimal digits and column width](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/adjust-column-width.html)). - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. From 0f7c46b04fe56b1a3ffe937ebd570c5189316ae8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:20:32 -0800 Subject: [PATCH 23/63] PDF export: an image whose pixel data can't be read still warns that it couldn't be decoded When the Output settings convert colors, a color image whose pixel data can't be read was left out with the "couldn't be converted" warning, as if it could have been written in its own colors. Such an image can't be written at all, so it is again left out with the "couldn't be decoded" warning, as every other PDF export does. Only an image beyond the decode allowance, or one whose header can't be read, is left out as unconverted. --- crates/pdf/src/images.rs | 36 +++++++++++++++++++---------- crates/pdf/src/tests/compression.rs | 23 ++++++++++++------ 2 files changed, 40 insertions(+), 19 deletions(-) diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index bc4e9641d3..600b45ff88 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -317,8 +317,8 @@ pub(crate) struct Recoded { /// Set when the image's colors are converted to the destination without its ICC profile, /// which can't be read. pub note: Option<&'static str>, - /// Set when the colors were to be converted but the image couldn't be decoded or written - /// with them: the source image, kept as it is, would be in its own colors. + /// Set when the colors were to be converted but the image couldn't be decoded within the + /// allowance or written with them: the source image, kept as it is, would be in its own colors. pub unconverted: bool, } @@ -481,9 +481,10 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB /// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as /// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be -/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB, and -/// is [`Recoded::unconverted`] when `convert` was to convert its colors (any image whose header -/// can't be read, as it may be in color). +/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. When +/// `convert` was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read +/// (it may be in color) or its pixels are beyond the decode allowance; a color image whose pixel +/// data can't be read is not. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -539,7 +540,12 @@ pub(crate) fn recode( if kept(&rule, dims, size, jpeg) && convert.is_none() && source.is_none() { return Recoded { image: None, warning: rule.instead, note: None, unconverted: false }; } - let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return Recoded { unconverted: convert.is_some(), ..keep } }; + // Pixels that can't be read can't be written in their own colors either; ones beyond the + // allowance can. + let mut img = match pixels.map_or_else(|| decoded_within(bytes), Ok) { + Ok(img) => img, + Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, + }; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -572,10 +578,10 @@ pub(crate) fn recode( } srgb } - None => { - let Some(img) = decoded(bytes) else { return Recoded { unconverted: convert.is_some(), ..keep } }; - img - } + None => match decoded_within(bytes) { + Ok(img) => img, + Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, + }, }; } // Pixels that keep their colours keep the profile they are in; converted ones are in the @@ -732,9 +738,15 @@ fn limits() -> image::Limits { /// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded. fn decoded(bytes: &[u8]) -> Option { - let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + decoded_within(bytes).ok() +} + +/// `bytes` decoded like [`decoded`]; on failure, whether the decoder stopped at [`limits`] +/// (`true`) rather than at data it can't read (`false`). +fn decoded_within(bytes: &[u8]) -> Result { + let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| false)?; r.limits(limits()); - r.decode().ok() + r.decode().map_err(|e| matches!(e, image::ImageError::Limits(_))) } /// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index d8055bd0e5..c27d17a736 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -270,12 +270,13 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert!(r.image.is_none(), "kept as it is"); } -/// When the Output settings convert colors, a color image that can't be decoded can't be kept as -/// it is: it is unconverted, and so is one whose header can't be read or one tagged with an ICC -/// profile it is converted from. A grey one, whose pixels aren't converted, and any image without -/// a conversion are kept as they are. +/// When the Output settings convert colors, a color image beyond the decode allowance can't be +/// kept as it is: it is unconverted, and so is one whose header can't be read. A color image +/// whose pixel data can't be read (tagged with an ICC profile it is converted from or not) can't +/// be written in its own colors either, and is kept as it is, as is a grey one, whose pixels +/// aren't converted, and any image without a conversion. #[test] -fn a_color_image_that_cant_be_decoded_for_a_conversion_is_unconverted() { +fn a_color_image_beyond_the_allowance_for_a_conversion_is_unconverted() { use vectorcraft_color::cms::{DISPLAY_P3, GENERIC_CMYK, icc_bytes}; let d = doc(encoded(colour(), ImageFormat::Png), "image/png"); let settings: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})).unwrap(); @@ -291,9 +292,17 @@ fn a_color_image_that_cant_be_decoded_for_a_conversion_is_unconverted() { let cut = |img: DynamicImage| half(encoded(img, ImageFormat::Png)); let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + // `declared_png`'s header declaring RGB pixels (color type 2), with the IHDR chunk's CRC + // written again. + let mut rgb_declared = declared_png(60_000, 60_000); + rgb_declared[25] = 2; + let mut crc = flate2::Crc::new(); + crc.update(&rgb_declared[12..29]); + rgb_declared[29..33].copy_from_slice(&crc.sum().to_be_bytes()); let cases = [ - ("RGB", cut(colour()), true), - ("tagged RGB", half(tagged(&colour(), &p3, ImageFormat::Png)), true), + ("RGB declaring more than the allowance", rgb_declared, true), + ("RGB", cut(colour()), false), + ("tagged RGB", half(tagged(&colour(), &p3, ImageFormat::Png)), false), ("unreadable", vec![1, 2, 3], true), ("grey", cut(colour().grayscale()), false), ("grey declaring more than the allowance", declared_png(60_000, 60_000), false), From 1727c171efcfec046bee0a915527bc3f29eb2073 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:20:42 -0800 Subject: [PATCH 24/63] Image Trace: Noise merges a dark speck into the line beside it, not the ground A region below Noise joined the color it shares the longest border with, so the specks of a thin dark line on a light ground joined the ground and the line broke into dashes. When that color is 10 or more apart from the region's own (Oklab x 100), the region now joins the neighboring color nearest its source pixels, among the colors sharing at least a tenth of the longest border. A single pixel tied between colors still joins by border. 6 Colors and 16 Colors move from Noise 15 to 8, and Black and White Logo from 25 to 5. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/trace/src/params.rs | 12 +- crates/trace/src/pipeline.rs | 5 +- crates/trace/src/quantize.rs | 7 + crates/trace/src/quantize/denoise.rs | 251 +++++++++++++++++++++++++-- crates/trace/src/tests.rs | 10 +- docs/image-trace-adjustments.md | 6 +- docs/image-trace-quality.md | 42 ++++- docs/mcp.md | 6 + docs/target-app-parity.md | 1 + 10 files changed, 314 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 66c9ec8fc4..2e5b2874fa 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 156d6fbef2..7b850fc344 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -82,8 +82,10 @@ pub struct TraceParams { pub paths: f64, /// Corners 0–100: higher keeps more corners. pub corners: f64, - /// Noise: areas smaller than this many pixels are ignored. (Flat Logo mode: areas smaller than - /// `noise / 10` pixels of the source image.) + /// Noise: areas smaller than this many pixels are ignored: each joins the color it shares the + /// longest border with, or, when that color is far from its own, the color beside it nearest + /// its source pixels. (Flat Logo mode: areas smaller than `noise / 10` pixels of the source + /// image.) pub noise: u32, pub method: Method, /// Ignore Color: drop the areas of one colour (no background shape): white, unless @@ -244,10 +246,10 @@ pub fn preset(name: &str) -> Option { "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), - "6 colors" => color(6, 50.0, 50.0, 15, Method::Abutting), - "16 colors" => color(16, 50.0, 50.0, 15, Method::Abutting), + "6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting), + "16 colors" => color(16, 50.0, 50.0, 8, Method::Abutting), "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 50.0, corners: 50.0, noise: 15, method: Method::Overlapping, ..d }, - "black and white logo" => bw(128, 50.0, 75.0, 25, true), + "black and white logo" => bw(128, 50.0, 75.0, 5, true), "sketched art" => bw(150, 50.0, 50.0, 20, false), "silhouettes" => bw(200, 50.0, 50.0, 90, false), "line art" => bw(128, 50.0, 75.0, 20, false), diff --git a/crates/trace/src/pipeline.rs b/crates/trace/src/pipeline.rs index cb635e7493..0e3abbadda 100644 --- a/crates/trace/src/pipeline.rs +++ b/crates/trace/src/pipeline.rs @@ -270,7 +270,10 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &( drop(grays); // Noise clears specks, not the regions of a rare colour Automatic kept on purpose. let keep: Vec = q.palette.iter().map(|c| rare.contains(c)).collect(); - quantize::denoise_keeping(&mut q.labels, w, h, params.noise as usize, &keep); + // A speck far from the color around it joins the color beside it nearest its own pixels. + let labs = quantize::palette_labs(&q.palette); + let source = quantize::Source { labs: &labs, rgba: &img.rgba, gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) }; + quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &keep, Some(&source)); go_on()?; // Ignore Color, background only: the labels traced, with the ignored color's areas that reach // the edge left out. Its other areas are traced with the rest. Edges are still placed by diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a54fdfacc7..ea8fa00ac8 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -11,7 +11,9 @@ mod rare; use cut_edge::{choosing_pixels, compact, settled, settled_wide, settles_wide}; pub(crate) use cut_edge::{continuous_tone, settle_cut_edges}; pub use denoise::denoise; +#[cfg(test)] pub(crate) use denoise::denoise_keeping; +pub(crate) use denoise::{Source, denoise_nearest}; pub use palette::FULL_TONE_MAX; use palette::{Bin, HistKey, TracedAs, Used, color_palette, flat_count, flat_palette, kmeans_1d, labs, nearest_1d, nearest_lab, nearest_library}; #[cfg(test)] @@ -296,6 +298,11 @@ fn oklab(c: [f64; 3]) -> [f64; 3] { ] } +/// [`oklab`] of each palette color. +pub(crate) fn palette_labs(palette: &[[u8; 3]]) -> Vec<[f64; 3]> { + palette.iter().map(|c| oklab(c.map(f64::from))).collect() +} + /// [`oklab`] of an sRGB colour, for the tests. #[cfg(test)] pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] { diff --git a/crates/trace/src/quantize/denoise.rs b/crates/trace/src/quantize/denoise.rs index a929691466..5bc237926a 100644 --- a/crates/trace/src/quantize/denoise.rs +++ b/crates/trace/src/quantize/denoise.rs @@ -8,16 +8,49 @@ pub fn denoise(labels: &mut [u16], w: usize, h: usize, min_area: usize) { denoise_keeping(labels, w, h, min_area, &[]); } +/// How far apart (Oklab × 100) a small region's color and the color it shares the longest +/// border with must be before it merges into the color beside it that is nearest its source +/// pixels instead (among those with at least [`NEAREST_BORDER`] of the longest border): a dark +/// speck on the edge of a light area joins the dark outline beside it, not the light area. +pub(crate) const NEAREST_APART: f64 = 10.0; + +/// See [`NEAREST_APART`]. +pub(crate) const NEAREST_BORDER: f64 = 0.1; + +/// The fewest pixels a region needs for [`NEAREST_APART`] to apply when two or more colors tie +/// for its longest border. Such a lone pixel merges by border alone: on an anti-aliased corner it +/// holds a mix of the colors on both sides, and joining the nearer one can cut the corner off a +/// shape. +pub(crate) const NEAREST_PIXELS: u32 = 2; + +/// The colors [`denoise_nearest`] compares a small region with. +pub(crate) struct Source<'a> { + /// Each label's color in Oklab × 100 ([`super::palette_labs`]). + pub labs: &'a [[f64; 3]], + /// The image the labels were made from, 4 bytes a pixel. + pub rgba: &'a [u8], + /// Whether the labels are grays (Grayscale, Black and White): the source pixels are compared as their gray. + pub gray: bool, +} + /// [`denoise`], except that a region of a label `keep` marks (a rare colour kept on purpose, see /// [`rare_colours`]) that is at least [`RARE_ISLAND`] pixels stays whatever `min_area` is: Noise /// clears specks, not a colour's only regions. Smaller regions of it go as any other. pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) { + denoise_nearest(labels, w, h, min_area, keep, None); +} + +/// [`denoise_keeping`]; with `source`, a region below `min_area` whose color is at least +/// [`NEAREST_APART`] from the color it shares the longest border with merges into the color +/// beside it nearest its source pixels, averaged, among those sharing at least [`NEAREST_BORDER`] +/// of the longest border ([`NEAREST_PIXELS`] limits this for a single pixel). Every region below +/// `min_area` still goes. +pub(crate) fn denoise_nearest(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool], source: Option<&Source>) { use std::cmp::Reverse; use std::collections::BinaryHeap; // Every index below is a `u32`, so a pixel costs 8 bytes and a region 18 instead of a `Vec` per region. An image // of `u32::MAX` pixels or more (far above the decoder's cap) is left as it is. - const NONE: u32 = u32::MAX; if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) || labels.len() >= NONE as usize { return; } @@ -66,14 +99,8 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: colour.push(label); parent.push(id); } - fn find(parent: &mut [u32], mut a: u32) -> u32 { - while parent[a as usize] != a { - let up = parent[parent[a as usize] as usize]; - parent[a as usize] = up; - a = up; - } - a - } + // Only when it can be read: the labels' colors and the source pixels must cover every label and every pixel. + let source = source.filter(|s| colour.iter().all(|&c| (c as usize) < s.labs.len()) && labels.len().checked_mul(4) == Some(s.rgba.len())); // Only regions below `min_area` are ever taken from the queue; a larger one ends the loop. let mut pending: BinaryHeap<_> = (0..size.len() as u32).filter(|&id| (size[id as usize] as usize) < min_area).map(|id| Reverse((size[id as usize], id))).collect(); @@ -110,9 +137,24 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: by_colour.clear(); by_colour.extend(borders.iter().map(|&(other, border)| (colour[other as usize], border))); merge_counts(&mut by_colour); - let Some(&(chosen, _)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else { + let Some(&(mut chosen, longest)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else { continue; // an opaque island surrounded only by transparency stays intact }; + if let Some(source) = source + && (area >= NEAREST_PIXELS || by_colour.iter().filter(|&&(_, border)| border == longest).count() == 1) + && let Some(own) = source.labs.get(colour[id as usize] as usize) + && distance(own, source.labs.get(chosen as usize)) >= NEAREST_APART + { + let mean = mean_lab(head[id as usize], &next, source); + let to = |c: u16| distance(&mean, source.labs.get(c as usize)); + if let Some(&(nearest, _)) = by_colour + .iter() + .filter(|&&(_, border)| border as f64 >= NEAREST_BORDER * longest as f64) + .min_by(|a, b| to(a.0).total_cmp(&to(b.0)).then(b.1.cmp(&a.1))) + { + chosen = nearest; + } + } // All adjacent regions of the chosen colour become connected by this merge. Absorb // them together, keeping the largest one as the survivor. let Some(target) = borders @@ -143,6 +185,44 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: } } +/// The end of a pixel list, and the region of a transparent pixel. +const NONE: u32 = u32::MAX; + +/// The root of `a` in the union-find `parent`, halving the paths on the way. +fn find(parent: &mut [u32], mut a: u32) -> u32 { + while parent[a as usize] != a { + let up = parent[parent[a as usize] as usize]; + parent[a as usize] = up; + a = up; + } + a +} + +/// The source pixels of the list that starts at `first` (linked through `next`), averaged, in Oklab × 100. +fn mean_lab(first: u32, next: &[u32], source: &Source) -> [f64; 3] { + let (mut sum, mut n) = ([0.0f64; 3], 0.0f64); + let mut pixel = first; + while pixel != NONE { + if let Some(p) = source.rgba.get(pixel as usize * 4..pixel as usize * 4 + 3) { + for (s, &v) in sum.iter_mut().zip(p) { + *s += f64::from(v); + } + n += 1.0; + } + pixel = next.get(pixel as usize).copied().unwrap_or(NONE); + } + let mut mean = sum.map(|s| s / n.max(1.0)); + if source.gray { + mean = [0.299 * mean[0] + 0.587 * mean[1] + 0.114 * mean[2]; 3]; + } + super::oklab(mean) +} + +/// The distance between two colors in Oklab × 100; infinite when `q` is missing. +fn distance(p: &[f64; 3], q: Option<&[f64; 3]>) -> f64 { + q.map_or(f64::INFINITY, |q| (0..3).map(|k| (p[k] - q[k]).powi(2)).sum::().sqrt()) +} + /// Sort `(key, count)` pairs and add up the counts of equal keys. fn merge_counts(pairs: &mut Vec<(K, usize)>) { pairs.sort_unstable_by_key(|p| p.0); @@ -285,6 +365,157 @@ mod tests { } } + /// A light ground, a dark ink, a tone barely darker than the ground and a dark brown close to the ink. + const GROUND_INK_TONE_BROWN: [[u8; 3]; 4] = [[235, 225, 210], [30, 25, 20], [228, 218, 203], [50, 42, 35]]; + + /// `labels` denoised at `min_area`, reading the source image that paints each label its palette color. + fn denoised_nearest(labels: &[u16], w: usize, h: usize, min_area: usize) -> Vec { + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); + let rgba: Vec = + labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect(); + let mut out = labels.to_vec(); + denoise_nearest(&mut out, w, h, min_area, &[], Some(&Source { labs: &labs, rgba: &rgba, gray: false })); + out + } + + /// A ground with a dark line two pixels wide down column 12 and 13, and a 2 × 2 speck of `speck` at (10, 10) that + /// touches the line on one side and the ground on three. + fn speck_beside_a_line(speck: u16) -> (Vec, usize, usize) { + let (w, h) = (30, 30); + let mut labels = vec![0u16; w * h]; + for y in 0..h { + labels[y * w + 12] = 1; + labels[y * w + 13] = 1; + } + for (x, y) in SPECK { + labels[y * w + x] = speck; + } + (labels, w, h) + } + + const SPECK: [(usize, usize); 4] = [(10, 10), (11, 10), (10, 11), (11, 11)]; + + /// A dark speck mostly on the light ground but touching a dark line joins the line, the color nearest it, not the + /// ground it shares more border with. + #[test] + fn a_dark_speck_beside_a_dark_line_joins_the_line() { + let (labels, w, h) = speck_beside_a_line(3); + let out = denoised_nearest(&labels, w, h, 15); + for (x, y) in SPECK { + assert_eq!(out[y * w + x], 1, "({x}, {y})"); + } + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + assert_eq!(blind[10 * w + 10], 0, "by border alone it joins the ground"); + } + + /// A speck whose color is close to the color it shares the longest border with joins that color, as before, + /// even though another color touches it. + #[test] + fn a_speck_close_to_its_longest_border_color_joins_it() { + let (labels, w, h) = speck_beside_a_line(2); + let out = denoised_nearest(&labels, w, h, 15); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + assert_eq!(out, blind); + assert_eq!(out[10 * w + 10], 0); + } + + /// A color that touches the speck along less than a tenth of its longest border is not chosen, however near. + #[test] + fn a_color_with_a_short_border_is_not_chosen() { + let (w, h) = (30, 30); + let mut labels = vec![0u16; w * h]; + // A 3 × 3 speck of brown in the ground, and a line of ink 16 pixels long (above Noise) that touches the speck at + // one pixel edge. + for y in 10..13 { + for x in 10..13 { + labels[y * w + x] = 3; + } + } + for x in 13..29 { + labels[10 * w + x] = 1; + } + // The brown speck has 11 pixel edges against the ground and 1 against the ink: 1 < 0.1 × 11. + let out = denoised_nearest(&labels, w, h, 15); + assert_eq!(out[11 * w + 11], 0); + assert!(out[10 * w + 13..10 * w + 29].iter().all(|&l| l == 1), "the line stays"); + } + + /// A lone pixel tied between two colors for its longest border merges by border alone, even when the other + /// color is nearer its source pixel. + #[test] + fn a_lone_pixel_tied_between_colors_merges_by_border() { + let (w, h) = (20, 20); + // Ground in the top-left, ink everywhere else, and one brown pixel at the corner with two edges on each. + let mut labels: Vec = (0..w * h).map(|i| u16::from(i % w >= 11 || i / w >= 11)).collect(); + labels[10 * w + 10] = 3; + let out = denoised_nearest(&labels, w, h, 5); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 5, &[]); + assert_eq!(out, blind); + assert_eq!(out[10 * w + 10], 0); + // With the ground one column wider the pixel has three edges on the ground and one on the ink: no longer tied, + // it joins the ink, the color nearest it. + for y in 0..11 { + labels[y * w + 11] = 0; + } + let out = denoised_nearest(&labels, w, h, 5); + assert_eq!(out[10 * w + 10], 1); + } + + /// Every region below Noise still goes: the nearest-color merge only changes where it goes. + #[test] + fn noise_still_removes_every_region_below_it() { + let (w, h) = (60, 50); + for seed in 1..6 { + let labels = noisy(w, h, 4, 0, seed); + for min_area in [2, 3, 5, 8, 15, 25] { + let out = denoised_nearest(&labels, w, h, min_area); + let mut seen = vec![false; w * h]; + for start in 0..w * h { + if seen[start] { + continue; + } + seen[start] = true; + let mut stack = vec![start]; + let mut count = 0; + while let Some(i) = stack.pop() { + count += 1; + let (x, y) = (i % w, i / w); + for j in [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)] + .into_iter() + .flatten() + { + if !seen[j] && out[j] == out[i] { + seen[j] = true; + stack.push(j); + } + } + } + assert!(count >= min_area, "seed {seed}, Noise {min_area}: a region of {count} pixels at {start}"); + } + } + } + } + + /// Without colors or a source image for every label and pixel, every region merges as it always did. + #[test] + fn a_source_that_does_not_cover_the_labels_is_not_read() { + let (labels, w, h) = speck_beside_a_line(3); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN[..2]); + let rgba = vec![0u8; w * h * 4]; + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, gray: false })); + assert_eq!(out, blind); + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba[4..], gray: false })); + assert_eq!(out, blind); + } + /// A minimum so large that regions keep merging into big ones. #[test] fn compact_denoise_matches_the_reference_with_a_large_min_area() { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 85e9d09778..cc7b1e323c 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -899,10 +899,10 @@ fn presets_have_their_paths_corners_and_noise() { ("High Fidelity Photo", 50.0, 50.0, 5), ("Low Fidelity Photo", 50.0, 50.0, 10), ("3 Colors", 50.0, 50.0, 15), - ("6 Colors", 50.0, 50.0, 15), - ("16 Colors", 50.0, 50.0, 15), + ("6 Colors", 50.0, 50.0, 8), + ("16 Colors", 50.0, 50.0, 8), ("Shades of Gray", 50.0, 50.0, 15), - ("Black and White Logo", 50.0, 75.0, 25), + ("Black and White Logo", 50.0, 75.0, 5), ("Sketched Art", 50.0, 50.0, 20), ("Silhouettes", 50.0, 50.0, 90), ("Line Art", 50.0, 75.0, 20), @@ -1928,7 +1928,9 @@ fn contour_spread(res: &TraceResult) -> (f64, usize) { #[test] fn the_borders_of_a_gradients_bands_follow_its_contours() { - let res = trace(&wavy_bands(), &sixteen_colors()); + // At the Noise this test was written for: at 16 Colors' Noise 8 the 6 levels of noise leave more + // small regions along the borders. + let res = trace(&wavy_bands(), &TraceParams { noise: 15, ..sixteen_colors() }); // The square's sides are edges: it keeps its four corners. let [l, t, r, b] = WAVY_SQUARE; let square = res.paths.iter().find(|p| p.color.iter().all(|&c| c < 40)).expect("the dark square"); diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 22557771e2..2bd58e4df4 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -20,9 +20,9 @@ its current location. Opening the controls does not add a document undo step. The built-in presets other than Auto Color and Flat Logo all use Paths 50, and so do their enhanced versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White -Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, -6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and -Black and White Logo, and 90 in Silhouettes (see +Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo and Black and White Logo, 8 in 6 Colors +and 16 Colors, 10 in Low Fidelity Photo, 15 in 3 Colors and Shades of Gray, 20 in Sketched Art, Line +Art and Outline, 25 in Default, and 90 in Silhouettes (see [image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). Sliders apply on release, and their numeric fields can be edited directly. Each committed diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index dacf436036..228c1ef9f8 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -237,10 +237,10 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co | High Fidelity Photo | 50 | 50 | 5 | 90, 25, 4 | | Low Fidelity Photo | 50 | 50 | 10 | 60, 50, 12 | | 3 Colors | 50 | 50 | 15 | 60, 60, 20 | -| 6 Colors | 50 | 50 | 15 | 65, 60, 16 | -| 16 Colors | 50 | 50 | 15 | 70, 55, 10 | +| 6 Colors | 50 | 50 | 8 | 65, 60, 16 | +| 16 Colors | 50 | 50 | 8 | 70, 55, 10 | | Shades of Gray | 50 | 50 | 15 | 60, 50, 10 | -| Black and White Logo | 50 | 75 | 25 | 95, 80, 8 | +| Black and White Logo | 50 | 75 | 5 | 95, 80, 8 | | Sketched Art | 50 | 50 | 20 | 50, 50, 100 | | Silhouettes | 50 | 50 | 90 | 40, 60, 30 | | Line Art | 50 | 75 | 20 | 80, 70, 10 | @@ -248,7 +248,9 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co | Outline | 50 | 75 | 20 | 80, 70, 10 | The palettes, color counts, thresholds and other options of the presets did not change. The enhanced -versions of these presets use the same Paths, Corners and Noise. +versions of these presets use the same Paths, Corners and Noise. 6 Colors and 16 Colors were at Noise 15 +and Black and White Logo at 25 until [Noise joins the nearest color](#noise-joins-the-nearest-color); +the measurements below were made at those values. Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 @@ -309,6 +311,38 @@ identical settings on unchanged current source and the candidate, including sepa crops and white-composited PNG comparisons. These local fixtures are not repository assets. The parity score is unchanged. +## Noise joins the nearest color + +A region below Noise used to join the color it shares the longest border with. Along a thin dark +line on a light ground, a dark speck of the line touches the ground on more sides than the line, so +it joined the ground and the line broke into dashes. Now, when the color of the longest border is +10 or more apart from the region's own color (Oklab × 100), the region joins the neighboring color +nearest the average of its source pixels, among the colors that share at least a tenth of the +longest border. A single pixel whose longest border is tied between colors joins by border as +before, so an anti-aliased corner pixel stays with the shape's corner. The rule changes only which +color a region joins, and higher Noise still continues the same merge sequence. The values are +VectorCraft's own. 6 Colors and 16 Colors move from Noise 15 to 8, and Black and White Logo from 25 to 5. + +Measured on 17 local images (synthetic shapes and photos at several sizes, a geometric drawing and +eight illustrations; not repository assets), against the same `main` without the change, with the +mean absolute difference per channel (0 to 255) against the image on white: + +| preset | three illustrations with fine dark lines | four other illustrations | synthetic shapes and photos | +|:--|:--|:--|:--| +| 16 Colors | 8.15 / 10.80 / 8.69 → 5.82 / 6.25 / 6.01; anchors +72% to +99% | −1.8% to −11.9%; anchors +20% to +39% | within 0.08 of a level; anchors 0% to +37% | +| 6 Colors | 7.24 / 9.14 / 9.21 → 5.87 / 6.66 / 7.87; anchors +55% to +73% | −0.6% to −3.5%; anchors +13% to +20% | within 0.03; anchors 0% to +22% | +| High Fidelity Photo | 8.42 / 10.11 / 7.46 → 6.85 / 7.54 / 6.00; anchors +31% to +51% | −1.4% to −5.8%; anchors −9% to +4% | within 0.08; anchors −6% to +5% | + +Black and White Logo's pixels that differ from the image thresholded at 128 fall from 2.00 / 2.42 / +1.96% to 1.49 / 1.58 / 1.23% on the three illustrations and from 1.19 to 2.37% to 1.14 to 1.94% on the +other four, with 5% to 64% more anchors; the synthetic inputs change by 0.01% or less. A simple flat +illustration changes by 1.1% or less in every preset, and the geometric drawing keeps its anchor +count and difference in every preset. Tests: `a_dark_speck_beside_a_dark_line_joins_the_line`, +`a_speck_close_to_its_longest_border_color_joins_it`, `a_color_with_a_short_border_is_not_chosen`, +`a_lone_pixel_tied_between_colors_merges_by_border`, `noise_still_removes_every_region_below_it` and +`a_source_that_does_not_cover_the_labels_is_not_read` in `crates/trace/src/quantize/denoise.rs`. +`the_borders_of_a_gradients_bands_follow_its_contours` runs at Noise 15, the value it was written for. + ## Pieces returning to a junction An outline piece can return to its starting junction while being fitted as an open chain. At loose Corners/Paths settings, a nonzero positioned boundary could collapse to one cubic and lose a small diff --git a/docs/mcp.md b/docs/mcp.md index a987c40c85..57c349d335 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3847,6 +3847,12 @@ already walks Image Trace. Short agent entry points: `paths` and `anchors` count the traced paths only. With `keepColors` in `params`, the reply's `warnings` name each listed color that no traced color matches, and say when nothing was traced. + `noise` (Color, Grayscale and Black and White, not Flat Logo) merges areas smaller than that many pixels into a + neighboring color. Each one joins the color it shares the longest border with, unless that color is 10 or more apart from its own (Oklab + × 100). Then it joins the neighboring color nearest the average of its source pixels, among the colors that share at + least a tenth of the longest border. A single pixel whose longest border is tied between two or more colors always + joins by border. These distances and fractions are VectorCraft's own values. The built-in presets 6 Colors and 16 + Colors use Noise 8, and Black and White Logo uses Noise 5. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with the preferences: `params` over `preset`'s (default: the saved preset `name`, else Default), checked as `imageTrace.make` checks them; without `name` it is a new "Tracing Preset N", and `newName` renames a saved preset (the reply's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 74ce58c5d6..85d4412e45 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1541,6 +1541,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. - **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. +- **Image Trace, Noise joins the nearest color:** in Color, Grayscale and Black and White, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest its source pixels, among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. From 4ac0d02bdb11e216eb41e47373a481257e4170b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:23:22 -0800 Subject: [PATCH 25/63] Docs: a color image whose pixel data can't be read is left out as undecoded, not unconverted --- docs/mcp.md | 7 ++++--- docs/target-app-parity.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b3d430f793..3d45e3326f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5911,9 +5911,10 @@ and then to the destination, instead of having its numbers read as sRGB (a profi them read as sRGB, with a warning); a gray image keeps its profile, as gray is not converted. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there. Any other image whose colors are converted (a CMYK image, or an RGB image going to a CMYK destination or to an -RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with the warning "an image -couldn't be converted to the Output destination and is missing from the picture", rather than written in its own -colors. +RGB one other than sRGB) but whose pixels are more than VectorCraft decodes or can't be written that way is left out with +the warning "an image couldn't be converted to the Output destination and is missing from the picture", rather than +written in its own colors. One whose pixel data can't be read is left out with the warning "an image couldn't be decoded +and is missing from the picture", as without a conversion. `preserveNumbers` still reads an image's numbers as sRGB. The destination is any profile `edit.colorSettings` lists (default: the document's for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c9efa4aea9..7cdaa80707 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1930,7 +1930,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but can't be decoded. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). + - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but is more than VectorCraft decodes. A color image whose pixel data can't be read is left out with the warning "an image couldn't be decoded and is missing from the picture", as without a conversion. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - PDF import keeps the CMYK profile of an image in a four-component `ICCBased` color space, whose stream holds the profile ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)), byte for byte with the image's ink amounts, so PDF export can write the image in it again. A CMYK TIFF carries it as tag 34675, whatever the image's Decode array and bit depth ([ICC.1:2010, Annex B](https://www.color.org/specification/ICC1v43_2010-12.pdf)). A CMYK JPEG kept as it is carries it in `ICC_PROFILE` APP2 segments in place of a profile of its own, with its compressed samples unchanged, and one whose segments can't hold it is stored as a CMYK TIFF carrying it. A profile that isn't well formed, isn't of CMYK colors or is over 16 MiB (VectorCraft's own limit) leaves the image's inks as they are, untagged. DeviceCMYK and DeviceN images carry no profile, and a CMYK TIFF's tag 34675 is read up to 16 MiB. EPS and PostScript import does not keep one: PostScript defines no `ICCBased` profile stream (`crates/pdf/src/tests/cmykimages.rs`, `cmyk::tests`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). From 531ce2a10e62ba731048c0d572b753fd05fdf401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:07:49 -0800 Subject: [PATCH 26/63] Effects: Safe Mode checks graph design art that a blurred fill of its series group draws effect.expandAppearance in Safe Mode left the art of a graph design in a series out of the plug-in check unless an effect of the series group itself would draw it. A raster effect on one of the group's fills or strokes, such as a Gaussian Blur, also turns the whole group into an image when it expands, art included, so a plug-in effect in that art was expanded without drawing. Such a raster effect now keeps the art in the check, and the command returns the Safe Mode error. --- crates/engine/src/cmd/effectcmd.rs | 7 ++++--- crates/engine/tests/plugin_safe_mode.rs | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5ca2055178..625300cd25 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1302,15 +1302,16 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { if vectorcraft_plugins::safe_mode::active() { // A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a // series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it - // with that group. + // with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group + // then becomes an image of all of it). let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots); + let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty(); let designs: Vec = super::appearance::design_art_in(&d, &roots) .into_iter() .filter(|art| { !d.ancestry(*art).is_some_and(|up| { let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len()); - up.get(from..up.len().saturating_sub(1)) - .is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(|g| g.appearance.effects.iter().any(|e| e.visible))) + up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members)) }) }) .collect(); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 8829c056b3..9ff0d0668a 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -507,6 +507,23 @@ fn expand_appearance_in_safe_mode_checks_design_art_its_series_group_draws() { let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); safe_mode::set_active(None); assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + // With a Gaussian Blur on a fill of the art's series group instead, expanding the group makes an image of it, art included. + let blurred_fill = { + let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 40, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone() + }; + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let g = d.node_mut(art_series).unwrap(); + g.appearance.effects.clear(); + g.appearance.items.push(blurred_fill); + } + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); } /// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop From d1801950c53defea7beba29ee92e037affacc39d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:18:42 -0800 Subject: [PATCH 27/63] Graph Data: a column drag keeps its width while scrolling and ends where released A column's dragged width is now its width when the drag started plus how far the pointer has moved since. Before, it was measured from the sheet's scroll origin, so with the sheet scrolled to its right end a held drag that narrowed a column kept narrowing it to 0 as the scroll offset followed the narrower sheet. A release that comes in the same frame as the last move now sets the width to where the pointer was released, also for an edge dragged out of view. Entering the width Column Width already shows, with Enter, now sets every column, the dragged ones too. Clicking into the field and away without a new value keeps the columns' own widths. --- crates/ui-egui/src/dialogs/graph_data.rs | 130 +++++++++++++++++++++-- 1 file changed, 124 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 935ce60bd9..90cc7d9f55 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -437,7 +437,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(12.0); widgets::dim_label(ui, tl!("Column Width:")); let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7); - if ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)).changed() { + let r = ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)); + // A value entered with Enter sets every column, also when it is the width shown. Leaving the + // field without a new value keeps the columns' own widths. + if r.changed() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) { set_width(d, w); } }); @@ -559,18 +562,38 @@ fn sheet(ui: &mut egui::Ui, d: &Dialog) -> SheetInput { } } // A column's right edge, over the rows in view: dragging it sets that column's width. The - // edge being dragged stays in the loop when it leaves the view, so the drag goes on. + // edge being dragged stays in the loop when it leaves the view, so the drag goes on, also in + // the frame it is released. let (top, bottom) = (origin.y + r0 as f32 * ch, origin.y + r1 as f32 * ch); - let dragged = ui.ctx().dragged_id().and_then(|id| (0..cols).find(|&c| edge_id(c) == id)).filter(|c| !(c0..c1).contains(c)); + let dragged = ui + .ctx() + .dragged_id() + .or_else(|| ui.ctx().drag_stopped_id()) + .and_then(|id| (0..cols).find(|&c| edge_id(c) == id)) + .filter(|c| !(c0..c1).contains(c)); for c in (c0..c1).chain(dragged) { let gap = origin.x + left(c + 1) - 0.5; let edge = egui::Rect::from_x_y_ranges(gap - 3.0..=gap + 3.0, top..=bottom); let h = ui.interact(edge, edge_id(c), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeColumn); + // The width is the column's width when the drag started plus how far the pointer has + // moved since, so a scroll offset that changes with the sheet's width doesn't change it. + if h.drag_started() + && let Some(p) = ui.input(|i| i.pointer.press_origin()).or_else(|| h.interact_pointer_pos()) + { + ui.data_mut(|m| m.insert_temp(edge_id(c), (p.x, left(c + 1) - left(c) - 1.0))); + } if h.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn); - if let Some(p) = h.interact_pointer_pos() { - resized = Some((c, px_digits(p.x - origin.x - left(c)))); - } + } + // The release can come in the same frame as the last move: it sets the width too. + if (h.dragged() || h.drag_stopped()) + && let Some(p) = h.interact_pointer_pos() + && let Some((x0, w0)) = ui.data(|m| m.get_temp::<(f32, f32)>(edge_id(c))) + { + resized = Some((c, px_digits(w0 + p.x - x0))); + } + if h.drag_stopped() { + ui.data_mut(|m| m.remove::<(f32, f32)>(edge_id(c))); } } }); @@ -834,6 +857,101 @@ mod tests { assert_eq!(digits(&app), [9; 4], "Cell Style sets every column"); } + /// A drag whose last move comes in the frame it is released sets the width to where it was + /// released. A held drag on a sheet scrolled to its right end keeps its width while the scroll + /// offset follows the narrower sheet. Entering the width that Column Width shows sets every + /// column, the dragged ones too. + #[test] + fn a_column_drag_ends_where_released_and_the_shown_width_entered_sets_every_column() { + let rows: Vec> = (0..3).map(|i| vec![i as f64; 30]).collect(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "rows": rows})).unwrap(); + open(&mut app).unwrap(); + let cols = extent(app.ui.dialog.as_ref().unwrap(), (0, 1)).1; + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn")); + let digits = |app: &VectorcraftApp, c: usize| col_digits(app.ui.dialog.as_ref().unwrap(), c); + for _ in 0..3 { + frame(&mut app, vec![]); + } + // The last move and the release in one frame: 70 points is 10 digits. + let at = edge(1).center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + let to = at + egui::vec2(70.0, 0.0); + frame(&mut app, vec![egui::Event::PointerMoved(to), button(to, false)]); + frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + assert_eq!(digits(&app, 1), 17, "the width where the drag was released"); + // Scroll the sheet to its right end, then narrow a column by 5 digits and hold the pointer still. + let over = edge(1).center() - egui::vec2(20.0, 0.0); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-100_000.0, 0.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + frame(&mut app, vec![egui::Event::PointerMoved(over), wheel]); + for _ in 0..30 { + frame(&mut app, vec![]); + } + let c = cols - 2; + let at = edge(c).center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + for step in 1..=5 { + frame(&mut app, vec![egui::Event::PointerMoved(at - egui::vec2(7.0 * step as f32, 0.0))]); + } + for _ in 0..10 { + frame(&mut app, vec![]); + } + assert_eq!(digits(&app, c), 2, "a held drag keeps its width"); + let to = at - egui::vec2(35.0, 0.0); + frame(&mut app, vec![button(to, false)]); + frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + assert_eq!(digits(&app, c), 2, "the width where the drag was released"); + // Column Width still shows 7: entering 7 there sets every column to 7. + let nodes = frame(&mut app, vec![]); + let label = nodes + .iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::Label && n.value() == Some("Column Width:")) + .and_then(|(_, n)| n.bounds()) + .expect("the Column Width label is drawn"); + let field = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::SpinButton) + .filter_map(|(_, n)| n.bounds()) + .filter(|b| b.x0 >= label.x1 && b.y0 < label.y1 && b.y1 > label.y0) + .min_by(|a, b| a.x0.total_cmp(&b.x0)) + .expect("the Column Width field is drawn"); + let at = egui::pos2(((field.x0 + field.x1) / 2.0) as f32, ((field.y0 + field.y1) / 2.0) as f32); + let click = |app: &mut VectorcraftApp, at| { + frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]); + frame(app, vec![button(at, false)]); + frame(app, vec![]); + }; + // Clicking into the field and away from it, without a new value, keeps the columns' widths. + click(&mut app, at); + click(&mut app, egui::pos2(((label.x0 + label.x1) / 2.0) as f32, ((label.y0 + label.y1) / 2.0) as f32)); + assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (17, 2, 7), "leaving the field keeps the widths"); + click(&mut app, at); + frame(&mut app, vec![egui::Event::Text("7".into())]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![enter]); + frame(&mut app, vec![]); + assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (7, 7, 7), "Column Width sets every column"); + } + #[test] fn a_column_width_in_points_maps_to_whole_digits() { for n in 0..=MAX_WIDTH { From 521f5dc6c827f14f74acd8e3e54e7a19856f8516 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:30:27 -0800 Subject: [PATCH 28/63] Selection: Select Behind keeps one limit of symbol art when it falls back Select Behind gave the general traversal a fresh limit of symbol art when it fell back to it, for an envelope in Edit Contents or a root that is not a layer. One Select Behind could then walk twice MAX_SYMBOL_NODES objects of symbol art. A root that is not a layer now sends Select Behind to the general traversal before the first pass walks any art. For an envelope in Edit Contents, the objects the first pass found stay first, and the general traversal finds the rest with what is left of the limit. --- crates/doc/src/hit.rs | 25 ++++++------- crates/doc/src/hit/tests.rs | 70 +++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d49776b2cb..8d918cba32 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -323,34 +323,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option) -> Vec { - let walk = ArtWalk::open(); + let _walk = ArtWalk::open(); let opt = HitOptions { scope: scope.or(opt.scope), ..opt }; // Normally one hit test per *object* suffices: layers and sublayers aren't selectable, // while a group (including a clipping group) is selected as one object. Repeatedly // searching the full tree for each hit made a stack of n overlapping paths O(n^2). // Isolation and Edit Contents change where selection groups begin; keep the original // traversal for those cases rather than change their Select Behind semantics. - if opt.scope.is_some() { + // Malformed files may contain non-layer roots; let the general traversal handle them. + if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) { return objects_at_repeated(doc, p, opt, scope); } let mut tops = Vec::new(); let mut seen = HashSet::new(); let symbols = doc.symbol_boxes(); for layer in doc.layers.iter().rev() { - // Malformed files may contain non-layer roots; let the general traversal handle them. - if !layer.is_layer() { - walk.restart(); - return objects_at_repeated(doc, p, opt, scope); - } if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) { continue; } if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) { // An envelope in Edit Contents may expose objects *within* a top-level group. - // The repeated traversal handles that mixed hierarchy precisely, with the whole - // limit of symbol art to walk. - walk.restart(); - return objects_at_repeated(doc, p, opt, scope); + // The repeated traversal handles that mixed hierarchy precisely. The objects found + // so far lie above the envelope and stay first; the repeated traversal finds the + // rest with what is left of the limit of symbol art to walk. + tops = objects_at_repeated_after(doc, p, opt, scope, tops); + break; } } // The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them. @@ -414,7 +411,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox /// The general selection order also handles isolation and nested Edit Contents. fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option) -> Vec { - let mut tops: Vec = vec![]; + objects_at_repeated_after(doc, p, opt, scope, vec![]) +} + +/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. +fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { // Each round leaves out the objects found so far (and everything inside them). while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { if tops.contains(&top) { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 74bd959a7f..4912f28857 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1452,6 +1452,76 @@ fn objects_at_edit_contents_uses_general_order() { assert_eq!(objects_at(&d, p, opt, None), vec![b, a]); } +/// Select Behind keeps one limit of symbol art to walk when it falls back to the general +/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback +/// walks no more art than what the first pass left, and keeps what the first pass found. +#[test] +fn select_behind_keeps_one_art_limit_when_it_falls_back() { + // 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art + // of and misses: each walk takes 3 objects of the 100. + let stack = |d: &mut Document, count: usize| { + let l = d.layers[0].id; + for _ in 0..count { + let inst = instance_of(d, "Clipped"); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap(); + } + }; + // An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50). + let envelope = |d: &mut Document| { + let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art())); + let (a, b) = (d.alloc_id(), d.alloc_id()); + let e = Node::new( + d.alloc_id(), + NodeKind::Envelope { + content: vec![inner(a), inner(b)], + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), + fidelity: 100.0, + editing: true, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ); + let l = d.layers[0].id; + d.insert(Some(l), 0, e).unwrap(); + (a, b) + }; + let p = Point::new(150.0, 50.0); + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + let (a, b) = envelope(&mut d); + stack(&mut d, 60); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert_eq!(behind, vec![b, a]); + assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked"); + // An instance that the first pass hits by its art, the limit then used up, stays in the list: + // `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`. + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + let (a, b) = envelope(&mut d); + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + group_symbol(&mut d, "Shown", vec![Arc::new(clip)]); + let hit = instance_of(&mut d, "Shown"); + let hit_id = hit.id; + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap(); + stack(&mut d, 32); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback"); + assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked"); + // A root that is not a layer, below the layer. + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + stack(&mut d, 60); + let root = Arc::new(Node::group(d.alloc_id(), vec![])); + d.layers.insert(0, root); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert!(behind.is_empty()); + assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked"); +} + #[test] fn locked_and_hidden_skip() { let mut d = Document::new(200.0, 200.0); From 94c815d97194d97cf3a290b438b267c933893d4f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:36:20 -0800 Subject: [PATCH 29/63] Paint: invert and complement of design art alone still reject a bad target paint.invert and paint.complement given only the art of a graph design, with no item, returned success for a target other than "object" or "contents", because the topmost-fill path read the target only after the early return for design art. The target is now read before that return. --- crates/engine/src/cmd/graph/tests.rs | 2 ++ crates/engine/src/cmd/paint.rs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 93cf1cf51b..65715e44d1 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -563,8 +563,10 @@ fn paint_edits_of_design_art_alone_leave_the_defaults() { json!({"ids": [art.0], "item": "top"}), json!({"ids": [art.0], "item": fill, "aligned": "yes"}), json!({"ids": [art.0], "item": fill, "target": "nowhere"}), + json!({"ids": [art.0], "target": "nowhere"}), ] { assert!(s.execute("paint.invert", &bad).is_err(), "{bad}"); + assert!(s.execute("paint.complement", &bad).is_err(), "{bad}"); } // So is an `item` the art has no row for, in each command that leaves the art out. let steps = s.doc().unwrap().history.undo.len(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 0870c1cd1a..ef15f896cd 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1098,6 +1098,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?, ItemTarget::Top => None, }; + // Read before the check below too: `targets` reads no `target` for the topmost fill or stroke. + let contents = super::appearance::targets_contents(p)?; let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); // Only design art was given or selected: nothing changes, the defaults and remembered colors included. if ids.is_empty() { @@ -1128,7 +1130,6 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( // objects change as their paint targets do (a compound path's member stands for the compound path). Design art // inside a given graph or series group is left out. ItemTarget::Top => { - let contents = super::appearance::targets_contents(p)?; let mut roots = vec![]; for id in &ids { let n = s.doc()?.doc.node(*id); From f0ba18f7930e6adc0da5535a7133f3c478fd7088 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:36:54 -0800 Subject: [PATCH 30/63] Place: the place cursor keeps an encrypted PDF and asks for its password file.place.queue read each file without a password, so an encrypted PDF, .ai or .ait file was skipped and never reached the cursor. It now stays in the cursor at 612 x 792 pt, VectorCraft's own size, with needsPassword: true and no thumbnail. A click or drag on it in the app asks for its password, with the Place dialog's Show Import Options on or off; headless, a click on it places nothing. A file that fails for a bad option or for another reason is still refused or skipped. File > Place of an encrypted PDF given a page and no password, with Show Import Options on, now asks for the password too, as it does with the option off; it used to fail for want of the password. --- crates/engine/src/cmd/place.rs | 30 +++++++++++++++-- crates/engine/src/tests/place.rs | 29 ++++++++++++++++ crates/ui-egui/src/place.rs | 33 ++++++++++++++++--- crates/ui-egui/src/tests/place.rs | 55 +++++++++++++++++++++++++++++++ docs/mcp.md | 8 +++-- docs/target-app-parity.md | 1 + 6 files changed, 147 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 83216b2f43..7a67773d0c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -71,6 +71,8 @@ const MAX_QUEUE: usize = 100; const MAX_THUMBNAIL: f64 = 512.0; /// A text file's natural box (`file.place.info`, the place cursor): a letter page less 1 in margins. const TEXT_FRAME: Rect = Rect::new(0.0, 0.0, 468.0, 648.0); +/// An encrypted PDF's box in the place cursor, which reads it without its password: a letter page. +const LOCKED_PAGE: Rect = Rect::new(0.0, 0.0, 612.0, 792.0); pub fn specs() -> Vec { vec![ @@ -79,7 +81,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -106,7 +108,7 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}", + "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last; an encrypted PDF, .ai or .ait file stays in the cursor at 612 × 792 pt (VectorCraft's own size) with needsPassword: true and no thumbnail, and a click on it in the app asks for its password (headless, its file.place fails for want of the password) → {count, files: [{name, format, width, height, thumbnailBase64?, needsPassword?}], skipped: [{name, error}]}", has_doc, queue ), @@ -988,6 +990,14 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { } Err(e) => { let name = str_param(&q, "path").or(str_param(&q, "name")).map(fileio::file_name).unwrap_or_default(); + // An encrypted PDF stays, at a size of its own, so that a click in the app can ask + // for its password. + if let Some(format) = locked_pdf(&q, &e) { + let (w, h) = (LOCKED_PAGE.width(), LOCKED_PAGE.height()); + files.push(json!({ "name": name, "format": format, "width": w, "height": h, "needsPassword": true })); + entries.push(json!({ "params": q, "name": name, "width": w, "height": h })); + continue; + } skipped.push(json!({ "name": name, "error": e.to_string() })); } } @@ -995,6 +1005,22 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { Ok(QueueRead { doc, params: p, entries, files, skipped }) } +/// The format id of the file `q` names when it is a PDF, `.ai` or `.ait` file (a path with one of +/// those extensions, as the app's password dialog reads it) that opens only with a password, and +/// reading it failed with `e` for want of that password (not for a bad option). +fn locked_pdf(q: &Value, e: &EngineError) -> Option<&'static str> { + if !e.to_string().contains(&vectorcraft_pdf::PdfError::NeedsPassword.to_string()) { + return None; + } + let src = fileio::source(q, QUEUE).ok()?; + if src.path.is_some() && !matches!(fileio::extension(src.name).as_str(), "pdf" | "ai" | "ait") { + return None; + } + let format = fileio::detect(src.name, &src.bytes)?; + let locked = matches!(vectorcraft_pdf::open_pdf(&src.bytes, None).map(|_| ()), Err(vectorcraft_pdf::PdfError::NeedsPassword)); + (matches!(format.id, "pdf" | "ai" | "ait") && locked).then_some(format.id) +} + impl Session { /// `file.place.queue`'s checks (with no document open, the error `file.place.queue` gives) of /// `params` → what reads the files ([`QueueJob::read`]; on the diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 8dbe06f349..cade51bca6 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -1101,6 +1101,35 @@ fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() { assert_eq!(b.place_queue_read(read).unwrap(), r); } +/// An encrypted PDF stays in the place cursor's queue, read with the session or apart from it, at +/// a letter page's size with `needsPassword`, so that a click in the app can ask for its password; +/// headless, a click on it places nothing. +#[test] +fn the_place_queue_keeps_an_encrypted_pdf() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let locked = pdf(&[PdfPage::new(100.0, 50.0, "0 g 0 0 10 10 re f")], Some("pw")); + let p = json!({"files": [file("locked.pdf", &locked), file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "thumbnail": 8}); + let (mut a, mut b) = (session(), session()); + let r = a.execute("file.place.queue", &p).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + assert_eq!(r["files"][0], json!({"name": "locked.pdf", "format": "pdf", "width": 612.0, "height": 792.0, "needsPassword": true})); + assert!(r["files"][1].get("needsPassword").is_none()); + let read = b.prepare_place_queue(&p).unwrap().read().unwrap(); + assert_eq!(b.place_queue_read(read).unwrap(), r); + let view = ViewInfo::default(); + assert_eq!(a.tool_options()["name"], "locked.pdf"); + let _ = a.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view); + let _ = a.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view); + assert_eq!((top_children(&a).len(), a.doc().unwrap().history.undo.len()), (0, 0), "nothing placed without the password"); + // An encrypted PDF with a bad option is refused for the option, not kept. + let e = a.execute("file.place.queue", &json!({"files": [file("locked.pdf", &locked)], "page": 0})).unwrap_err().to_string(); + assert!(e.contains("page must be a whole number from 1"), "{e}"); + // A PDF that can't be read for another reason is still skipped. + let broken = file("broken.pdf", b"%PDF-1.7\nnot a PDF body\n"); + let r = a.execute("file.place.queue", &json!({"files": [broken, file("b.png", &png(4, 4, [0; 4], None))]})).unwrap(); + assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("broken.pdf")), "{r}"); +} + /// The place queue's thumbnail of an image is drawn from the pixels its check decoded, so each /// image is decoded once. #[test] diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 80c2464f62..54be279e09 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -74,8 +74,11 @@ pub struct PlaceState { queue_asks: bool, /// The loaded cursor's files by name, with the size a click places them at. queue_sizes: Vec<(String, f64, f64)>, + /// The names of the loaded cursor's encrypted PDF files, which ask for their password. + queue_locked: Vec, /// The engine's count of cursor loads ([`vectorcraft_engine::Session::place_queue_loads`]) when - /// `queue_asks` and `queue_sizes` were set: a later load (`tool.setOption`, a script) clears them. + /// `queue_asks`, `queue_sizes` and `queue_locked` were set: a later load (`tool.setOption`, a + /// script) clears them. queue_load: u64, /// The import options dialog a click of the cursor opened (the token in its params' /// [`ASKED`]), with the automation roots the cursor was loaded in: its OK, pressed outside any @@ -202,8 +205,8 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result R /// The file a click or drag of the place cursor places (`file.place` with `p`, its `rect` set): /// read off the UI thread where the files the user places are ([`crate::placing::start`]), else at /// once. When the Place dialog loaded the cursor with Show Import Options on, a file that has -/// import options asks for them first (Cancel leaves it unplaced). An error shows in the status bar. +/// import options asks for them first (Cancel leaves it unplaced); otherwise only an encrypted PDF +/// asks, for its password. An error shows in the status bar. pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) { // Read within the automation roots of whoever loaded the cursor, even on a click of the person // at the keyboard: an agent's queue reaches no file it wasn't given. let roots = app.session.place_queue_roots(); forget_older_queue(app); vectorcraft_engine::file_access::confine(roots.as_ref(), || { - if app.place.queue_asks { + let locked = is_locked(app, p); + if app.place.queue_asks || locked { let mut p = clicked_at_full_size(app, p); + if !app.place.queue_asks { + // Only its password is asked for, as File › Place with Show Import Options off. + p["showImportOptions"] = json!(false); + } // The import options it may ask for keep the token, and their OK places within the // same roots ([`place_file`]). app.place.asked = roots.clone().map(|r| { @@ -498,10 +507,17 @@ fn forget_older_queue(app: &mut VectorcraftApp) { if app.place.queue_load != app.session.place_queue_loads() { app.place.queue_asks = false; app.place.queue_sizes.clear(); + app.place.queue_locked.clear(); app.place.asked = None; } } +/// Does `p` (a cursor click's `file.place` params) name a file the cursor holds as an encrypted PDF? +fn is_locked(app: &VectorcraftApp, p: &Value) -> bool { + let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name); + name.is_some_and(|n| app.place.queue_locked.contains(&n)) +} + /// The params of a cursor click (`rect` at the file's queued size) on a PDF or DXF file, whose /// import options may change its size (another page, another scale): placed as its options place /// it at the click (`at`, the center of the box the click gave), as File › Place of that one file @@ -538,6 +554,13 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) { .flatten() .filter_map(|f| Some((f["name"].as_str()?.to_string(), f["width"].as_f64()?, f["height"].as_f64()?))) .collect(); + app.place.queue_locked = r["files"] + .as_array() + .into_iter() + .flatten() + .filter(|f| f["needsPassword"] == true) + .filter_map(|f| Some(f["name"].as_str()?.to_string())) + .collect(); app.place.thumbs = r["files"] .as_array() .into_iter() diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index f470ef49bc..0141f69403 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -1071,6 +1071,61 @@ fn the_place_cursors_files_ask_for_their_import_options_when_show_import_options assert_eq!(dialog_kind(&app), None); } +/// An encrypted PDF in the place cursor asks for its password when clicked, with Show Import +/// Options on or off, and the password's OK places it where the click put it. +#[test] +fn an_encrypted_pdf_in_the_place_cursor_asks_for_its_password_when_clicked() { + let mut app = app(); + let dir = Folder::new("ui-place-cursor-encrypted-pdf"); + let a = dir.file("a.png", &png(10, 10, 72.0)); + let pages = [PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), PdfPage::new(300.0, 100.0, "1 0 0 rg 0 0 30 30 re f")]; + let locked = dir.file("locked.pdf", &pdf(&pages, Some("pw"))); + // The click gives the box of the size the cursor holds it at, a letter page. + let click = json!({"path": locked, "link": false, "rect": [10, 10, 612, 792]}); + let center = vectorcraft_geom::Point::new(316.0, 406.0); + let placed = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let b = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap(); + (b.width().round(), b.center()) + }; + for show in [false, true] { + app.run("file.place", json!({"paths": [a, locked]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("showImportOptions".into(), json!(show)); + d.fields.insert("link".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options()["count"], 2, "kept in the cursor"); + crate::place::place_from_cursor(&mut app, &click); + let d = app.ui.dialog.as_mut().expect("the password dialog"); + assert!(d.bool("__locked")); + assert_eq!(d.fields["__place"], json!({"link": false, "at": [316.0, 406.0]})); + d.fields.insert("password".into(), json!("pw")); + crate::dialogs::confirm(&mut app).unwrap(); + if show { + // Unlocked, it asks for the page. + assert_eq!(dialog_kind(&app), Some("importPdf")); + crate::dialogs::confirm(&mut app).unwrap(); + } + assert_eq!((dialog_kind(&app), placed(&app)), (None, (100.0, center)), "Show Import Options {show}"); + } + // A cursor loaded by file.place.queue asks too, also with a `page`, which it then places. + app.run("file.place.queue", json!({"paths": [a, locked], "link": false, "page": 2})).unwrap(); + crate::place::place_from_cursor(&mut app, &json!({"path": locked, "link": false, "page": 2, "rect": [10, 10, 612, 792]})); + let d = app.ui.dialog.as_mut().expect("the password dialog"); + assert!(d.bool("__locked")); + d.fields.insert("password".into(), json!("pw")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((dialog_kind(&app), placed(&app).0), (None, 300.0), "page 2"); + // File › Place of it with a `page` and Show Import Options on asks for the password too. + crate::place::run_for_user(&mut app, &json!({"path": locked, "link": false, "page": 1})).unwrap(); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.bool("__locked"))); + app.ui.dialog = None; + // An encrypted PDF whose name has no PDF extension is still left out of the cursor. + let misnamed = dir.file("locked.dat", &pdf(&pages, Some("pw"))); + let r = app.run("file.place.queue", json!({"paths": [a, misnamed]})).unwrap(); + assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("locked.dat")), "{r}"); +} + /// A cursor loaded again after the Place dialog loaded it with Show Import Options on (a queue set /// on the Place tool) places its files at once. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..281fe5b650 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7183,7 +7183,10 @@ that draws the image does not decode the file again. `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and -`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). `file.place`, `file.place.queue` and +`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). The cursor keeps an encrypted PDF, `.ai` +or `.ait` file that it cannot read without the password, at 612 × 792 pt (VectorCraft's own size) with +`needsPassword: true` and no thumbnail; in the app a click or drag on it asks for the password, and headless it places +nothing. `file.place`, `file.place.queue` and `file.place.info` refuse, of the keys each one takes, a `link`, `replace` or `template` that is not true or false and a `thumbnail` that is not a number, naming the key, and place nothing; null is the same as leaving the key out. @@ -7194,7 +7197,8 @@ slices (Place PSD). `showImportOptions: false` places such a file without asking its dialog: the text options, the DXF fit, lineweight, centering and layer choices with the drawing at 1:1 in its own unit, and the PSD conversion, hidden-layer and Import Slices choices. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no -`password` still asks for the password. A `showImportOptions` that is not true or false is refused, and nothing is placed. The +`password` still asks for the password. An encrypted PDF given a `page` and no `password` asks for the password with +Show Import Options on too, and places that page. A `showImportOptions` that is not true or false is refused, and nothing is placed. The Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). It is on by default and saved with the preferences. On, each file that has import options asks for them before it is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 72de21a43c..bb91b61316 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1905,6 +1905,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). + - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. From f1f4d629e89881bac271d6b4572be4254e958b53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:39:43 -0800 Subject: [PATCH 31/63] Panels: the double triangle on a panel's tab strip cycles its display sizes A double triangle at the right end of the tab strip of Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency steps the active panel through its display sizes. The sizes are the states the panel menu's Show/Hide Options items set (Transparency: thumbnails and options, thumbnails alone, neither), largest first, and the smallest goes back to the largest. window.panel.cycleOptions {panel} does the same and returns {panel, size, sizes}. An unknown panel or a panel without sizes is an error and changes nothing. Docs: docs/mcp.md, docs/control-protocol.md, docs/ui-parity.md. --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panel_docking.rs | 18 ++- crates/ui-egui/src/panel_docking/sizes.rs | 128 ++++++++++++++++++++++ crates/ui-egui/src/panel_docking/tests.rs | 113 +++++++++++++++++++ docs/control-protocol.md | 1 + docs/mcp.md | 8 ++ docs/ui-parity.md | 1 + 36 files changed, 353 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/panel_docking/sizes.rs diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ecbdf780fb..ae0f0c3a5a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -650,6 +650,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..e6d1474af0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5150,6 +5150,7 @@ effect Soft Меко Change Panel Layout Промяна на оформлението на панела Close Panel Затваряне на панела Collapse Panel Group Свиване на групата панели + Cycle Display Sizes Превключване на размерите на показване Move Panel Преместване на панела Group with Групиране с Resize panels Преоразмеряване на панели diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..b46a82203a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1015,6 +1015,7 @@ Change Panel Layout Promijeni raspored panela Close Panel Zatvori panel Collapse Panel Group Skupi grupu panela + Cycle Display Sizes Mijenjaj veličine prikaza Move Panel Pomakni panel Group with Grupiši sa Resize panels Promijeni veličinu panela diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..0865ac739e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -772,6 +772,7 @@ antiAlias Sharp Nítid Preserve Numbers Conserva els números Coarse Dots Punts gruixuts Collapse Panel Group Replega el grup de panells + Cycle Display Sizes Alterna les mides de visualització Collapse Panels to Icons Replega els panells a icones Collapse to Icons Replega a icones Collate Intercala @@ -6542,6 +6543,8 @@ digits Malayalam Malaiàlam @msg unknown option `{path}.{k}` opció desconeguda `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressions desconegudes `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panell desconegut `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` no té mides de visualització per alternar +@msg the panels are not shown els panells no es mostren @msg panels can't be shown in Presentation Mode els panells no es poden mostrar en el mode de presentació @msg unknown parameter `{key}`; did you mean `{near}`? paràmetre desconegut `{key}`; volies dir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters paràmetre desconegut `{key}`; l’ordre no admet cap paràmetre diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..b1cb31d433 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1035,6 +1035,7 @@ Change Panel Layout Změnit rozložení panelů Close Panel Zavřít panel Collapse Panel Group Sbalit skupinu panelů + Cycle Display Sizes Přepínat velikosti zobrazení Move Panel Přesunout panel Group with Seskupit s Resize panels Změnit velikost panelů @@ -5434,6 +5435,8 @@ imageTrace Outline Obrys @msg unknown option `{path}.{k}` neznámá možnost `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) neznámé přetisky `{o}` (preserve, simulate nebo discard) @msg unknown panel `{raw}` neznámý panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` nemá velikosti zobrazení k přepínání +@msg the panels are not shown panely nejsou zobrazeny @msg panels can't be shown in Presentation Mode v režimu prezentace nelze panely zobrazit @msg unknown preference `{key}` neznámá předvolba `{key}` @msg Preferences imported. Předvolby byly importovány. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..ec858a8d29 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1581,6 +1581,7 @@ Change Panel Layout Skift panelets layout Close Panel Luk panel Collapse Panel Group Skjul panelgruppe + Cycle Display Sizes Skift mellem visningsstørrelser Move Panel Flyt panel Group with Gruppér med Resize panels Tilpas størrelse på paneler @@ -5549,6 +5550,8 @@ imageTrace Outline Kontur @msg unknown option `{path}.{k}` ukendt indstilling `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ukendt overprint `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` ukendt panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` har ingen visningsstørrelser at skifte mellem +@msg the panels are not shown panelerne vises ikke @msg unknown preference `{key}` ukendt præference `{key}` @msg Preferences imported. Præferencerne er importeret. @msg not a preferences file: {e} ikke en præferencefil: {e} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..4bc6a0c484 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5042,6 +5042,8 @@ theme Appearance Erscheinungsbild @msg unknown option `{path}.{k}` unbekannte Option `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) unbekannter Wert für overprints `{o}` (preserve, simulate oder discard) @msg unknown panel `{raw}` unbekanntes Bedienfeld `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` hat keine Anzeigegrößen zum Durchlaufen +@msg the panels are not shown die Bedienfelder werden nicht angezeigt @msg panels can't be shown in Presentation Mode im Präsentationsmodus können keine Bedienfelder angezeigt werden @msg unknown preference `{key}` unbekannte Voreinstellung `{key}` @msg Preferences imported. Voreinstellungen importiert. @@ -5501,6 +5503,7 @@ theme Appearance Erscheinungsbild Change Panel Layout Bedienfeldanordnung ändern Close Panel Bedienfeld schließen Collapse Panel Group Bedienfeldgruppe minimieren + Cycle Display Sizes Anzeigegrößen durchlaufen Move Panel Bedienfeld verschieben Group with Gruppieren mit Resize panel window Bedienfeldfenster skalieren diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..743cacbfac 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2726,6 +2726,7 @@ effect Soft Απαλό Change Panel Layout Αλλαγή διάταξης πάνελ Close Panel Κλείσιμο πάνελ Collapse Panel Group Σύμπτυξη ομάδας πάνελ + Cycle Display Sizes Εναλλαγή μεγεθών εμφάνισης Move Panel Μετακίνηση πάνελ Group with Ομαδοποίηση με Resize panels Αλλαγή μεγέθους πάνελ @@ -5082,6 +5083,8 @@ digits Malayalam Μαλαγιάλαμ @msg unknown option `{path}.{k}` άγνωστη επιλογή `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) άγνωστη επιλογή υπερεκτύπωσης `{o}` (preserve, simulate ή discard) @msg unknown panel `{raw}` άγνωστος πίνακας `{raw}` +@msg `{panel}` has no display sizes to cycle ο πίνακας `{panel}` δεν έχει μεγέθη εμφάνισης για εναλλαγή +@msg the panels are not shown οι πίνακες δεν εμφανίζονται @msg panels can't be shown in Presentation Mode τα πλαίσια δεν μπορούν να εμφανιστούν στη λειτουργία παρουσίασης @msg unknown preference `{key}` άγνωστη προτίμηση `{key}` @msg Preferences imported. Οι προτιμήσεις εισήχθησαν. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..bcc5114697 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5132,6 +5132,8 @@ axis Both Ambos @msg unknown option `{path}.{k}` opción desconocida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpresiones desconocidas `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panel desconocido `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` no tiene tamaños de visualización que alternar +@msg the panels are not shown los paneles no se muestran @msg panels can't be shown in Presentation Mode los paneles no se pueden mostrar en el modo de presentación @msg unknown preference `{key}` preferencia desconocida `{key}` @msg Preferences imported. Preferencias importadas. @@ -5507,6 +5509,7 @@ axis Both Ambos Change Panel Layout Cambiar distribución de paneles Close Panel Cerrar panel Collapse Panel Group Contraer grupo de paneles + Cycle Display Sizes Alternar tamaños de visualización Move Panel Mover panel Group with Agrupar con Resize panels Cambiar tamaño de los paneles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..05ec936c53 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1018,6 +1018,7 @@ Change Panel Layout Muuta paneelien asettelua Close Panel Sulje paneeli Collapse Panel Group Kutista paneeliryhmä + Cycle Display Sizes Vaihda näyttökokoa Move Panel Siirrä paneelia Group with Ryhmitä kohteen kanssa Resize panels Muuta paneelien kokoa @@ -5345,6 +5346,8 @@ imageTrace Outline Ääriviiva @msg unknown option `{path}.{k}` tuntematon asetus `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) tuntematon päällepainatusten käsittely `{o}` (preserve, simulate tai discard) @msg unknown panel `{raw}` tuntematon paneeli `{raw}` +@msg `{panel}` has no display sizes to cycle paneelissa `{panel}` ei ole vaihdettavia näyttökokoja +@msg the panels are not shown paneelit eivät ole näkyvissä @msg panels can't be shown in Presentation Mode paneeleja ei voi näyttää esitystilassa @msg unknown preference `{key}` tuntematon asetus `{key}` @msg Preferences imported. Asetukset tuotiin. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..2958fd842e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5109,6 +5109,8 @@ axis Both Les deux @msg unknown option `{path}.{k}` option inconnue `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) surimpressions inconnues `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` panneau inconnu `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` n’a pas de tailles d’affichage à parcourir +@msg the panels are not shown les panneaux ne sont pas affichés @msg panels can't be shown in Presentation Mode les panneaux ne peuvent pas être affichés en mode Présentation @msg unknown preference `{key}` préférence inconnue `{key}` @msg Preferences imported. Préférences importées. @@ -5503,6 +5505,7 @@ effect Soft Doux Change Panel Layout Modifier la disposition des panneaux Close Panel Fermer le panneau Collapse Panel Group Réduire le groupe de panneaux + Cycle Display Sizes Parcourir les tailles d’affichage Move Panel Déplacer le panneau Group with Regrouper avec Resize panels Redimensionner les panneaux diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..b97abaddb0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -611,6 +611,7 @@ Closing bracket with no opening one ખુલતા કૌંસ વગરનો બંધ થતો કૌંસ Coincidence: સંયોગ: Collapse Panel Group પેનલ ગ્રૂપ સંકોચો + Cycle Display Sizes પ્રદર્શન કદ બદલો Collapse Panels to Icons પેનલ્સને આઇકનમાં સંકોચો Collapse to Icons આઇકનમાં સંકોચો Collate ક્રમમાં ગોઠવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..5df953bd5c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -900,6 +900,7 @@ antiAlias Sharp शार्प Coarse Dots मोटे बिंदु Coincidence: संयोग: Collapse Panel Group पैनल समूह संक्षिप्त करें + Cycle Display Sizes प्रदर्शन आकार बदलें Collapse Panels to Icons सिकोड़ें करने के लिए पैनल Collapse to Icons प्रतीक के लिए पतन Collate कोलेट @@ -8620,6 +8621,8 @@ antiAlias Sharp शार्प @msg unknown overprints `{v}` (preserve, simulate or discard) अज्ञात ओवरप्रिंट `{v}` (preserve, simulate या discard) @msg unknown panel अज्ञात पैनल @msg unknown panel `{raw}` अज्ञात पैनल `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` के पास बदलने के लिए कोई प्रदर्शन आकार नहीं है +@msg the panels are not shown पैनल नहीं दिखाए गए हैं @msg panels can't be shown in Presentation Mode प्रस्तुति मोड में पैनल्स नहीं दिखाए जा सकते @msg unknown parameter `{key}`; did you mean `{near}`? अज्ञात पैरामीटर `{key}`; क्या आपको `{near}` का मतलब है? @msg unknown parameter `{key}`; the command takes no parameters अज्ञात पैरामीटर `{key}`; कमांड कोई पैरामीटर नहीं लेता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..5e4971048e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -686,6 +686,7 @@ font-technology Variable Változó Close Library Könyvtár bezárása Close Panel Panel bezárása Collapse Panel Group Panelcsoport összecsukása + Cycle Display Sizes Megjelenítési méretek váltása Close Path Útvonal lezárása Close paths when ends are within: Útvonalak lezárása, ha a végek távolsága legfeljebb: Clumped Csomós @@ -5949,6 +5950,8 @@ imageTrace Outline Körvonal @msg unknown option `{path}.{k}` ismeretlen beállítás: `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ismeretlen felülnyomás-kezelés: `{o}` (preserve, simulate vagy discard) @msg unknown panel `{raw}` ismeretlen panel: `{raw}` +@msg `{panel}` has no display sizes to cycle a(z) `{panel}` panelnek nincsenek váltható megjelenítési méretei +@msg the panels are not shown a panelek nem láthatók @msg panels can't be shown in Presentation Mode bemutató módban a panelek nem jeleníthetők meg @msg unknown preference `{key}` ismeretlen beállítás: `{key}` @msg Preferences imported. A beállítások importálva. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..32edb91429 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -957,6 +957,7 @@ Change Panel Layout Ubah tata letak panel Close Panel Tutup panel Collapse Panel Group Ciutkan grup panel + Cycle Display Sizes Ganti ukuran tampilan Move Panel Pindahkan panel Group with Grupkan dengan Resize panels Ubah ukuran panel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..14c6122876 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5171,6 +5171,8 @@ axis Both Entrambi @msg unknown option `{path}.{k}` opzione sconosciuta `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) valore di sovrastampa sconosciuto `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` pannello sconosciuto `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` non ha dimensioni di visualizzazione da scorrere +@msg the panels are not shown i pannelli non sono visualizzati @msg panels can't be shown in Presentation Mode i pannelli non possono essere mostrati in modalità presentazione @msg unknown preference `{key}` preferenza sconosciuta `{key}` @msg Preferences imported. Preferenze importate. @@ -5548,6 +5550,7 @@ effect Regular Normale Change Panel Layout Modifica disposizione dei pannelli Close Panel Chiudi pannello Collapse Panel Group Comprimi gruppo di pannelli + Cycle Display Sizes Scorri le dimensioni di visualizzazione Move Panel Sposta pannello Group with Raggruppa con Resize panels Ridimensiona pannelli diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..49ee217a66 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5108,6 +5108,8 @@ swatch Bright Violet ビビッドバイオレット @msg give only one of onto, below and above onto、below、above のうち 1 つだけを指定してください @msg column must be true or a number from 1 column には true または 1 以上の数値を指定してください @msg unknown panel `{raw}` `{raw}` は不明なパネルです +@msg `{panel}` has no display sizes to cycle `{panel}` には切り替える表示サイズがありません +@msg the panels are not shown パネルが表示されていません @msg panels can't be shown in Presentation Mode プレゼンテーションモードではパネルを表示できません @msg x and y must both be numbers x と y はどちらも数値で指定してください @msg Downloaded {what} {what} をダウンロードしました @@ -5591,6 +5593,7 @@ effect Vertical 垂直 Change Panel Layout パネルの配置を変更 Close Panel パネルを閉じる Collapse Panel Group パネルグループを折りたたむ + Cycle Display Sizes 表示サイズを切り替え Move Panel パネルを移動 Group with グループ化先 Resize panels パネルのサイズを変更 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2864881e87..0aa64688f5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3008,6 +3008,7 @@ Change Panel Layout პანელების განლაგების შეცვლა Close Panel პანელის დახურვა Collapse Panel Group პანელების ჯგუფის აკეცვა + Cycle Display Sizes ჩვენების ზომების გადართვა Move Panel პანელის გადაადგილება Group with ერთად დაჯგუფება Resize panels პანელების ზომის შეცვლა @@ -6858,6 +6859,8 @@ font-technology Variable ცვლადი @msg unknown option `{path}.{k}` უცნობი პარამეტრი `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) უცნობი ზედდაბეჭდვა `{o}` (preserve, simulate ან discard) @msg unknown panel `{raw}` უცნობი პანელი `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` პანელს არ აქვს გადასართავი ჩვენების ზომები +@msg the panels are not shown პანელები არ ჩანს @msg panels can't be shown in Presentation Mode პრეზენტაციის რეჟიმში პანელების ჩვენება შეუძლებელია @msg unknown preference `{key}` უცნობი პარამეტრი `{key}` @msg Preferences imported. პარამეტრები იმპორტირებულია. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..69513cad5a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5035,6 +5035,8 @@ theme Appearance 외관 @msg give only one of onto, below and above onto, below, above 중 하나만 지정하세요 @msg column must be true or a number from 1 column은 true이거나 1 이상의 숫자여야 합니다 @msg unknown panel `{raw}` 알 수 없는 패널 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}`에는 전환할 표시 크기가 없습니다 +@msg the panels are not shown 패널이 표시되지 않습니다 @msg panels can't be shown in Presentation Mode 프레젠테이션 모드에서는 패널을 표시할 수 없습니다 @msg x and y must both be numbers x와 y는 모두 숫자여야 합니다 @msg Downloaded {what} {what}을(를) 다운로드했습니다 @@ -5516,6 +5518,7 @@ effect Vertical 세로 Change Panel Layout 패널 레이아웃 변경 Close Panel 패널 닫기 Collapse Panel Group 패널 그룹 접기 + Cycle Display Sizes 표시 크기 전환 Move Panel 패널 이동 Group with 함께 그룹화 Resize panels 패널 크기 조절 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..edef345ce1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1477,6 +1477,7 @@ Change Panel Layout Paneelindeling wijzigen Close Panel Paneel sluiten Collapse Panel Group Paneelgroep samenvouwen + Cycle Display Sizes Weergavegrootten doorlopen Move Panel Paneel verplaatsen Group with Groeperen met Resize panels Panelen van formaat wijzigen @@ -5445,6 +5446,8 @@ imageTrace Outline Contour @msg unknown option `{path}.{k}` onbekende optie `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) onbekende overdruk `{o}` (preserve, simulate of discard) @msg unknown panel `{raw}` onbekend paneel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` heeft geen weergavegrootten om te doorlopen +@msg the panels are not shown de panelen worden niet getoond @msg unknown preference `{key}` onbekende voorkeur `{key}` @msg Preferences imported. Voorkeuren geïmporteerd. @msg not a preferences file: {e} geen voorkeurenbestand: {e} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..7ba2c97742 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -975,6 +975,7 @@ Change Panel Layout Zmień układ paneli Close Panel Zamknij panel Collapse Panel Group Zwiń grupę paneli + Cycle Display Sizes Przełącz rozmiary wyświetlania Move Panel Przesuń panel Group with Grupuj z Resize panels Zmień rozmiar paneli @@ -5260,6 +5261,8 @@ imageTrace Outline Kontur @msg unknown option `{path}.{k}` nieznana opcja `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) nieznana wartość nadruków `{o}` (preserve, simulate lub discard) @msg unknown panel `{raw}` nieznany panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` nie ma rozmiarów wyświetlania do przełączania +@msg the panels are not shown panele nie są wyświetlane @msg panels can't be shown in Presentation Mode w trybie prezentacji nie można wyświetlić paneli @msg unknown preference `{key}` nieznana preferencja `{key}` @msg Preferences imported. Zaimportowano preferencje. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..9a0fd94428 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3544,6 +3544,7 @@ imageTrace Outline Contorno Change Panel Layout Alterar Layout dos Painéis Close Panel Fechar Painel Collapse Panel Group Recolher Grupo de Painéis + Cycle Display Sizes Alternar Tamanhos de Exibição Move Panel Mover Painel Group with Agrupar com Resize panels Redimensionar painéis @@ -4490,6 +4491,8 @@ axis Both Ambos @msg unknown option `{path}.{k}` opção desconhecida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressões desconhecidas `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` painel desconhecido `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` não tem tamanhos de exibição para alternar +@msg the panels are not shown os painéis não estão sendo exibidos @msg panels can't be shown in Presentation Mode os painéis não podem ser mostrados no Modo de Apresentação @msg unknown preference `{key}` preferência desconhecida `{key}` @msg Preferences imported. Preferências importadas. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..b7ce3c4a99 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5169,6 +5169,8 @@ axis Both Оба @msg unknown option `{path}.{k}` неизвестный параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) неизвестные наложения `{o}` (preserve, simulate или discard) @msg unknown panel `{raw}` неизвестная панель `{raw}` +@msg `{panel}` has no display sizes to cycle у панели `{panel}` нет размеров отображения для переключения +@msg the panels are not shown панели не показаны @msg panels can't be shown in Presentation Mode в режиме презентации панели показать нельзя @msg unknown preference `{key}` неизвестная настройка `{key}` @msg Preferences imported. Настройки импортированы. @@ -5546,6 +5548,7 @@ axis Both Оба Change Panel Layout Изменить расположение панелей Close Panel Закрыть панель Collapse Panel Group Свернуть группу панелей + Cycle Display Sizes Переключить размеры отображения Move Panel Переместить панель Group with Сгруппировать с Resize panels Изменить размер панелей diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..343f65b7f5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5024,6 +5024,8 @@ axis Both Båda @msg unknown option `{path}.{k}` okänt alternativ `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) okänt värde för övertryck `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` okänd panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` har inga visningsstorlekar att växla mellan +@msg the panels are not shown panelerna visas inte @msg panels can't be shown in Presentation Mode paneler kan inte visas i presentationsläge @msg unknown preference `{key}` okänd inställning `{key}` @msg Preferences imported. Inställningarna har importerats. @@ -5415,6 +5417,7 @@ effect Soft Mjuk Change Panel Layout Ändra panellayout Close Panel Stäng panel Collapse Panel Group Komprimera panelgrupp + Cycle Display Sizes Växla visningsstorlekar Move Panel Flytta panel Group with Gruppera med Resize panels Ändra storlek på paneler diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..1a7e54b161 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4876,6 +4876,8 @@ axis Both Her İkisi @msg unknown option `{path}.{k}` bilinmeyen seçenek `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) bilinmeyen üst baskılar `{o}` (preserve, simulate veya discard) @msg unknown panel `{raw}` bilinmeyen panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` panelinde geçiş yapılacak görüntü boyutu yok +@msg the panels are not shown paneller gösterilmiyor @msg panels can't be shown in Presentation Mode Sunum Modunda paneller gösterilemez @msg unknown preference `{key}` bilinmeyen tercih `{key}` @msg Preferences imported. Tercihler içe aktarıldı. @@ -6487,6 +6489,7 @@ theme Appearance Görünüm @msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın Collapse Panel Group Panel Grubunu Daralt + Cycle Display Sizes Görüntü Boyutları Arasında Geçiş Yap @msg panel is not in a dock group panel bir yuva grubunda değil @msg only a dock group above or below others collapses, not one beside another yalnızca diğerlerinin üstünde veya altındaki bir yuva grubu daraltılabilir, yanındaki değil @msg icon must be true or false icon true veya false olmalı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..0d330a2ad2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5155,6 +5155,8 @@ axis Both Обидві @msg unknown option `{path}.{k}` невідомий параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) невідомі накладення `{o}` (preserve, simulate або discard) @msg unknown panel `{raw}` невідома панель `{raw}` +@msg `{panel}` has no display sizes to cycle панель `{panel}` не має розмірів відображення для перемикання +@msg the panels are not shown панелі не показано @msg panels can't be shown in Presentation Mode у режимі презентації панелі показати не можна @msg unknown preference `{key}` невідоме налаштування `{key}` @msg Preferences imported. Налаштування імпортовано. @@ -5530,6 +5532,7 @@ axis Both Обидві Change Panel Layout Змінити розташування панелей Close Panel Закрити панель Collapse Panel Group Згорнути групу панелей + Cycle Display Sizes Перемкнути розміри відображення Move Panel Перемістити панель Group with Згрупувати з Resize panels Змінити розмір панелей diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..09a41c0cc2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -598,6 +598,7 @@ font-technology Variable Biến thiên Close Library Đóng thư viện Close Panel Đóng bảng Collapse Panel Group Thu gọn nhóm bảng + Cycle Display Sizes Chuyển kích thước hiển thị Close Path Đóng đường dẫn Close paths when ends are within: Đóng đường dẫn khi hai đầu cách nhau trong: Clumped Dạng cụm @@ -5691,6 +5692,8 @@ theme Appearance Giao diện @msg unknown option `{path}.{k}` tùy chọn không xác định `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) chế độ in đè không xác định `{o}` (preserve, simulate hoặc discard) @msg unknown panel `{raw}` bảng không xác định `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` không có kích thước hiển thị để chuyển +@msg the panels are not shown các bảng không được hiển thị @msg panels can't be shown in Presentation Mode không thể hiển thị bảng trong chế độ trình bày @msg unknown parameter `{key}`; did you mean `{near}`? tham số không xác định `{key}`; ý bạn là `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tham số không xác định `{key}`; lệnh này không nhận tham số diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..9db0295a11 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4789,6 +4789,8 @@ imageTrace Outline 轮廓 @msg give only one of onto, below and above onto、below 和 above 只能给出一个 @msg column must be true or a number from 1 column 必须是 true 或从 1 开始的数字 @msg unknown panel `{raw}` 未知面板 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` 没有可切换的显示大小 +@msg the panels are not shown 面板未显示 @msg panels can't be shown in Presentation Mode 演示模式下无法显示面板 @msg x and y must both be numbers x 和 y 都必须是数字 @msg Downloaded {what} 已下载 {what} @@ -5830,6 +5832,7 @@ effect Vertical 垂直 Change Panel Layout 更改面板布局 Close Panel 关闭面板 Collapse Panel Group 折叠面板组 + Cycle Display Sizes 切换显示大小 Move Panel 移动面板 Group with 组合到 Resize panels 调整面板大小 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..a2c5a44ed7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2437,6 +2437,8 @@ file-filter Templates 範本 @msg give only one of onto, below and above onto、below 和 above 只能提供其中一個 @msg column must be true or a number from 1 column 必須是 true 或從 1 起算的數字 @msg unknown panel `{raw}` 未知的面板 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` 沒有可切換的顯示大小 +@msg the panels are not shown 面板未顯示 @msg panels can't be shown in Presentation Mode 簡報模式下無法顯示面板 @msg x and y must both be numbers x 和 y 都必須是數字 @msg Downloaded {what} 已下載 {what} @@ -5666,6 +5668,7 @@ effect Soft 柔和 Change Panel Layout 變更面板配置 Close Panel 關閉面板 Collapse Panel Group 摺疊面板群組 + Cycle Display Sizes 切換顯示大小 Move Panel 移動面板 Group with 群組至 Resize panels 調整面板大小 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c099422957..4ecff55718 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -651,6 +651,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 5b4913d552..0a4f01879d 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -316,7 +316,7 @@ fn apply(layout: &mut Layout, action: Action) -> Result Option> { if let Some(result) = crate::tools_float::command(app, id, params) { @@ -326,6 +326,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, params: &Value) -> Opt "window.panel" => return Some(show_panel(app, params)), "window.collapseDock" => return Some(crate::menus::opt_bool(params, "collapsed").and_then(|c| collapse_dock(app, c))), "window.panels.peek" => return Some(peek::command(app, params)), + "window.panel.cycleOptions" => return Some(sizes::command(app, params)), "window.panel.collapse" => { let minimized = match crate::menus::opt_bool(params, "collapsed") { Ok(c) => c, @@ -1472,13 +1473,21 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { crate::panels::panel_menu_items(self.app, ui, id); } - fn group_header_width(&self, panels: &[String], _active: &String, floating: bool, _strip_width: f32) -> f32 { + fn group_header_width(&self, panels: &[String], active: &String, floating: bool, _strip_width: f32) -> f32 { let flyout = self.app.ui.open_panel.as_ref().is_some_and(|panel| panels.contains(panel)); - if floating || flyout { 52.0 } else { 28.0 } + let cycle = if sizes::has_sizes(active) { sizes::CELL } else { 0.0 }; + cycle + if floating || flyout { 52.0 } else { 28.0 } } fn group_header(&mut self, ui: &mut egui::Ui, panels: &[String], active: &String, floating: bool) { - let header = ui.max_rect(); + let mut header = ui.max_rect(); + // The double triangle comes first, for a panel with display sizes. + if sizes::has_sizes(active) { + let split = (header.left() + sizes::CELL).min(header.right()); + let cell = egui::Rect::from_min_max(header.min, egui::pos2(split, header.bottom())); + sizes::button(self.app, ui, cell, active); + header.min.x = split; + } let flyout = self.app.ui.open_panel.clone().filter(|panel| panels.contains(panel)); let menu_cell = if floating || flyout.is_some() { let split = (header.right() - 28.0).max(header.left()); @@ -1523,6 +1532,7 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } mod peek; +mod sizes; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/panel_docking/sizes.rs b/crates/ui-egui/src/panel_docking/sizes.rs new file mode 100644 index 0000000000..283b348696 --- /dev/null +++ b/crates/ui-egui/src/panel_docking/sizes.rs @@ -0,0 +1,128 @@ +//! A panel's display sizes: the double triangle at the end of its tab strip steps through them +//! (`window.panel.cycleOptions`). A size is a set of the panel's Hide Options, Hide Thumbnails +//! and Show Options states, the ones its panel menu already sets, so the menu and the control +//! always agree. The sizes go from the largest to the smallest, and the smallest is followed by +//! the largest again. A panel whose parts are in no size's states goes to its largest size. + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::panels::{pstate, set_pstate}; + +/// A part of a panel that can be hidden. +#[derive(Clone, Copy, Debug)] +enum Part { + /// A Hide flag the panel keeps with its panel state ([`pstate`]), true while hidden. + Hide(&'static str), + /// The Color panel's Hide Options, kept with the preferences. + ColorOptions, + /// The Flattener Preview panel's Show Options. + FlattenerOptions, +} + +/// A panel that has display sizes: its parts, and the parts each size hides, largest first. +struct Sizes { + panel: &'static str, + parts: &'static [Part], + sizes: &'static [&'static [bool]], +} + +/// Options shown, then hidden. +const OPTIONS: &[&[bool]] = &[&[false], &[true]]; + +/// The panels with display sizes. +const PANELS: &[Sizes] = &[ + Sizes { panel: "align", parts: &[Part::Hide("align-hide-options")], sizes: OPTIONS }, + Sizes { panel: "attributes", parts: &[Part::Hide("attr-hide-options")], sizes: OPTIONS }, + Sizes { panel: "character", parts: &[Part::Hide("ch-hide-options")], sizes: OPTIONS }, + Sizes { panel: "color", parts: &[Part::ColorOptions], sizes: OPTIONS }, + Sizes { panel: crate::panels::flattener_preview::ID, parts: &[Part::FlattenerOptions], sizes: OPTIONS }, + Sizes { panel: "gradient", parts: &[Part::Hide("gradient-hide-options")], sizes: OPTIONS }, + Sizes { panel: "info", parts: &[Part::Hide("info-hide-options")], sizes: OPTIONS }, + Sizes { panel: "paragraph", parts: &[Part::Hide("pa-hide-options")], sizes: OPTIONS }, + Sizes { panel: "stroke", parts: &[Part::Hide("stroke-hide-options")], sizes: OPTIONS }, + Sizes { panel: "transform", parts: &[Part::Hide("xf-hide-options")], sizes: OPTIONS }, + // Thumbnails and options, then thumbnails alone, then neither. + Sizes { + panel: "transparency", + parts: &[Part::Hide("tr-hide-thumbs"), Part::Hide("tr-hide-options")], + sizes: &[&[false, false], &[false, true], &[true, true]], + }, +]; + +fn sizes_of(panel: &str) -> Option<&'static Sizes> { + PANELS.iter().find(|s| s.panel == panel) +} + +/// Does `panel` have display sizes to step through? +pub(crate) fn has_sizes(panel: &str) -> bool { + sizes_of(panel).is_some() +} + +fn hidden(app: &VectorcraftApp, ctx: &egui::Context, part: Part) -> bool { + match part { + Part::Hide(key) => pstate(ctx, key), + Part::ColorOptions => app.ui.color_hide_options, + Part::FlattenerOptions => !app.ui.flattener_preview.show_options, + } +} + +fn set_hidden(app: &mut VectorcraftApp, ctx: &egui::Context, part: Part, hide: bool) { + match part { + Part::Hide(key) => set_pstate(ctx, key, hide), + Part::ColorOptions => app.ui.color_hide_options = hide, + Part::FlattenerOptions => app.ui.flattener_preview.show_options = !hide, + } +} + +/// The size `panel` shows now (0 is the largest), or `None` when its parts match no size. +fn current(app: &VectorcraftApp, ctx: &egui::Context, sizes: &Sizes) -> Option { + let now: Vec = sizes.parts.iter().map(|&part| hidden(app, ctx, part)).collect(); + sizes.sizes.iter().position(|size| *size == now.as_slice()) +} + +/// `window.panel.cycleOptions {panel}`: show `panel` at its next display size, as the double +/// triangle on its tab strip does. An unknown panel, a panel without display sizes, or no panels +/// drawn yet is an error, and then nothing changes. → {panel, size, sizes}: the size shown now +/// (0 is the largest) and how many sizes the panel has. +pub(crate) fn command(app: &mut VectorcraftApp, params: &Value) -> Result { + let raw = params.get("panel").and_then(Value::as_str).unwrap_or_default(); + let panel = super::normalize(raw).ok_or_else(|| format!("unknown panel `{raw}`"))?; + let sizes = sizes_of(panel).ok_or_else(|| format!("`{panel}` has no display sizes to cycle"))?; + let ctx = app.ui_ctx.clone().ok_or("the panels are not shown")?; + let next = current(app, &ctx, sizes).map_or(0, |i| (i + 1) % sizes.sizes.len()); + for (&part, &hide) in sizes.parts.iter().zip(sizes.sizes[next]) { + set_hidden(app, &ctx, part, hide); + } + ctx.request_repaint(); + Ok(json!({"panel": panel, "size": next, "sizes": sizes.sizes.len()})) +} + +/// Width of the double triangle's cell at the start of a group header. +pub(crate) const CELL: f32 = 20.0; + +/// Draw the double triangle for `panel` centered in `cell`; a click shows its next size. +pub(crate) fn button(app: &mut VectorcraftApp, ui: &mut egui::Ui, cell: egui::Rect, panel: &str) { + let rect = egui::Rect::from_center_size(cell.center(), egui::vec2(16.0_f32.min(cell.width()), 22.0_f32.min(cell.height()))); + if !rect.is_positive() { + return; + } + let label = tl!("Cycle Display Sizes"); + let response = ui.interact(rect, ui.scope_id().with(("cycle-display-sizes", panel)), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + let tokens = crate::theme::Tokens::get(ui.ctx()); + let color = if response.hovered() || response.has_focus() { tokens.text_strong } else { tokens.text_dim }; + let c = rect.center(); + let (w, h, gap) = (3.5, 3.5, 1.5); + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + let up = vec![egui::pos2(c.x - w, c.y - gap), egui::pos2(c.x + w, c.y - gap), egui::pos2(c.x, c.y - gap - h)]; + let down = vec![egui::pos2(c.x - w, c.y + gap), egui::pos2(c.x, c.y + gap + h), egui::pos2(c.x + w, c.y + gap)]; + for points in [up, down] { + painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); + } + if response.on_hover_text(label).clicked() + && let Err(error) = app.run("window.panel.cycleOptions", json!({"panel": panel})) + { + app.ui.status = error; + } +} diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 2c95ff0e16..ec9f3d0b5a 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1702,3 +1702,116 @@ fn rail_flyout_collapse_arrow_closes_the_opening_icon_after_switching_tabs() { assert!(craft_ui::docking::flyout::(&h.ctx, area_id()).is_none()); assert_eq!(h.layout(), before, "all tabs and their active state stay in the rail"); } + +/// The texts `panel`'s menu draws, in the harness's context. +fn panel_menu_texts(h: &mut Harness, panel: &str) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().trim().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let app = &mut h.app; + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(SCREEN), ..Default::default() }, |ui| { + crate::panels::panel_menu_items(app, ui, panel); + }); + out.textures_delta.clear(); + let mut v = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + v +} + +fn cycle_button(h: &Harness, panel: &str) -> Option { + let panel = panel.to_string(); + h.ctx.read_response(area_id().with(("header", &panel)).with(("cycle-display-sizes", &panel))).map(|r| r.rect) +} + +/// Each panel with display sizes steps between the states its panel menu's Show/Hide Options +/// item sets, and the smallest size goes back to the largest. +#[test] +fn cycle_options_steps_through_the_states_the_panel_menu_sets() { + let mut h = Harness::new(); + for panel in ["align", "attributes", "character", "color", "gradient", "info", "paragraph", "stroke", "transform"] { + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Hide Options"), "{panel} starts with its options"); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": panel})).unwrap(); + assert_eq!(r, json!({"panel": panel, "size": 1, "sizes": 2}), "{panel}"); + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Show Options"), "{panel} hides its options"); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": panel})).unwrap(); + assert_eq!(r["size"], 0, "{panel}"); + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Hide Options"), "{panel} shows them again"); + } + // The Flattener Preview's options start hidden: its first step shows them, as Show Options does. + assert!(!h.app.ui.flattener_preview.show_options); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": "Flattener Preview"})).unwrap(); + assert_eq!(r, json!({"panel": crate::panels::flattener_preview::ID, "size": 0, "sizes": 2})); + assert!(h.app.ui.flattener_preview.show_options); + h.app.run("window.panel.cycleOptions", json!({"panel": crate::panels::flattener_preview::ID})).unwrap(); + assert!(!h.app.ui.flattener_preview.show_options); + // Transparency: thumbnails and options, thumbnails alone, neither, and back. + let shown = |h: &mut Harness| { + let t = panel_menu_texts(h, "transparency"); + (t.iter().any(|t| t == "Hide Thumbnails"), t.iter().any(|t| t == "Hide Options")) + }; + assert_eq!(shown(&mut h), (true, true)); + for (size, want) in [(1, (true, false)), (2, (false, false)), (0, (true, true))] { + let r = h.app.run("window.panel.cycleOptions", json!({"panel": "transparency"})).unwrap(); + assert_eq!((r["size"].clone(), r["sizes"].clone()), (json!(size), json!(3))); + assert_eq!(shown(&mut h), want, "size {size}"); + } + // Options hidden with the thumbnails shown matches no size, so the next step is the largest. + crate::panels::set_pstate(&h.ctx, "tr-hide-thumbs", true); + assert_eq!(h.app.run("window.panel.cycleOptions", json!({"panel": "transparency"})).unwrap()["size"], 0); + assert_eq!(shown(&mut h), (true, true)); +} + +/// An unknown panel, a panel without display sizes or a missing `panel` is an error, and the +/// panels keep their sizes. +#[test] +fn cycle_options_rejects_panels_without_sizes() { + let mut h = Harness::new(); + for (params, error) in [ + (json!({"panel": "nope"}), "unknown panel `nope`"), + (json!({}), "unknown panel ``"), + (json!({"panel": 3}), "unknown panel ``"), + (json!({"panel": "layers"}), "`layers` has no display sizes to cycle"), + (json!({"panel": "swatches"}), "`swatches` has no display sizes to cycle"), + ] { + assert_eq!(h.app.run("window.panel.cycleOptions", params.clone()).unwrap_err(), error, "{params}"); + } + assert!(panel_menu_texts(&mut h, "stroke").iter().any(|t| t == "Hide Options")); + assert!(!h.app.ui.color_hide_options); +} + +/// The double triangle shows on the tab strip of a panel with display sizes, docked or floating, +/// and a click on it shows the panel's next size; other panels have none. +#[test] +fn the_double_triangle_on_the_tab_strip_cycles_the_display_sizes() { + let mut h = Harness::new(); + h.ctx.enable_accesskit(); + h.frame(vec![]); + assert!(cycle_button(&h, "properties").is_none() && cycle_button(&h, "layers").is_none(), "the main column's panels have no sizes"); + h.app.run("window.panel.float", json!({"panel": "stroke"})).unwrap(); + for _ in 0..3 { + h.frame(vec![]); + } + let control = cycle_button(&h, "stroke").expect("a floating Stroke panel has the double triangle"); + assert!(h.nodes.iter().any(|(_, node)| node.label() == Some("Cycle Display Sizes")), "screen readers name it"); + let menu = h.ctx.read_response(area_id().with(("header", &"stroke".to_string())).with(("panel-menu", &"stroke".to_string()))).unwrap().rect; + assert!(!menu.intersects(control), "the double triangle and the menu have separate hit targets"); + h.click(control.center()); + assert!(crate::panels::pstate::(&h.ctx, "stroke-hide-options"), "a click hides the options"); + assert!(floating_window(&h.layout(), "stroke").is_some(), "the panel stays where it is"); + h.click(control.center()); + assert!(!crate::panels::pstate::(&h.ctx, "stroke-hide-options"), "a second click shows them again"); + // A docked panel's tab strip has it too, and a floating panel without sizes does not. + h.app.run("window.panel.dock", json!({"panel": "color", "anchor": "layers", "zone": "below"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "swatches"})).unwrap(); + for _ in 0..3 { + h.frame(vec![]); + } + let control = cycle_button(&h, "color").expect("a docked Color panel has the double triangle"); + h.click(control.center()); + assert!(h.app.ui.color_hide_options); + assert!(cycle_button(&h, "swatches").is_none()); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b0bd90eb59..76ad9628d1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1061,6 +1061,7 @@ Commands (`panel` and every panel parameter take a panel id in any case or its d | `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` | shows and selects, or hides | | `window.panel.minimize` | `{panel, minimized?}` | minimizes a dock group to its tabs, or a floating window to its title bar; omitted toggles | | `window.panel.collapse` | `{panel, collapsed?}` | `window.panel.minimize`; returns `{panel, collapsed, layout}` | +| `window.panel.cycleOptions` | `{panel}` | shows the panel at its next display size (its Show/Hide Options states, largest first), as the double triangle on its tab strip does; a panel without sizes is an error; returns `{panel, size, sizes}` | | `window.panel.iconic` | `{panel, iconic?}` | collapses the panel's dock column to icons, or expands it | | `window.panel.layout`, `ui.dock` | `{action}` | one craft-ui `Action`, externally tagged, e.g. `{"MoveFloating":{"panel":"swatches","rect":[44,66,360,450]}}` or `{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}`; `ui.dock` also takes craft-ui's `{operation, …}` | diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..a524cdaf60 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3374,6 +3374,14 @@ already walks Image Trace. Short agent entry points: `largeList`. Without `view` the command answers the current one. Each panel keeps its own view for the session, and the document does not change. An unknown panel or view is an error, and then nothing changes. It answers `{panel, view}`. +- Panel display sizes: `window.panel.cycleOptions {panel}` shows the panel at its next display size, as the double + triangle at the right end of its tab strip does, docked or floating. The sizes are the states its panel menu's Show + Options and Hide Options items set, largest first, and the smallest is followed by the largest. Align, Attributes, + Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke and Transform have two sizes (options shown, + options hidden). Transparency has three: thumbnails and options, thumbnails alone, and neither. A panel whose + states match none of its sizes goes to its largest. An unknown panel or a panel without display sizes is an error, + and then nothing changes. It answers `{panel, size, sizes}`, where `size` 0 is the largest. The order of the sizes + and the panels that have them are VectorCraft's own. - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 071c8d4719..b3f3b7d86f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -405,6 +405,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Floating groups stack into sets; sets dock as extra dock columns (a multi-column dock); groups drop anywhere in a set or column, or onto its tabs; a column taller than the window scrolls | done | `window.panel.float {below, above}`, `window.panel.dock {column}` | | Panels dragged onto a dock group's tabs join it; onto its upper or lower half they make a new group above or below it (a top/bottom split, resizable); onto the icon column they become icons, the tabbed group's panels too; a dock tab's context menu closes it (Window menu reopens it) | done | `window.panel.dock {anchor, zone}`, `window.panel.dock {icon: true}`, `window.panel.close` | | A double-click on a dock group's tab collapses the group to its tabs (a group below it moves up into the room) and a second one expands it; a click on another of its tabs expands it showing that panel ([helpx: Workspace basics](https://helpx.adobe.com/illustrator/using/workspace-basics.html), panel groups) | done | `window.panel.collapse {panel, collapsed?}`; in dock groups and floating windows; a group beside another (a left/right split) doesn't collapse | +| The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | | Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | | Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | | Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | From 303d0c0a050eba7c8a069eda60f01355df49c619 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:45:10 -0800 Subject: [PATCH 32/63] PSD: a version 6 slice record whose ID is 16 is read as a slice A version 6 slices resource may follow a record with a descriptor of version 16, and the reader took any record that starts with the value 16 for one. A record whose ID is 16 then had its first bytes read as a descriptor, and the records after it were misread or left out. When the records read one after another, followed by nothing or by one descriptor (the layout ag-psd writes), only the last record is checked for a descriptor. Files that follow each record with a descriptor are read as before. --- crates/engine/src/cmd/fileio/psdslices.rs | 50 ++++++++++++++++--- .../engine/src/cmd/fileio/tests_psdslices.rs | 26 ++++++++++ 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs index ea87f70797..d0cd21a8e9 100644 --- a/crates/engine/src/cmd/fileio/psdslices.rs +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St if count > MAX_SLICES { return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read")); } + let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget); let mut out = vec![]; - for _ in 0..count { + for i in 0..count { // The ID and group ID. r.take(8)?; let origin = r.u32()?; @@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St format!("#{red:02x}{green:02x}{blue:02x}") }; // Photoshop 7 and later may follow a record with a descriptor (version 16); a record that - // doesn't start one is the next slice. A descriptor read that uses up the budget is an - // error. - if r.rest().starts_with(&16u32.to_be_bytes()) { + // doesn't start one is the next slice. When the records follow one another, only the + // last one may be followed by a descriptor. A descriptor read that uses up the budget is + // an error. + if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) { let mut ahead = Reader::new(r.rest()); ahead.u32()?; match descriptor(&mut ahead, 0, budget) { @@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St Ok(out) } +/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one +/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is +/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor. +fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool { + if !(0..count).all(|_| skip_record(&mut r).is_ok()) { + return false; + } + r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok()) +} + +/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings +/// are checked and read past without being decoded. +fn skip_record(r: &mut Reader<'_>) -> Result<(), String> { + // The ID and group ID. + r.take(8)?; + if r.u32()? == 1 { + r.take(4)?; + } + units(r)?; + // The type and the rectangle. + r.take(20)?; + for _ in 0..4 { + units(r)?; + } + r.take(1)?; + units(r)?; + // The alignments and the background color. + r.take(12)?; + Ok(()) +} + /// Versions 7 and 8: the descriptor's `slices` list, each slice an object. fn from_descriptor(d: &[(String, Value)]) -> Result, String> { let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) }; @@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result { /// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped. fn unicode(r: &mut Reader<'_>) -> Result { - let n = text_len(r.u32()? as usize)?; - let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?; + let bytes = units(r)?; let units: Vec = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect(); Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) } +/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units. +fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> { + let n = text_len(r.u32()? as usize)?; + r.take(n.checked_mul(2).ok_or(TRUNCATED)?) +} + /// A descriptor's value, as far as the slices need it. #[derive(Clone, Debug, PartialEq)] enum Value { diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 42dc33c600..97eb17bcac 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() { assert_eq!(names, ["a", "b"]); } +#[test] +fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() { + // The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18 + // bytes also read as a descriptor of version 16 with no items. + let records: Vec = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect(); + let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat(); + for trailing in [vec![], descriptor_after] { + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 17, "{got:?}"); + assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), "")); + assert_eq!(got[16].1.name, "a"); + } + // A descriptor after each record whose class ID is four zero bytes, with no items, followed by + // records with no strings: the records don't also read one after another. + let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat(); + let trailing = [16u32.to_be_bytes().to_vec(), empty].concat(); + for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] { + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({})); + let w = warnings(&r); + assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}"); + assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}"); + } +} + #[test] fn version_6_descriptors_share_one_budget_of_values() { // Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold; From 24867f7827cd401e1ecb9069786bbb30d8c66cf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:53:31 -0800 Subject: [PATCH 33/63] Paste: legend labels in a pie's wedges follow wedges that take the document's swatch When a pasted pie's wedge links a global swatch that the document gives another color (swatchConflict "merge", the default), the wedge takes the document's color. Its legend label kept the contrast it had in the copy, so a wedge that turned dark could show a black label, and one that turned light a white label, until the pie was drawn again. Pasting now reads which wedges show a dark fill before the copy is linked to the document's swatches. A pie whose wedges change darkness gets the legend label contrast a redraw sets: white on a dark wedge, black on a light one. Pies whose legend labels have a fill of their own keep it. This applies to every paste command, Paste without Formatting included, and to pies inside opacity masks. --- crates/engine/src/cmd/clipboard/resources.rs | 5 +- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/graph.rs | 6 +- crates/engine/src/cmd/graph/series.rs | 63 ++++++++++++++++ crates/engine/src/tests/clipboard.rs | 78 ++++++++++++++++++++ docs/mcp.md | 6 +- 6 files changed, 153 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..932ad3a1a3 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1031,10 +1031,13 @@ impl Imported { self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone()); } } - /// Point a pasted copy at the document's resources. + /// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the + /// other darkness take the contrast a redraw sets there. pub(crate) fn apply(&self, n: &mut Node) { if self.relinks { + let shades = super::super::graph::wedge_shades(n); self.relink.node(n); + super::super::graph::follow_wedge_shades(n, &shades); } } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..0ac559c874 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 7be0a122df..11a41174c1 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -49,9 +49,9 @@ use generate::generate; use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art, - label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, - series_marks_in, series_object_opacity_differs, shown_paint, + capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, + is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, + series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index ee33f23517..c3cf55ca60 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1,4 +1,5 @@ use vectorcraft_color::BlendMode; +use vectorcraft_doc::swatches::walk_with_masks; use vectorcraft_geom::Shape; use super::axis::radar_axis; @@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap) { } } +/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included) +/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a +/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`]. +pub(crate) fn wedge_shades(n: &Node) -> HashMap> { + let mut out = HashMap::new(); + walk_with_masks(n, &mut |m| { + if let Some(g) = m.extras().graph.as_deref() + && g.kind == GraphKind::Pie + && g.legend + && g.pie_legend_in_wedges + && !g.label_styles.legend_fill_is_own() + { + out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect()); + } + }); + out +} + +/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a +/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept +/// their darkness keep their labels as they are. +pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap>) { + let mut changed = vec![]; + walk_with_masks(n, &mut |m| { + if let Some(before) = was.get(&m.id) + && pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied()) + { + changed.push(m.id); + } + }); + if !changed.is_empty() { + restore_contrast(n, &changed); + } +} + +/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw +/// sets them on their wedges. +fn restore_contrast(n: &mut Node, ids: &[NodeId]) { + if ids.contains(&n.id) { + let on_dark = match n.extras().graph.as_deref() { + Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)), + None => HashMap::new(), + }; + set_legend_fills(n, &on_dark); + } + let holds = |c: &Node| { + let mut found = false; + walk_with_masks(c, &mut |m| found |= ids.contains(&m.id)); + found + }; + if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art)) + && let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + { + restore_contrast(Arc::make_mut(&mut m.art), ids); + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + restore_contrast(Arc::make_mut(c), ids); + } + } +} + /// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them. fn legend_labels(n: &Node) -> Vec<&Node> { legend_in(n.children().map_or(&[], |c| c.as_slice())) diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 368bc6de10..e1232c9a56 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -768,6 +768,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() { assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again"); } +/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges +/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that +/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were. +#[test] +fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() { + let mut s = session(); + let csv = ",North,South\nP,1,1"; + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + /// The fill of the legend label of graph `id` that says `name`. + fn label(s: &Session, id: NodeId, name: &str) -> Paint { + let mut out = None; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == name + { + out = Some(t.first_style().fill.clone()); + } + }); + out.unwrap() + } + // The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black. + let mut wedges = vec![]; + for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) { + c.walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + wedges.push(m.id.0); + } + }); + } + assert!(!wedges.is_empty()); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge"); + assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK)); + copy(&mut s, &[g]); + + for (cmd, choice, north) in [ + ("edit.pasteWithoutFormatting", "merge", Color::WHITE), + ("edit.paste", "merge", Color::WHITE), + ("edit.pasteWithoutFormatting", "add", Color::BLACK), + ("edit.paste", "add", Color::BLACK), + ] { + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0]; + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}"); + assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it"); + } + + // A copy of the pie in the opacity mask of a rectangle follows the same way. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0); + let art = { + let d = doc_mut(&mut s); + let pie = d.node(g).unwrap().clone(); + d.reid(&pie) + }; + doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0]; + let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone(); + let mut north = None; + mask.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == "North" + { + north = Some(t.first_style().fill.clone()); + } + }); + assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask"); +} + /// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph /// is pasted without formatting. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..f4a0ebc68d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7232,8 +7232,10 @@ graph's art is pasted as it was copied. A global or spot swatch whose name the document gives another colour is a conflict: `clipboard.conflicts` lists them, and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the -pasted swatch comes in renamed) or one answer per name. Pasting back into the document the objects came from uses -its resources as they are now and raises no conflict. +pasted swatch comes in renamed) or one answer per name. When a merged swatch turns a pie's wedge from light to dark +or back, the legend labels in that pie's wedges take the contrast a redraw gives them (white on a dark wedge, black on +a light one), unless the legend labels have a fill of their own. Pasting back into the document the objects came from +uses its resources as they are now and raises no conflict. Placement: `edit.paste {center}` centres the objects on a point (the app passes the view centre), else offsets them by `dx`/`dy` (the Paste Offset preference). With nothing selected, `edit.pasteInFront` / `edit.pasteInBack` put them From 3dad1013a4d09b47f5803e92b68623d41e36d4e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:59:07 -0800 Subject: [PATCH 34/63] Image Trace: Noise leaves cut-edge blends out of a speck's color When Noise picks the nearest color for a speck, the speck's average now leaves out the semi-transparent pixels along a cut-out image's edge that are the color beside them blended with the transparent background. settle_cut_edges returns which pixels those are. A speck made only of them merges by border. In Grayscale the speck's gray is read with luma, the gray Grayscale traces with, and the test probe shift_probe denoises as a trace does. The docs now say the rule applies in Color and Grayscale (in Black and White a region has only one neighboring color, so Black and White Logo changes only by its Noise value), name `ea3f81d9c3` as the base of the measurements, and say that the gradient-border test sets Noise 15 because at Noise 8 its borders stray 0.92 px against a 0.9 px limit. --- crates/trace/src/layers.rs | 9 ++-- crates/trace/src/pipeline.rs | 12 +++-- crates/trace/src/quantize/cut_edge.rs | 9 +++- crates/trace/src/quantize/denoise.rs | 72 ++++++++++++++++++++------- crates/trace/src/tests.rs | 27 +++++++++- docs/image-trace-quality.md | 37 ++++++++------ docs/mcp.md | 9 ++-- docs/target-app-parity.md | 2 +- 8 files changed, 130 insertions(+), 47 deletions(-) diff --git a/crates/trace/src/layers.rs b/crates/trace/src/layers.rs index 04f687b46b..7a8375f24e 100644 --- a/crates/trace/src/layers.rs +++ b/crates/trace/src/layers.rs @@ -5,13 +5,13 @@ use super::params::{Method, Mode, TraceParams}; use super::pipeline::TracedPath; #[cfg(test)] use super::pipeline::{bw_tones, left_out}; +#[cfg(test)] +use super::quantize; use super::raster::{Raster, TraceError}; use super::{ AtomicUsize, Crack, Loop, Ordering, PathData, Quantized, TRANSPARENT, TracedGradient, TracedShape, centerline, contour, fit, logo, shapes, trace_mask, }; -#[cfg(test)] -use super::{denoise, quantize}; /// What tracing one colour layer needs. pub(crate) struct Layers<'a> { @@ -1005,7 +1005,10 @@ impl Layers<'_> { pub(crate) fn shift_probe(img: &Raster, params: &TraceParams) -> Vec<[f64; 4]> { let (w, h) = (img.width as usize, img.height as usize); let mut q = quantize(img, params); - denoise(&mut q.labels, w, h, params.noise as usize); + let labs = super::quantize::palette_labs(&q.palette); + let source = + super::quantize::Source { labs: &labs, rgba: &img.rgba, blended: &[], gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) }; + super::quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &[], Some(&source)); let n = q.palette.len(); let rank: Vec = (0..n).collect(); let gradients = vec![None; n]; diff --git a/crates/trace/src/pipeline.rs b/crates/trace/src/pipeline.rs index 0e3abbadda..235447bee4 100644 --- a/crates/trace/src/pipeline.rs +++ b/crates/trace/src/pipeline.rs @@ -250,9 +250,11 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &( let (mut q, rare) = quantize::quantize_keeping(without.as_ref().unwrap_or(img), params); go_on()?; // The semi-transparent edge of a cut-out image traces as the color beside it. - if matches!(params.mode, Mode::Color | Mode::Grayscale) { - quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale); - } + let blended = if matches!(params.mode, Mode::Color | Mode::Grayscale) { + quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale) + } else { + Vec::new() + }; drop(without); // Each gradient is a palette entry of its own (its colour: the gradient's middle). let mut gradients: Vec> = vec![None; q.palette.len()]; @@ -272,8 +274,10 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &( let keep: Vec = q.palette.iter().map(|c| rare.contains(c)).collect(); // A speck far from the color around it joins the color beside it nearest its own pixels. let labs = quantize::palette_labs(&q.palette); - let source = quantize::Source { labs: &labs, rgba: &img.rgba, gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) }; + let source = + quantize::Source { labs: &labs, rgba: &img.rgba, blended: &blended, gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) }; quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &keep, Some(&source)); + drop(blended); go_on()?; // Ignore Color, background only: the labels traced, with the ignored color's areas that reach // the edge left out. Its other areas are traced with the rest. Edges are still placed by diff --git a/crates/trace/src/quantize/cut_edge.rs b/crates/trace/src/quantize/cut_edge.rs index 4578fbe7fc..61a9db4c8e 100644 --- a/crates/trace/src/quantize/cut_edge.rs +++ b/crates/trace/src/quantize/cut_edge.rs @@ -594,12 +594,15 @@ pub(super) fn compact(mut labels: Vec, palette: Vec<[u8; 3]>) -> Quantized /// when one of the fully opaque pixels it reaches has it, or when its color is a blend of none of /// them, as with a thin semi-transparent outline of another color. Pixels outside the image do not /// count as transparent. With `gray` (Grayscale), a pixel's color is its gray (see [`luma`]). -pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) { +/// Returns which cut-edge pixels are a blend of the color of a fully opaque pixel they reach (see +/// [`edge_blend_of`]), whether or not they took that color (empty when `q` does not match `img`). +pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> Vec { let (w, h) = (img.width as usize, img.height as usize); let px = img.rgba.as_chunks::<4>().0; if q.labels.len() != w * h || px.len() != w * h { - return; + return Vec::new(); } + let mut blended = vec![false; w * h]; let color = |p: &[u8; 4]| if gray { [luma(*p); 3] } else { [p[0], p[1], p[2]] }; let edge = cut_edge(img); let mut changed = false; @@ -627,6 +630,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) { } } }); + blended[i] = !near.is_empty(); if keep || near.is_empty() { continue; } @@ -641,6 +645,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) { if changed { *q = compact(std::mem::take(&mut q.labels), std::mem::take(&mut q.palette)); } + blended } /// Calls `visit` with the index of each fully opaque pixel of `img` within two pixels of the pixel diff --git a/crates/trace/src/quantize/denoise.rs b/crates/trace/src/quantize/denoise.rs index 5bc237926a..e320194b6d 100644 --- a/crates/trace/src/quantize/denoise.rs +++ b/crates/trace/src/quantize/denoise.rs @@ -4,6 +4,8 @@ use super::rare::RARE_ISLAND; /// Merge whole 4-connected regions, smallest first, into their most common neighbouring label. /// The merge order does not depend on `min_area`: a higher threshold continues the same sequence /// instead of splitting a region already merged at a lower threshold. Transparency is a barrier. +/// It reads only the labels. A trace also reads the image, and a speck far from the color around +/// it joins the color beside it nearest its pixels instead. pub fn denoise(labels: &mut [u16], w: usize, h: usize, min_area: usize) { denoise_keeping(labels, w, h, min_area, &[]); } @@ -27,9 +29,13 @@ pub(crate) const NEAREST_PIXELS: u32 = 2; pub(crate) struct Source<'a> { /// Each label's color in Oklab × 100 ([`super::palette_labs`]). pub labs: &'a [[f64; 3]], - /// The image the labels were made from, 4 bytes a pixel. + /// The prepared image the labels were made from, 4 bytes a pixel. pub rgba: &'a [u8], - /// Whether the labels are grays (Grayscale, Black and White): the source pixels are compared as their gray. + /// The pixels along a cut edge that [`super::settle_cut_edges`] finds to be the color of an opaque pixel beside + /// them blended with the transparent background. They are not read. + pub blended: &'a [bool], + /// Whether the labels are grays (Grayscale, Black and White): the pixels are compared as their gray + /// ([`super::luma`]). pub gray: bool, } @@ -144,8 +150,8 @@ pub(crate) fn denoise_nearest(labels: &mut [u16], w: usize, h: usize, min_area: && (area >= NEAREST_PIXELS || by_colour.iter().filter(|&&(_, border)| border == longest).count() == 1) && let Some(own) = source.labs.get(colour[id as usize] as usize) && distance(own, source.labs.get(chosen as usize)) >= NEAREST_APART + && let Some(mean) = mean_lab(head[id as usize], &next, source) { - let mean = mean_lab(head[id as usize], &next, source); let to = |c: u16| distance(&mean, source.labs.get(c as usize)); if let Some(&(nearest, _)) = by_colour .iter() @@ -198,24 +204,26 @@ fn find(parent: &mut [u32], mut a: u32) -> u32 { a } -/// The source pixels of the list that starts at `first` (linked through `next`), averaged, in Oklab × 100. -fn mean_lab(first: u32, next: &[u32], source: &Source) -> [f64; 3] { - let (mut sum, mut n) = ([0.0f64; 3], 0.0f64); +/// The source pixels of the list that starts at `first` (linked through `next`), averaged, in Oklab × 100, read as +/// `source` says, leaving out the blended cut-edge pixels. `None` when every pixel is one of them. +fn mean_lab(first: u32, next: &[u32], source: &Source) -> Option<[f64; 3]> { + let (mut sum, mut n) = ([0.0f64; 3], 0u32); let mut pixel = first; while pixel != NONE { - if let Some(p) = source.rgba.get(pixel as usize * 4..pixel as usize * 4 + 3) { - for (s, &v) in sum.iter_mut().zip(p) { - *s += f64::from(v); + let blended = source.blended.get(pixel as usize).copied().unwrap_or(false); + if !blended && let Some(&[r, g, b, a]) = source.rgba.get(pixel as usize * 4..pixel as usize * 4 + 4) { + let p = if source.gray { [f64::from(super::luma([r, g, b, a])); 3] } else { [r, g, b].map(f64::from) }; + for (s, v) in sum.iter_mut().zip(p) { + *s += v; } - n += 1.0; + n += 1; } pixel = next.get(pixel as usize).copied().unwrap_or(NONE); } - let mut mean = sum.map(|s| s / n.max(1.0)); - if source.gray { - mean = [0.299 * mean[0] + 0.587 * mean[1] + 0.114 * mean[2]; 3]; + if n == 0 { + return None; } - super::oklab(mean) + Some(super::oklab(sum.map(|s| s / f64::from(n)))) } /// The distance between two colors in Oklab × 100; infinite when `q` is missing. @@ -374,7 +382,7 @@ mod tests { let rgba: Vec = labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect(); let mut out = labels.to_vec(); - denoise_nearest(&mut out, w, h, min_area, &[], Some(&Source { labs: &labs, rgba: &rgba, gray: false })); + denoise_nearest(&mut out, w, h, min_area, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false })); out } @@ -506,14 +514,42 @@ mod tests { let mut blind = labels.clone(); denoise_keeping(&mut blind, w, h, 15, &[]); let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN[..2]); - let rgba = vec![0u8; w * h * 4]; + // Every pixel ink: read, the speck would join the line. + let rgba: Vec = (0..w * h).flat_map(|_| [30, 25, 20, 255]).collect(); let mut out = labels.clone(); - denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, gray: false })); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false })); assert_eq!(out, blind); let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); let mut out = labels.clone(); - denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba[4..], gray: false })); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba[4..], blended: &[], gray: false })); assert_eq!(out, blind); + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false })); + assert_eq!(out[10 * w + 10], 1, "a source that covers them is read"); + } + + /// A speck made only of cut-edge pixels that are the color beside them blended with the transparent background + /// merges by border alone. + #[test] + fn a_speck_of_blended_cut_edge_pixels_merges_by_border() { + let (labels, w, h) = speck_beside_a_line(3); + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); + let rgba: Vec = + labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect(); + let mut blended = vec![false; w * h]; + for (x, y) in SPECK { + blended[y * w + x] = true; + } + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &blended, gray: false })); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + assert_eq!(out, blind); + // One pixel that is not such a blend is enough to read it. + blended[10 * w + 10] = false; + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &blended, gray: false })); + assert_eq!(out[10 * w + 10], 1); } /// A minimum so large that regions keep merging into big ones. diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index cc7b1e323c..df794f215b 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -716,13 +716,35 @@ fn a_cut_out_edge_in_grayscale_ties_by_its_gray() { let t = TRANSPARENT; let q = Quantized { labels: vec![0, 2, 1, t, t, t], palette: vec![[50, 50, 50], [150, 150, 150], [90, 90, 90]] }; let mut gray = q.clone(); - crate::quantize::settle_cut_edges(&mut gray, &img, true); + let marked = crate::quantize::settle_cut_edges(&mut gray, &img, true); assert_eq!(gray.palette.get(gray.labels[1] as usize), Some(&[50, 50, 50])); + assert_eq!(marked, [false, true, false, false, false, false], "the edge pixel is marked as a blend"); let mut color = q; crate::quantize::settle_cut_edges(&mut color, &img, false); assert_eq!(color.palette.get(color.labels[1] as usize), Some(&[150, 150, 150])); } +#[test] +fn a_cut_out_edge_pixel_already_of_the_color_beside_it_is_marked_when_a_blend_of_it() { + // A semi-transparent dark red edge pixel between opaque red and blue pixels, already labeled red: it keeps red, + // and is marked as a blend for Noise. A purple one labeled red is a blend of neither pixel's color alone and is + // not marked. + for (edge, blend) in [([128, 0, 0, 192], true), ([128, 0, 128, 192], false)] { + let img = Raster::from_fn(3, 2, |x, y| match (x, y) { + (0, 0) => [255, 0, 0, 255], + (1, 0) => edge, + (2, 0) => [0, 0, 255, 255], + _ => [0, 0, 0, 0], + }); + let t = TRANSPARENT; + let q = Quantized { labels: vec![0, 0, 1, t, t, t], palette: vec![[255, 0, 0], [0, 0, 255]] }; + let mut settled = q.clone(); + let marked = crate::quantize::settle_cut_edges(&mut settled, &img, false); + assert_eq!(settled, q, "{edge:?}"); + assert_eq!(marked, [false, blend, false, false, false, false], "{edge:?}"); + } +} + #[test] fn a_semi_transparent_line_across_a_gap_keeps_its_own_color() { // A light block, a transparent column, then a semi-transparent tan line: the block lies within @@ -761,8 +783,9 @@ fn a_thin_semi_transparent_outline_keeps_its_own_color() { let q = quantize(&img, &TraceParams { mode, colors: 3, ..TraceParams::default() }); assert_ne!(q.labels[9 * 60 + 30], q.labels[30 * 60 + 30], "{mode:?}, alpha {alpha}: the outline has a color of its own"); let mut settled = q.clone(); - crate::quantize::settle_cut_edges(&mut settled, &img, mode == Mode::Grayscale); + let marked = crate::quantize::settle_cut_edges(&mut settled, &img, mode == Mode::Grayscale); assert_eq!(settled, q, "{mode:?}, alpha {alpha}"); + assert!(!marked.contains(&true), "{mode:?}, alpha {alpha}: the outline is no blend of the square"); } } } diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 228c1ef9f8..b111a25fb7 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -317,15 +317,20 @@ A region below Noise used to join the color it shares the longest border with. A line on a light ground, a dark speck of the line touches the ground on more sides than the line, so it joined the ground and the line broke into dashes. Now, when the color of the longest border is 10 or more apart from the region's own color (Oklab × 100), the region joins the neighboring color -nearest the average of its source pixels, among the colors that share at least a tenth of the -longest border. A single pixel whose longest border is tied between colors joins by border as -before, so an anti-aliased corner pixel stays with the shape's corner. The rule changes only which -color a region joins, and higher Noise still continues the same merge sequence. The values are +nearest the average of its pixels, among the colors that share at least a tenth of the longest +border. The average is taken in the image as prepared for tracing (deblocked, and smoothed for a +photo) and leaves out the semi-transparent pixels along a cut-out image's edge that are the color +beside them blended with the transparent background. A single pixel whose longest border is tied +between colors keeps the previous rule. The rule changes only which +color a region joins, and higher Noise still continues the same merge sequence. It applies in Color +and Grayscale: in Black and White a region has only one neighboring color. The values are VectorCraft's own. 6 Colors and 16 Colors move from Noise 15 to 8, and Black and White Logo from 25 to 5. +The new Noise values were chosen with the rule in place, and the measurements below include both +changes. Measured on 17 local images (synthetic shapes and photos at several sizes, a geometric drawing and -eight illustrations; not repository assets), against the same `main` without the change, with the -mean absolute difference per channel (0 to 255) against the image on white: +eight illustrations; not repository assets), against `main` at `ea3f81d9c3`, with the mean absolute +difference per channel (0 to 255) against the image on white: | preset | three illustrations with fine dark lines | four other illustrations | synthetic shapes and photos | |:--|:--|:--|:--| @@ -333,15 +338,19 @@ mean absolute difference per channel (0 to 255) against the image on white: | 6 Colors | 7.24 / 9.14 / 9.21 → 5.87 / 6.66 / 7.87; anchors +55% to +73% | −0.6% to −3.5%; anchors +13% to +20% | within 0.03; anchors 0% to +22% | | High Fidelity Photo | 8.42 / 10.11 / 7.46 → 6.85 / 7.54 / 6.00; anchors +31% to +51% | −1.4% to −5.8%; anchors −9% to +4% | within 0.08; anchors −6% to +5% | -Black and White Logo's pixels that differ from the image thresholded at 128 fall from 2.00 / 2.42 / -1.96% to 1.49 / 1.58 / 1.23% on the three illustrations and from 1.19 to 2.37% to 1.14 to 1.94% on the -other four, with 5% to 64% more anchors; the synthetic inputs change by 0.01% or less. A simple flat -illustration changes by 1.1% or less in every preset, and the geometric drawing keeps its anchor -count and difference in every preset. Tests: `a_dark_speck_beside_a_dark_line_joins_the_line`, -`a_speck_close_to_its_longest_border_color_joins_it`, `a_color_with_a_short_border_is_not_chosen`, -`a_lone_pixel_tied_between_colors_merges_by_border`, `noise_still_removes_every_region_below_it` and +With Black and White Logo, where only the Noise value changes, the pixels that differ from the image +thresholded at 128 fall from 2.00 / 2.42 / 1.96% to 1.49 / 1.58 / 1.23% on the three illustrations, +with 37% to 64% more anchors, and from 1.19 to 2.37% to 1.14 to 1.94% on the other four, with 5% to +41% more anchors; the synthetic inputs change by 0.01% or less. On a simple flat illustration the +difference changes by 1.0% or less in every preset, with up to 21% more anchors, and the geometric +drawing keeps its anchor count and difference in every preset. Tests: +`a_dark_speck_beside_a_dark_line_joins_the_line`, `a_speck_close_to_its_longest_border_color_joins_it`, +`a_color_with_a_short_border_is_not_chosen`, `a_lone_pixel_tied_between_colors_merges_by_border`, +`a_speck_of_settled_cut_edge_pixels_merges_by_border`, `noise_still_removes_every_region_below_it` and `a_source_that_does_not_cover_the_labels_is_not_read` in `crates/trace/src/quantize/denoise.rs`. -`the_borders_of_a_gradients_bands_follow_its_contours` runs at Noise 15, the value it was written for. +`the_borders_of_a_gradients_bands_follow_its_contours` now traces at Noise 15: at 16 Colors' new +Noise 8 the borders of its noisy gradient stray 0.92 px from the contours, above the test's 0.9 px +limit. ## Pieces returning to a junction An outline piece can return to its starting junction while being fitted as an open chain. At loose diff --git a/docs/mcp.md b/docs/mcp.md index d7e47925ed..0f5418734f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3849,9 +3849,12 @@ already walks Image Trace. Short agent entry points: when nothing was traced. `noise` (Color, Grayscale and Black and White, not Flat Logo) merges areas smaller than that many pixels into a neighboring color. Each one joins the color it shares the longest border with, unless that color is 10 or more apart from its own (Oklab - × 100). Then it joins the neighboring color nearest the average of its source pixels, among the colors that share at - least a tenth of the longest border. A single pixel whose longest border is tied between two or more colors always - joins by border. These distances and fractions are VectorCraft's own values. The built-in presets 6 Colors and 16 + × 100). Then it joins the neighboring color nearest the average of its pixels, among the colors that share at + least a tenth of the longest border. The average is taken in the image as prepared for tracing (deblocked, and + smoothed for a photo) and leaves out the semi-transparent pixels along a cut-out image's edge that are the color + beside them blended with the transparent background. A single pixel whose + longest border is tied between two or more colors always joins by border. In Black and White an area has only one + neighboring color. These distances and fractions are VectorCraft's own values. The built-in presets 6 Colors and 16 Colors use Noise 8, and Black and White Logo uses Noise 5. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with the preferences: `params` over `preset`'s (default: the saved preset `name`, else Default), checked as `imageTrace.make` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4f7a0fe2e5..56b10d9daa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1543,7 +1543,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. - **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. -- **Image Trace, Noise joins the nearest color:** in Color, Grayscale and Black and White, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest its source pixels, among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. +- **Image Trace, Noise joins the nearest color:** in Color and Grayscale, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest the average of its pixels (leaving out cut-edge pixels that are the color beside them blended with the transparent background), among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. From 73502e83ac5c0e213bb67de7d21d6a0217199b69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:06:13 -0800 Subject: [PATCH 35/63] SVG: hidden pieces of a cut image put no shared image in the defs The pieces a Warp effect cuts an image into share one in the defs. The writer counted every piece, hidden ones included, so pieces the file leaves out (hidden, or in a hidden clip group) still put an into the defs, with the linked file's path under Images: Link. A confined caller's read-root check looks only at the art the file draws and did not refuse it. Image sharing and the colorized-image counts now walk only the art the writer draws: hidden layers and objects only with hidden layers kept, and never a template layer's art. --- crates/svg/src/export/paint.rs | 20 ++++++++++++-- crates/svg/tests/it/warp_pieces.rs | 43 ++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 7e67f09cf7..f52a701867 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -37,9 +37,25 @@ pub(super) enum StrokePlan { Written(Written), } +/// Visit `n` and the descendants the writer draws ([`Writer::node_body`]): a hidden layer or object +/// and what it holds only with `hidden` (SVG Options › hidden layers kept), and a template layer's +/// art never. +fn walk_drawn<'a>(n: &'a Node, hidden: bool, f: &mut impl FnMut(&'a Node)) { + if !(n.visible || hidden) { + return; + } + f(n); + if matches!(n.kind, NodeKind::Layer { template: true, .. }) { + return; + } + for c in n.children().into_iter().flatten() { + walk_drawn(c, hidden, f); + } +} + impl Writer<'_> { pub(super) fn count_colorized_images(&mut self, art: &Node) { - art.walk(&mut |n| { + walk_drawn(art, self.opts.hidden_layers, &mut |n| { let NodeKind::Image(im) = &n.kind else { return }; let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; let shown = self.doc.shown_image(n, im); @@ -176,7 +192,7 @@ impl Writer<'_> { self.count_colorized_images(art); // Each image's count and its first piece, which shows what they all show. let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); - art.walk(&mut |c| { + walk_drawn(art, self.opts.hidden_layers, &mut |c| { if let NodeKind::Image(im) = &c.kind { let shown = self.doc.shown_image(c, im); let im = &*shown; diff --git a/crates/svg/tests/it/warp_pieces.rs b/crates/svg/tests/it/warp_pieces.rs index 9c8b3e1760..4d61baee14 100644 --- a/crates/svg/tests/it/warp_pieces.rs +++ b/crates/svg/tests/it/warp_pieces.rs @@ -118,6 +118,49 @@ fn opaque_pixels_stay_opaque_where_warp_pieces_overlap() { } } +/// Pieces the file leaves out share no image: with Images set to Link, the warp pieces of a linked +/// image that are hidden, or sit in hidden clip groups, put no `` naming its file in the +/// defs unless hidden layers are kept. Visible pieces share one. +#[test] +fn hidden_warp_pieces_share_no_image() { + let path = "/away/photo.png"; + let svg = |d: &Document, hidden_layers: bool| { + let opts = ExportOptions { images: vectorcraft_svg::ImageMode::Link, hidden_layers, ..ExportOptions::default() }; + export_full(d, &opts, None).svg + }; + // Every image in `n` linked to `path`. + fn link(n: &mut Node, path: &str) { + if let NodeKind::Image(im) = &mut n.kind { + im.link = Some(vectorcraft_doc::LinkInfo::new(path)); + } + for c in n.children_mut().into_iter().flatten() { + link(std::sync::Arc::make_mut(c), path); + } + } + for masked in [false, true] { + // Hide every image (`ancestor` false), or every clip group holding one (`ancestor` true). + for ancestor in [false, true] { + let mut d = warped_pixels(&|p| p, masked, [255, 0, 0, 255], |_| {}); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + let g = std::sync::Arc::make_mut(&mut layer.children_mut().unwrap()[0]); + link(g, path); + let visible = d.clone(); + assert_eq!(svg(&visible, false).matches(path).count(), 1, "masked {masked}: the pieces share one image"); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + let g = std::sync::Arc::make_mut(&mut layer.children_mut().unwrap()[0]); + for piece in g.children_mut().unwrap() { + let piece = std::sync::Arc::make_mut(piece); + match piece.children_mut() { + Some(kids) if !ancestor => std::sync::Arc::make_mut(&mut kids[1]).visible = false, + _ => piece.visible = false, + } + } + assert!(!svg(&d, false).contains(path), "masked {masked}, ancestor {ancestor}: {}", svg(&d, false)); + assert_eq!(svg(&d, true).matches(path).count(), 1, "masked {masked}, ancestor {ancestor}"); + } + } +} + /// Pieces of an opaque image are drawn one over another without knockout masks; a colorize paint /// draws a gray image's light pixels partly transparent, so its pieces take them. #[test] From 1e32738b8f1ceb5b3a1f9e6b5b91257c96d2bddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:12:48 -0800 Subject: [PATCH 36/63] MCP: confined SVG output checks the linked images the file draws The read-root check for SVG output now looks at the same art the writer draws: - A placed document's art is checked, with the pixels its file holds. A placed native file that links an image outside the read roots was written with that path under Images: Link. - Hidden objects inside symbols, patterns and graph designs are left out unless hidden layers are kept, as they are in the layers. - With profile tiny12 the file leaves out opacity masks, and their images are not checked. - An object whose effect SVG has no filter for is checked as the image the file draws of it, for file output and clipboard.exportSvg alike. The last three refused files and clipboard SVG that name no file outside the roots. --- crates/engine/src/cmd/fileio/access.rs | 28 +++-- crates/engine/src/cmd/links.rs | 55 +++++++--- crates/engine/src/tests/links.rs | 138 +++++++++++++++++++++++++ docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 5 files changed, 204 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index cb5b4e85cc..856656f564 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read /// 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 -/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with +/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects +/// SVG has no filters for as the images the file draws of them), of the art the file draws for each +/// placed document, and of the symbols, patterns and brushes that art uses; with /// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them /// and each data set's image. The error names no file or folder. pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> { @@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { return Ok(()); } - // Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden - // layers kept: the encoder refuses them anyway. - let (link, preserve, hidden) = match super::svg::options_map(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) { Ok(m) => { let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false)); - (m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers")) + let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12"); + (m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny) } - Err(_) => (true, true, true), + Err(_) => (true, true, true, false), }; // The opacity-mask and symbol editing layers are never written. let d = &*d.without_edit_modes(); - let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden); - if preserve && crate::cmd::links::names_hidden_file(d, base) - || names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f))) - { + let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny); + // The SVG draws the objects with effects it has no filters for as images of them, as the + // encoder and the clipboard prepare them. + let drawing_names = || { + let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny); + let d = flat.as_ref().unwrap_or(d); + names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f))) + }; + if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() { return Err(bad(cmd, IMAGE_OUTSIDE)); } Ok(()) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b3fc65e8fc..522bd47817 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1314,27 +1314,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool { /// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image /// without pixels. The images of the art the SVG writes (opacity masks included) and of the /// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes -/// no other resource. Hidden layers and objects are written only with -/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]). -/// Always `false` without read roots in force. -pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool { - if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) { +/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden +/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the +/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny +/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in +/// force. +pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool { + if crate::file_access::current().is_none() { return false; } - let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect(); - names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link) + if !d.has_placed() && !names_hidden_image(d, base, link) { + return false; + } + // The writer draws placed documents' art with the pixels their files hold. + let placed = d.with_placed_art(); + let d = &*placed; + let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect(); + let mut out = super::clipboard::Clipboard::gather(d, art).to_document(); + let written = |n: &std::sync::Arc| { + let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); + std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty)) + }; + for s in &mut out.symbols { + s.art = written(&s.art); + } + for g in &mut out.graph_designs { + g.art = written(&g.art); + } + for p in &mut out.patterns { + p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect(); + } + names_hidden_image(&out, base, link) } -/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object -/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art. -/// Only layers and groups lose members; other objects keep theirs as they are. -fn svg_written(n: &Node, hidden: bool) -> Option { +/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a +/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled +/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document +/// is the art the writer draws for it. Only layers and groups lose members; other objects keep +/// theirs as they are. +fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option { if !(n.visible || hidden) { return None; } + if matches!(n.kind, NodeKind::PlacedDocument(_)) { + return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny); + } let mut n = n.clone(); - let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| { - let art = svg_written(&m.art, hidden)?; + let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| { + let art = svg_written(d, &m.art, hidden, tiny)?; Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() })) }); if n.extras().mask.is_some() { @@ -1343,7 +1370,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option { match &mut n.kind { NodeKind::Layer { template: true, children, .. } => children.clear(), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { - *children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect(); + *children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect(); } _ => {} } diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 57bb9e278e..931c011d40 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2138,3 +2138,141 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap(); } } + +/// 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. +#[test] +fn confined_svg_output_checks_the_images_of_placed_documents() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-placed-away"); + let home = Folder::new("svg-placed-home"); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for (photo, outside) in [(away.file("photo.png"), true), (home.file("photo.png"), false)] { + write(&photo, &png(60, 30, RED)); + let src = home.file("src.vectorcraft"); + let mut inner = session(); + place(&mut inner, &photo); + save(&mut inner, &src); + let mut s = session(); + place(&mut s, &src); + let link = json!({"format": "svg", "images": "link"}); + assert!(svg_text(&s.execute("document.serialize", &link).unwrap()).contains(&photo), "the file names the placed art's image"); + for format in ["svg", "svgz"] { + for images in ["link", "embed"] { + let p = json!({"format": format, "images": images}); + // Embed writes the pixels the placed file holds. + let names = svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo); + assert_eq!(names, images == "link", "{p}"); + match confine(roots.as_ref(), || s.execute("document.serialize", &p)) { + Ok(r) => assert!(!outside || !svg_text(&r).contains(&photo), "{p}: {}", svg_text(&r)), + Err(e) => { + assert!(outside && names, "{p}: {e}"); + assert!(e.to_string().contains("a linked image file is outside the read roots"), "{p}: {e}"); + } + } + } + } + if outside { + let e = confine(roots.as_ref(), || s.execute("document.serialize", &link)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots") && !e.contains("photo.png"), "{e}"); + } + } +} + +/// A confined caller's SVG of a symbol holding a visible rectangle and a hidden linked image outside +/// the read roots: the file leaves the hidden image out of the symbol and is written, unless hidden +/// layers are kept, which writes the image and refuses the file. +#[test] +fn confined_svg_output_leaves_hidden_symbol_art_unchecked() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-symbol-hidden-away"); + let home = Folder::new("svg-symbol-hidden-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()["id"].clone(); + let a = place(&mut s, &photo); + s.execute("object.hide", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mixed"})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["svg", "svgz"] { + let p = json!({"format": format, "images": "link"}); + assert!(!svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo), "{p}"); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap()); + assert!(!text.contains(&photo), "{p}: {text}"); + let kept = json!({"format": format, "images": "link", "hiddenLayers": true}); + assert!(svg_text(&s.execute("document.serialize", &kept).unwrap()).contains(&photo), "{kept}"); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &kept)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{kept}: {e}"); + } +} + +/// A confined caller's SVG Tiny 1.2 of an object whose opacity mask is a linked image outside the +/// read roots: the Tiny file leaves the mask out and is written; SVG 1.1 writes the mask and is +/// refused. +#[test] +fn confined_svg_tiny_output_leaves_opacity_mask_images_unchecked() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-tiny-mask-away"); + let home = Folder::new("svg-tiny-mask-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()["id"].clone(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["svg", "svgz"] { + let tiny = json!({"format": format, "images": "link", "profile": "tiny12"}); + assert!(!svg_text(&s.execute("document.serialize", &tiny).unwrap()).contains(&photo), "{tiny}"); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &tiny)).unwrap()); + assert!(!text.contains(&photo), "{tiny}: {text}"); + let full = json!({"format": format, "images": "link"}); + assert!(svg_text(&s.execute("document.serialize", &full).unwrap()).contains(&photo), "{full}"); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &full)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{full}: {e}"); + } +} + +/// A confined caller's SVG of a linked image outside the read roots, without pixels in the +/// document, under Radial Blur: the file and the clipboard draw the rendered image in its place, +/// name no file, and are written. +#[test] +fn confined_svg_output_checks_the_images_drawn_for_pixel_effects() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-flat-away"); + let home = Folder::new("svg-flat-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("effect.apply", &json!({"effect": "blur.radial", "ids": [a.0], "params": {"amount": 30, "quality": "draft"}})).unwrap(); + without_pixels(&mut s, a); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let clip = + |s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string(); + assert!(!clip(&mut s).contains(&photo)); + assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_some_and(|svg| !svg.contains(&photo))); + for format in ["svg", "svgz"] { + for images in ["link", "embed"] { + let p = json!({"format": format, "images": images}); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap()); + assert!(!text.contains(&photo), "{p}: {text}"); + } + } + // Without the effect, the image names its file. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("effect.remove", &json!({"index": 0})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); +} diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..b859cb914f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -255,9 +255,12 @@ the suite) keep the agent to the folders you give it: paths kept of them and each data set's image, in every symbol, pattern, graph design and brush, used or not, colorized or not, and a stored brush entry that does not read as a brush is refused too, since its links cannot be checked. Otherwise the images of the art the file writes, - in opacity masks and in the symbols, patterns and brushes that art uses, are checked: hidden layers and - objects only with `hiddenLayers` (a save keeps them unless it is `false`), and template layers and the - layer of opacity-mask or symbol editing mode never. `selectedOnly` and `document.exportSelection` check the + in opacity masks, in the art drawn for placed documents and in the symbols, patterns and brushes that art + uses, are checked: hidden layers and objects only with `hiddenLayers` (a save keeps them unless it is + `false`), also inside symbols, patterns and graph designs, and template layers and the layer of + opacity-mask or symbol editing mode never. With `profile: "tiny12"` the file leaves out opacity masks, and + their images are not checked. An object whose effect SVG has no filter for is checked as the image the file + draws of it. `selectedOnly` and `document.exportSelection` check the 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. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 72de21a43c..89ebb463dc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -872,7 +872,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Link replies under `--automation-read-root`: `links.list`, `links.check`, `links.info` and `document.open`'s link rows leave out the path, found path and folder of a linked file outside the read roots, and the stored size and date of it in `links.info`; each row keeps its id, file name and status, and the document's links are not changed. `crates/engine/src/tests/linkspanel.rs` (`link_paths_outside_the_read_roots_are_left_out`), `crates/engine/src/tests/placed_document.rs` (`link_info_leaves_out_a_placed_documents_path_outside_the_read_roots`). - Document replies under `--automation-read-root`: `document.inspect` gives `path` as null for a document file outside the read roots, and `document.json` names a linked image or placed file outside them by its file name alone, without its relative path, size or date, brush art included, leaves out a relative path that leads outside them and a stored brush entry that does not read as a brush, names a data set's image value outside them by its file name, and leaves an Export for Screens folder outside them out of `export_settings`; the document is not changed. `crates/engine/src/tests/placed_document.rs` (`document_replies_leave_out_paths_outside_the_read_roots`, `document_json_checks_brush_art_and_relative_paths_against_the_read_roots`). - SVG output under `--automation-read-root`: `document.serialize`, `document.export`, `document.exportSelection`, `document.exportForScreens`, `assets.export`, the SVG and SVGZ saves, `file.exportAs` and the SVG Options dialog's Show Code refuse an SVG or SVGZ of a document that links a JavaScript file outside the read roots, before any file or folder is written, with an error that names no file or folder; a URL, a file inside the roots and a relative path that leads inside them are written as stored, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/interactivity.rs` (`confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `svg_output_keeps_linked_javascript_files_a_caller_may_read`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots`). - - 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. `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`), `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`). + - 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`). - 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 51803c222deec2da2c6fbf57cd996ef8f3e13269 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:19:33 -0800 Subject: [PATCH 37/63] Docs: moving a label can scale the plot of a graph saved without placedArt docs/mcp.md said that moving a label on its own never moves or scales a graph's plot. A graph saved without `placedArt`, or with one that has no width or height, is measured on `placed`, the bounds of all of its art including the labels. Moving an outermost label of such a graph on its own changes those bounds, and the next redraw moves and scales the plot. The paragraph now says so. --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..f4137b63f0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -921,7 +921,8 @@ its own, can move or scale the plot at the next redraw. When all of a graph's ar the art measured has no width or no height, a redraw leaves the plot where it is and does not follow a move or scale of the graph. A graph opened from a `.ai` file saves `placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is -measured on `placed`. +measured on `placed`. `placed` includes the labels, so in such a graph moving an outermost label on its own can move or +scale the plot at the next redraw. The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, and the paint, stroke, gradient and transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its From bb3653e98fe4f489723254a2baf80a2f74322819 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:18:05 -0800 Subject: [PATCH 38/63] =?UTF-8?q?Docs:=20the=20command=20palette=20is=20na?= =?UTF-8?q?med=20by=20its=20menu=20item,=20not=20by=20=E2=8C=98K?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The egui crate's header comment and the M14.8 line in docs/target-app-parity.md called it "the ⌘K palette" and "a ⌘K command palette". Cmd+K runs edit.preferences, and help.commandPalette (Help › Search Commands…) defaults to Cmd+Shift+/. Both now name the menu item, and the crate comment links the palette module. --- crates/ui-egui/src/lib.rs | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3f89789d5d..79b1f41100 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2,7 +2,7 @@ //! //! 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, -//! shortcuts, the ⌘K palette and the control channel ([`control`]). +//! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..196ed385d7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -985,7 +985,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - - Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). + - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their progress rings and counts of tutorials finished; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list`, `learn.tab {tab}`, `learn.skill {skill}`, `learn.show {tutorial}` and `learn.back` script it, and the tab buttons, the rows and Back run them ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). - A tool's name in a Learn tutorial step is a blue link that shows where the tool is without choosing it (`learn.locateTool {tool}`): its toolbar button is marked, a collapsed group's flyout opens with the tool's row marked, a torn-off strip comes to the front, and a tool no shown toolbar holds is marked in the All Tools drawer. The mark, its 3 seconds and the hidden-toolbar cases are VectorCraft's own rules ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`, the `a_learn_link_*` tests in `toolbar::tests`). - Under a tutorial's steps, View more opens the tutorial's own practice sample as a new untitled document, and once the tutorial is finished, Next Up moves to the next tutorial in the same skill, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). The samples are VectorCraft's own drawings. A Finish tutorial button that shows once the sample is open, the untitled copy, Back to skills in place of Next Up after a skill's last tutorial, and Next Up showing the next tutorial without opening its sample are VectorCraft's own rules. `learn.openSample`, `learn.finish`, `learn.next` and `learn.skills` (Back to skills) script them. Not done: the help page's short video. Regression tests: `view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document`, `finishing_a_tutorial_offers_next_up_in_its_skill`, `the_practice_controls_work_from_the_keyboard`, `the_last_tutorial_of_a_skill_offers_back_to_skills`, `learn_finish_and_learn_next_follow_the_practice`, `learn_skills_shows_the_list_of_skills`, `the_practice_commands_reject_a_missing_or_unknown_tutorial`, `every_tutorial_has_its_own_readable_sample` and `the_next_tutorial_is_the_next_one_in_the_same_skill` in `crates/ui-egui/src/panels/learn/tests.rs`. From a9119df4bcb70d3b3302570e2d28e81645602979 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:24:23 -0800 Subject: [PATCH 39/63] i18n: drop the ka and ru toolbar error rows that main already has --- crates/ui-egui/src/i18n/ka.tsv | 13 ------------- crates/ui-egui/src/i18n/ru.tsv | 13 ------------- 2 files changed, 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e3748b43ff..9475bb917c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9763,19 +9763,6 @@ font-script Japanese იაპონური Not Aligned to Pixel Grid პიქსელურ ბადეზე გაუსწორებელი @msg only paths and compound paths can be aligned to the pixel grid პიქსელურ ბადეზე მხოლოდ ტრაექტორიების და შედგენილი ტრაექტორიების გასწორებაა შესაძლებელი @msg side is left or right, not `{s}` side არის left ან right და არა `{s}` -@msg side is left or right, not `{v}` side არის left ან right და არა `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order არის მთელი რიცხვი 0-დან {others}-მდე და არა `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს -@msg no toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` არ არის -@msg toolbar name can't be empty ხელსაწყოთა ზოლის სახელი ცარიელი ვერ იქნება -@msg a toolbar name has at most {MAX_NAME} characters ხელსაწყოთა ზოლის სახელში მაქსიმუმ {MAX_NAME} სიმბოლოა -@msg there is already a toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` უკვე არსებობს -@msg there is already a toolbar named `{to}` ხელსაწყოთა ზოლი სახელით `{to}` უკვე არსებობს -@msg a workspace keeps at most {MAX} toolbars სამუშაო სივრცე ინახავს მაქსიმუმ {MAX} ხელსაწყოთა ზოლს -@msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს -@msg name (a toolbar's name) is required name (ხელსაწყოთა ზოლის სახელი) აუცილებელია -@msg to (the new name) is required to (ახალი სახელი) აუცილებელია -@msg name must be a toolbar's name name ხელსაწყოთა ზოლის სახელი უნდა იყოს Ignore All ყველას იგნორირება Add to Dictionary ლექსიკონში დამატება No Suggestions შემოთავაზებები არ არის diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 4d8b654b23..02cdb08e31 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7666,19 +7666,6 @@ shape Open Открытый Not Aligned to Pixel Grid Не выровненные по пиксельной сетке @msg only paths and compound paths can be aligned to the pixel grid по пиксельной сетке можно выровнять только контуры и составные контуры @msg side is left or right, not `{s}` side — это left или right, а не `{s}` -@msg side is left or right, not `{v}` side принимает значение left или right, а не `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order должен быть целым числом от 0 до {others}, а не `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (имя панели инструментов) должен быть строкой -@msg no toolbar named `{name}` нет панели инструментов с именем `{name}` -@msg toolbar name can't be empty имя панели инструментов не может быть пустым -@msg a toolbar name has at most {MAX_NAME} characters имя панели инструментов содержит не более {MAX_NAME} символов -@msg there is already a toolbar named `{name}` панель инструментов с именем `{name}` уже есть -@msg there is already a toolbar named `{to}` панель инструментов с именем `{to}` уже есть -@msg a workspace keeps at most {MAX} toolbars рабочая среда хранит не более {MAX} панелей инструментов -@msg name (a toolbar's name) must be a string name (имя панели инструментов) должен быть строкой -@msg name (a toolbar's name) is required Необходимо указать name (имя панели инструментов) -@msg to (the new name) is required Необходимо указать to (новое имя) -@msg name must be a toolbar's name name должен быть именем панели инструментов Ignore All Пропустить все Add to Dictionary Добавить в словарь No Suggestions Нет вариантов From 3e2a2ad9ac74f51cfeeba19e48609548af137e12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:41:04 -0800 Subject: [PATCH 40/63] Paint: invert and complement of a group of design art remember its new fill paint.invert and paint.complement given a group whose own fill or stroke changed, with only graph design art inside it, left the last color and the recent colors as they were, because the remembered paint was taken only from the objects inside the group. It now comes from the first group whose own fill or stroke changed. A recolor that changes no group's paint, such as the complement of a gray fill, remembers nothing. --- crates/engine/src/cmd/graph/tests.rs | 52 ++++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 17 ++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 65715e44d1..2ead810dff 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -642,6 +642,58 @@ fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() { assert_eq!(look(&s, art), art_was); } +/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and +/// remember that color, as the last color and the newest recent color. With several such groups the color remembered +/// is that of the first group whose fill changed. +#[test] +fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() { + // A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it). + let paint_own = |s: &mut Session, group: NodeId, hex: &str| { + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone(); + d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint; + }; + // Series 0's group with its own fill painted `hex`. + let painted_series = |hex: &str| { + let (mut s, graph, _, art, _) = design_art(); + let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id; + paint_own(&mut s, group, hex); + (s, group, art) + }; + for cmd in ["paint.invert", "paint.complement"] { + let (mut s, group, art) = painted_series("#ff0000"); + let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone(); + let (art_was, fill_was) = (look(&s, art), fill(&s)); + s.execute(cmd, &json!({"ids": [group.0]})).unwrap(); + assert_eq!(look(&s, art), art_was, "{cmd}"); + assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored"); + let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}"); + } + // A gray fill is its own complement: nothing changes, and the remembered colors stay as they were. + let (mut s, group, _) = painted_series("#808080"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors)); + let was = remembered(&s); + assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0)); + assert_eq!(remembered(&s), was); + // Both series groups hold only the design's art: a gray one first and a red one, given together. + let (mut s, graph, _, _, _) = design_art(); + s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap(); + let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id); + paint_own(&mut s, groups[0], "#808080"); + paint_own(&mut s, groups[1], "#ff0000"); + s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap(); + let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else { + panic!("the red group's fill is not a solid color") + }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color))); +} + /// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects /// sets only theirs. #[test] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index ef15f896cd..c37d6519bd 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1149,9 +1149,24 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( return Ok(json!({ "changed": 0 })); } let art = super::appearance::design_art_in(d, &roots).into_iter().collect(); + // The fill or stroke the proxy shows of each group among the roots, before the edit. + let own = |d: &Document, id: NodeId| { + d.node(id) + .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) + .and_then(|n| n.proxy_paint_only(stroke, None)) + .cloned() + }; + let own_before: Vec> = roots.iter().map(|id| own(d, *id)).collect(); let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::>()}); let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?; - let shown_at = super::appearance::drop_design_art(&s.doc()?.doc, leaf_targets(s, &ids)?).first().map(|id| (*id, None)); + let d = &s.doc()?.doc; + let leaves = super::appearance::drop_design_art(d, leaf_targets(s, &ids)?); + // With only design art inside, which keeps its paint, the first group whose own fill or stroke changed shows it. + let shown_at = leaves + .first() + .copied() + .or_else(|| roots.iter().zip(&own_before).find(|(id, was)| was.is_some() && own(d, **id) != **was).map(|(id, _)| *id)) + .map(|id| (id, None)); (r, shown_at) } }; From f73280731a9f76ebf161ab586a274d069345a45a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:07:33 -0800 Subject: [PATCH 41/63] Paint: invert and complement of a group remember the fill its proxy shows paint.invert and paint.complement given a group with a fill or stroke of its own remembered the new paint of the first object inside it, while the Fill and Stroke proxies show the group's own paint. The remembered paint now follows the proxy: for each object given, in order, a group whose own fill or stroke changed gives that paint, otherwise the first object inside it that is not graph design art does. --- crates/engine/src/cmd/graph/tests.rs | 5 +++++ crates/engine/src/cmd/paint.rs | 24 ++++++++++++++++-------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 2ead810dff..ae48718a63 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -635,6 +635,11 @@ fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() { assert_ne!(own(&s), own_was, "the group's own fill"); assert_ne!(look(&s, mark), mark_was); assert_eq!(look(&s, art), art_was); + // The color remembered is the group's own new fill, which the Fill proxy shows. + let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else { + panic!("the group's fill is not a solid color") + }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color))); let (own_was, mark_was) = (own(&s), look(&s, mark)); s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap(); assert_eq!(own(&s), own_was, "target: contents"); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c37d6519bd..5ae2ebd4c9 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1156,17 +1156,25 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( .and_then(|n| n.proxy_paint_only(stroke, None)) .cloned() }; - let own_before: Vec> = roots.iter().map(|id| own(d, *id)).collect(); + let own_before: std::collections::HashMap = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect(); let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::>()}); let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?; + // As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it + // that is not design art (which keeps its paint). The first object given that has either shows it. let d = &s.doc()?.doc; - let leaves = super::appearance::drop_design_art(d, leaf_targets(s, &ids)?); - // With only design art inside, which keeps its paint, the first group whose own fill or stroke changed shows it. - let shown_at = leaves - .first() - .copied() - .or_else(|| roots.iter().zip(&own_before).find(|(id, was)| was.is_some() && own(d, **id) != **was).map(|(id, _)| *id)) - .map(|id| (id, None)); + let mut shown_at = None; + for id in &ids { + if let Some(was) = own_before.get(id) + && own(d, *id).as_ref() != Some(was) + { + shown_at = Some((*id, None)); + break; + } + if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() { + shown_at = Some((*leaf, None)); + break; + } + } (r, shown_at) } }; From 402b62b20d5adccfeaf2b48a952c0fe32ade5aff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:18:36 -0800 Subject: [PATCH 42/63] 3D: a transparent gradient lines up its colors and transparency across the faces Follows #7338. Under colored lights, and under the classic effects' shading, a gradient with transparent stops is drawn opaque on each face under one opacity mask of its transparency. A gradient without a placement of its own fitted its colors to each face's bounds, while the mask fitted the whole solid, so the color and transparency ramps did not line up and the colors started over on each face. Such a gradient is now placed once on all of the solid's faces, grown by 1 pt, before it is split into colors and mask. Opaque gradients and placed gradients are drawn as before. --- crates/effects/src/lighting.rs | 16 +++++++++ crates/effects/src/solids.rs | 11 ++++-- crates/effects/src/solids/classic.rs | 5 +-- crates/effects/src/solids/tests.rs | 51 ++++++++++++++++++++++++++++ docs/three-d.md | 4 ++- 5 files changed, 82 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 257576822a..7e73594d89 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -321,6 +321,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option) { (base, transparent.then_some(mask)) } +/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient +/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the +/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement. +/// An opaque gradient is returned as [`opaque_paint`] returns it. +pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option) { + let (base, mask) = opaque_paint(paint); + if mask.is_none() || !matches!(paint, Paint::Gradient(_)) { + return (base, mask); + } + let mut pinned = paint.clone(); + if let Paint::Gradient(g) = &mut pinned { + g.pin(bounds().inflate(1.0, 1.0)); + } + opaque_paint(&pinned) +} + fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node { use std::sync::Arc; use vectorcraft_doc::color::BlendMode; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5a2a179437..e10771a8d0 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -625,7 +625,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { /// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid /// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless /// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order -/// with the faces of other solids. +/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn +/// opaque under one mask of its transparency, placed once on all the facets when it has no +/// placement of its own ([`crate::lighting::opaque_surface_paint`]). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node { if !faces && composites_facets(&facets, paint, colored) { let mut group = crate::lighting::solid_surface(n.id, &facets, paint); @@ -634,7 +636,7 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble return group; } // Preserve existing white-light paints and alpha composition exactly. - let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) }; + let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) }; let paint = &opaque; let children = facets .into_iter() @@ -671,6 +673,11 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). +pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { + facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) +} + /// The width of the stroke of a facet's own paint that closes the seams between `face` and its /// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than /// the stroke, and its stroke would then paint over its neighbors. diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..0d867462fc 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -231,14 +231,15 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by /// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] /// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage. +/// its own transparency, so the shading follows the gradient's coverage; without a placement of its +/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]). pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; let paint = &paint; let children = facets .into_iter() diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 9b57c989c6..319cdf2949 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1960,6 +1960,57 @@ fn classic_shading_keeps_a_gradients_transparency() { } } +/// A gradient without a placement and with a transparent stop, under colored lights or classic +/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask +/// share one placement, so the color and transparency ramps line up across the faces. A gradient +/// placed in the document keeps its placement. +#[test] +fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() { + use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + // The source's stops carry an unusual midpoint, so its color and mask copies can be told from + // the light ramps. + const MARK: f32 = 0.37; + let mut first = GradientStop::new(0.0, RED); + first.midpoint = MARK; + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = 0.25; + let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end])); + let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None }; + // The placement of each copy of the source gradient: its own, else its fit on the path it fills. + fn placements(n: &Node, out: &mut Vec) { + n.walk(&mut |c| { + if let Some(mask) = &c.extras().mask { + placements(&mask.art, out); + } + let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO); + for item in &c.appearance.items { + if let Paint::Gradient(g) = paint_ref(item) + && g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK) + { + out.push(g.resolve(bounds)); + } + } + }); + } + let lit = json!({"lights": [{"color": "#ff8080"}]}); + for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] { + for geom in [None, Some(placed)] { + let mut n = square_node(); + n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))]; + n.appearance.effects.push(fx(id, params.clone())); + let art = solid_art(&n).unwrap_or_else(|| panic!("{id}")); + let mut masks = 0; + art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some())); + assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask"); + let mut found = vec![]; + placements(&art, &mut found); + assert!(found.len() > 2, "{id}: the faces' colors and the mask"); + let expected = geom.unwrap_or(found[0]); + assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}"); + } + } +} + /// A group member in a gradient with transparent stops keeps the shared back-to-front order of /// every member's faces: its faces go in runs that carry its opacity mask, and the other member's /// faces are drawn between them where they are in front of some and behind others. Here a square diff --git a/docs/three-d.md b/docs/three-d.md index e30d0ee4b8..437c40d5f3 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -180,7 +180,9 @@ The rest is our reading: curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in this order, in runs that each carry the mask, and a graphic drawn after one of its faces carries the mask too - ([Graphics](#graphics)). A member of a 3D group with its own opacity + ([Graphics](#graphics)). Such a gradient, and a gradient with transparent stops under the classic effects' + shading, is placed once on the whole solid when it has no placement of its own, so its colors and its + transparency line up across the faces. A member of a 3D group with its own opacity mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its From 58fc13a1e04337622291cda6aaae9bfada6de6ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:23:55 -0800 Subject: [PATCH 43/63] Eraser: the drag's area outline takes the tip the pen gives at each step The outline of the area an Eraser drag covers used the set Angle and Roundness and varied the Size only with Pressure, while the release (since #7726) erases with the tip the pen gives at each point on the Pressure, Tilt, Bearing and Rotation modes. Each step now takes the tip halfway between those at its ends, read as the release reads the stroke. A step whose angle or roundness varies is outlined where its own tip is round, and the parts inside other steps' areas are removed as before. A pen turned in place gives the last step the new tip, and a changed mode or Variation starts the outline again. A round tip whose Size follows the pen shows each step that wide. Random shows the value itself until the release draws it. --- crates/tools/src/draw2/gesture.rs | 88 +++++++++---- crates/tools/src/draw2/gesture/area.rs | 156 +++++++++++++++++++----- crates/tools/src/draw2/gesture/tests.rs | 143 ++++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 4 +- 5 files changed, 338 insertions(+), 57 deletions(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 75b71ec8df..9b4068c1eb 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -190,6 +190,8 @@ pub struct GestureTool { /// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from /// upright ([`super::pen_bearing`]), for the Eraser's tip outline. bearing: Option, + /// `bearing` as it was at each of `poses`, for the outline of the area the Eraser's drag covers. + bearings: Vec>, /// The length of the stroke, in points. length: f64, /// The outline of the area a Blob Brush or Eraser drag covers, as far as it is built @@ -871,6 +873,7 @@ impl GestureTool { tip_at: None, light: false, bearing: None, + bearings: vec![], length: 0.0, area: Cell::new(None), area_pending: Cell::new(false), @@ -938,6 +941,7 @@ impl GestureTool { let pose = ev.pen.map(PenPose::sanitized); self.bearing = pose.and_then(super::pen_bearing).or(self.bearing); self.poses.push(pose); + self.bearings.push(self.bearing); } } @@ -959,6 +963,9 @@ impl GestureTool { None if had_bearing => self.poses.iter().rev().find_map(|q| q.and_then(super::pen_bearing)), None => self.bearing, }; + if let Some(b) = self.bearings.last_mut() { + *b = self.bearing; + } } /// Would a press with `m` held draw a straight Pencil line? Shift or Alt held, unless Alt lends @@ -1046,6 +1053,7 @@ impl GestureTool { self.shift_line = None; self.light = false; self.bearing = None; + self.bearings.clear(); self.length = 0.0; self.area.set(None); self.area_pending.set(false); @@ -1106,12 +1114,32 @@ impl GestureTool { matches!(self.id, "blobBrush" | "eraser") } - /// The pen pressure of each point of a Blob Brush or Eraser stroke whose Size varies with - /// Pressure, when a pen pressed less than fully anywhere along it (a stroke without pressure - /// keeps its Size). - fn size_pressures(&self) -> Option<&[f32]> { - let pressed = self.pressures.len() == self.points.len() && self.light; - (self.tip_modes()[2] == Variation::Pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice()) + /// Which of the tip's angle, roundness and size vary along a Blob Brush or Eraser stroke: those + /// on a mode the pen gave a reading for anywhere along it (a pressure less than full, a tilt, a + /// bearing or a rotation). Random draws one value from the whole drag at the release, and the + /// outline shows the value itself. + fn tip_varies(&self) -> [bool; 3] { + let n = self.points.len(); + let (pressed, posed) = (self.light && self.pressures.len() == n, self.poses.len() == n); + let reads = |mode: Variation| match mode { + Variation::Pressure => pressed, + Variation::Tilt => posed && self.poses.iter().flatten().any(|q| q.tilt.is_some()), + Variation::Bearing => posed && self.bearings.iter().any(Option::is_some), + Variation::Rotation => posed && self.poses.iter().flatten().any(|q| q.rotation.is_some()), + Variation::Fixed | Variation::Random => false, + }; + if self.smoothing { + return [false; 3]; + } + self.tip_modes().map(reads) + } + + /// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there: the pressure + /// once the pen has pressed less than fully, the tilt and rotation of the point, and the + /// bearing of the last point up to it that the pen leaned 1° or more at ([`Self::tip_for`]). + fn tip_of_point(&self, i: usize) -> [f64; 3] { + let pressure = if self.light { self.pressures.get(i).map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; + self.tip_for(pressure, self.poses.get(i).copied().flatten(), self.bearings.get(i).copied().flatten()) } /// How the tip's angle, roundness and size vary: the Eraser's three modes, the Blob Brush's @@ -1137,12 +1165,20 @@ impl GestureTool { /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. fn tip_now(&self) -> [f64; 3] { - let base = [self.angle, self.roundness, self.size]; if self.id != "eraser" || !self.active { - return base; + return [self.angle, self.roundness, self.size]; } let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - let controls = super::pen_controls(pressure, self.poses.last().copied().flatten(), self.bearing); + self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing) + } + + /// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward + /// `bearing`: each value on a mode that follows the pen goes from the value less its Variation + /// to the value plus it ([`super::pen_controls`]); for Random, Fixed and what the pen does not + /// give, the values themselves. + fn tip_for(&self, pressure: f64, pose: Option, bearing: Option) -> [f64; 3] { + let base = [self.angle, self.roundness, self.size]; + let controls = super::pen_controls(pressure, pose, bearing); let variations = [self.angle_variation, self.roundness_variation, self.size_variation]; let mut out = base; for (i, (v, mode)) in out.iter_mut().zip(self.tip_modes()).enumerate() { @@ -1653,31 +1689,39 @@ impl Tool for GestureTool { }; let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK }; // A tip that is not round shows the outline of the area it covers, each step of the drag - // as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush - // tip: a line as wide as the brush would end square, where the stroke it adds is round at - // both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]). - if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing { - let pressures = self.size_pressures(); + // with the tip the pen gives there on the modes that follow the pen. So does a round Blob + // Brush tip: a line as wide as the brush would end square, where the stroke it adds is + // round at both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]). + let [angle_varies, roundness_varies, size_varies] = self.tip_varies(); + // An angle varies the tip only when it is not round. + let shaped = roundness_varies || (angle_varies && self.roundness < 100.0); + if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || shaped || self.id == "blobBrush") && !self.smoothing { let key = AreaKey { blob: self.id == "blobBrush", size: self.size, - variation: self.size_variation, + variation: if size_varies { self.size_variation } else { 0.0 }, angle: self.angle, roundness: self.roundness, - pressure: pressures.is_some(), + varies: shaped || size_varies, + shaped, + modes: self.tip_modes(), + variations: [self.angle_variation, self.roundness_variation, self.size_variation], }; let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0])); - area.step(&self.points, pressures); + area.step(&self.points, &|i| { + let [angle, roundness, size] = self.tip_of_point(i); + [angle, roundness, if size_varies { size } else { self.size }] + }); let paths = area.paths(&self.points); o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 })); o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); self.area_pending.set(area.pending(&self.points)); self.area.set(Some(area)); - } else if let Some(pressures) = self.size_pressures() { - // With Size set to Pressure, each step of the drag shows as wide as the pen pressed there. - for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) { - let pressure = f64::from(p[0] + p[1]) / 2.0; - let width = super::pressure_size(self.size, self.size_variation, pressure) * cx.zoom; + } else if size_varies { + // With Size on a mode that follows the pen, each step of the drag shows as wide as the + // tip the pen gives at its ends. + for (j, seg) in self.points.windows(2).enumerate() { + let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom; o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false }); } } else { diff --git a/crates/tools/src/draw2/gesture/area.rs b/crates/tools/src/draw2/gesture/area.rs index a56322db40..418cd349f7 100644 --- a/crates/tools/src/draw2/gesture/area.rs +++ b/crates/tools/src/draw2/gesture/area.rs @@ -2,10 +2,11 @@ //! tip covers, built a bounded amount at a time. //! //! The drag is cut into pieces of up to [`PIECE_SEGMENTS`] segments (one segment each when the -//! Size varies with pressure). A call outlines again, in the space where the tip is round, only the +//! tip varies along the drag). A call outlines again, in the space where the tip is round, only the //! pieces it added segments to. A piece's outline then loses the parts that lie inside the area //! of another piece, found through a grid of squares that lists the segments near each square, so -//! the pieces show as one outline. One call takes at most [`POINTS_PER_CALL`] new points and does at most +//! the pieces show as one outline. When the tip's angle or roundness varies, each segment has its +//! own space where its tip is round, and the grid is on the page. One call takes at most [`POINTS_PER_CALL`] new points and does at most //! [`WORK_PER_CALL`] units of work, plus the one step it was in; what is left waits for the next //! call ([`AreaPreview::pending`]). Until then a piece shows the outline it last finished, and the //! points not yet taken show as a thin line. The settled pieces show as paths of up to @@ -15,14 +16,15 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; +use vectorcraft_brush::Variation; use vectorcraft_geom::{Affine, BezPath, Line, ParamCurve, PathData, PathEl, PathSeg, Point, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{Cap, Join}; use super::super::{MIN_BRUSH_SIZE, blob_tip, eraser_tip, pressure_size}; -/// The most segments of a drag that one piece of its outline holds, when the Size does not vary -/// with pressure (a piece then holds one segment). +/// The most segments of a drag that one piece of its outline holds, when the tip does not vary +/// along the drag (a piece then holds one segment). pub(super) const PIECE_SEGMENTS: usize = 32; /// The most points of a drag one call takes. pub(super) const POINTS_PER_CALL: usize = 256; @@ -68,10 +70,19 @@ pub(super) struct AreaKey { pub variation: f64, pub angle: f64, pub roundness: f64, - /// Each segment is as wide as the pen pressed there. - pub pressure: bool, + /// Each segment takes its own tip from the pen's readings at its ends ([`AreaPreview::step`]): + /// its own size, and with `shaped` its own angle and roundness. + pub varies: bool, + /// Each segment's tip has its own angle and roundness. + pub shaped: bool, + /// The modes and Variations of the angle, roundness and size that the tips at the points follow. + pub modes: [Variation; 3], + pub variations: [f64; 3], } +/// A tip's angle in degrees, roundness in percent and size in points. +pub(super) type Tip = [f64; 3]; + /// The work of the last call. #[derive(Clone, Copy, Default, Debug)] pub(super) struct AreaWork { @@ -129,16 +140,24 @@ struct Check { pub(super) struct AreaPreview { key: AreaKey, first: Point, + /// The map from the page to the grid's space: where the tip is round, or the page itself when + /// each segment's tip has its own angle and roundness. squash: Affine, stretch: Affine, - /// The side of the grid's squares, where the tip is round. + /// The side of the grid's squares, in the grid's space. side: f64, - /// The points taken, where the tip is round. + /// The points taken, in the grid's space. sq: Vec, /// The last point taken, on the page. last: Point, - /// The tip's radius along each segment, where the tip is round. + /// The tip at the last point taken, when the tip varies along the drag. + last_tip: Option, + /// The tip's radius along each segment, where its tip is round. It is also as far as the + /// segment's area reaches from the segment in the grid's space. radius: Vec, + /// The map from the grid's space to the space where each segment's tip is round, when each + /// segment's tip has its own angle and roundness (empty otherwise: the grid's space). + to_round: Vec, pieces: Vec, squares: HashMap<(i64, i64), Vec>, /// How many listings the squares hold ([`LISTINGS`]). @@ -156,8 +175,12 @@ pub(super) struct AreaPreview { impl AreaPreview { /// The outline of a drag that starts at `first`. pub(super) fn new(key: AreaKey, first: Point) -> Self { - let stretch = if key.blob { blob_tip(key.angle, key.roundness) } else { eraser_tip(key.angle, key.roundness) }; - let widest = if key.pressure { pressure_size(key.size, key.variation, 1.0) } else { key.size }; + let stretch = match key { + AreaKey { shaped: true, .. } => Affine::IDENTITY, + AreaKey { blob: true, .. } => blob_tip(key.angle, key.roundness), + _ => eraser_tip(key.angle, key.roundness), + }; + let widest = if key.varies { pressure_size(key.size, key.variation, 1.0) } else { key.size }; Self { key, first, @@ -166,7 +189,9 @@ impl AreaPreview { side: widest.max(MIN_BRUSH_SIZE), sq: vec![], last: first, + last_tip: None, radius: vec![], + to_round: vec![], pieces: vec![], squares: HashMap::new(), listed: 0, @@ -208,28 +233,49 @@ impl AreaPreview { } /// Take the points of the drag `pts` added since the last call and check outlines, within this - /// call's limits. `pressures` holds the pen pressure at each point when the Size varies with it. - pub(super) fn step(&mut self, pts: &[Point], pressures: Option<&[f32]>) { + /// call's limits. When the tip varies along the drag, `tip(i)` gives the tip at point `i`, and + /// each segment takes the tip halfway between those at its ends. A last point whose tip changed + /// since it was taken (a pen turned or tilted in place) gives its segment the new tip. + pub(super) fn step(&mut self, pts: &[Point], tip: &dyn Fn(usize) -> Tip) { self.work = AreaWork::default(); let mut changed = BTreeSet::new(); + if self.key.varies + && let Some(j) = self.sq.len().checked_sub(2) + && self.last_tip.is_some_and(|t| t != tip(j + 1)) + { + let k = self.piece_of(j); + let old = self.radius[j]; + self.set_tip(j, tip(j), tip(j + 1)); + self.last_tip = Some(tip(j + 1)); + changed.insert(k); + // The pieces near the old tip or the new one are checked again. + let new = self.radius[j]; + self.radius[j] = old.max(new); + self.near(j, k, false); + self.radius[j] = new; + } while self.sq.len() < pts.len() && self.work.points < POINTS_PER_CALL && self.work.work < WORK_PER_CALL { let i = self.sq.len(); self.sq.push(self.squash * pts[i]); self.last = pts[i]; self.work.points += 1; + if self.key.varies { + self.last_tip = Some(tip(i)); + } let Some(j) = i.checked_sub(1) else { continue }; - let size = match pressures.filter(|_| self.key.pressure).and_then(|f| f.get(j..=i)) { - Some(f) => pressure_size(self.key.size, self.key.variation, f64::from(f[0] + f[1]) / 2.0), - None => self.key.size, - }; - self.radius.push(size / 2.0); - if self.key.pressure || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) { + if self.key.varies { + self.radius.push(0.0); + self.set_tip(j, tip(j), tip(i)); + } else { + self.radius.push(self.key.size / 2.0); + } + if self.key.varies || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) { self.pieces.push(Piece { from: j, to: j, outline: vec![], shown: BezPath::new() }); } let k = self.pieces.len() - 1; self.pieces[k].to = j + 1; changed.insert(k); - self.list(j, k); + self.near(j, k, true); } for k in changed { self.outline_piece(k); @@ -237,6 +283,30 @@ impl AreaPreview { self.check_some(); } + /// Give segment `j` the tip halfway between `from` and `to`, the tips at its ends: its radius, + /// and with `shaped` the map to the space where that tip is round. The angles meet the shorter + /// way round, a tip turned by 180° being the same tip. + fn set_tip(&mut self, j: usize, from: Tip, to: Tip) { + let size = (from[2] + to[2]) / 2.0; + self.radius[j] = size.max(MIN_BRUSH_SIZE) / 2.0; + if self.key.shaped { + let turn = (to[0] - from[0]).rem_euclid(180.0); + let turn = if turn > 90.0 { turn - 180.0 } else { turn }; + let angle = from[0] + turn / 2.0; + let roundness = (from[1] + to[1]) / 2.0; + let round = eraser_tip(angle, roundness).inverse(); + match self.to_round.get_mut(j) { + Some(m) => *m = round, + None => self.to_round.push(round), + } + } + } + + /// The map from the grid's space to the space where segment `m`'s tip is round. + fn round_of(&self, m: usize) -> Affine { + self.to_round.get(m).copied().unwrap_or(Affine::IDENTITY) + } + /// The paths to show: the settled pieces' outlines, joined [`BLOCK_PIECES`] at a time, the /// growing last piece's and a thin line over the points of `pts` not taken yet. The joined /// paths with a changed piece are joined again, newest first, at most @@ -281,13 +351,13 @@ impl AreaPreview { /// How many pieces no longer grow: all of them but a last one with room for more segments. fn settled_count(&self) -> usize { - let growing = !self.key.pressure && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS); + let growing = !self.key.varies && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS); self.pieces.len() - usize::from(growing) } /// The piece that holds segment `j`. fn piece_of(&self, j: usize) -> usize { - if self.key.pressure { j } else { j / PIECE_SEGMENTS } + if self.key.varies { j } else { j / PIECE_SEGMENTS } } /// The square of the grid that holds `p`; `None` far outside any document. @@ -317,16 +387,16 @@ impl AreaPreview { Some(keys) } - /// List segment `j` of piece `k` in the squares its area reaches, and mark the other pieces - /// whose outline its area can reach to be checked again. - fn list(&mut self, j: usize, k: usize) { + /// With `add`, list segment `j` of piece `k` in the squares its area reaches; either way, mark + /// the other pieces whose outline its area can reach to be checked again. + fn near(&mut self, j: usize, k: usize, add: bool) { let (a, b, r) = (self.sq[j], self.sq[j + 1], self.radius[j]); let mut near = vec![]; match self.squares_along(a, b, SEGMENT_SAMPLES) { Some(keys) => { for key in keys { self.work.work += 1; - if self.listed >= LISTINGS { + if self.listed >= LISTINGS || !add { near.extend(self.squares.get(&key).into_iter().flatten().map(|m| *m as usize)); continue; } @@ -350,7 +420,7 @@ impl AreaPreview { } } } - if self.wide.len() < WIDE_SEGMENTS { + if add && self.wide.len() < WIDE_SEGMENTS { self.wide.push(j); } } @@ -374,10 +444,21 @@ impl AreaPreview { fn outline_piece(&mut self, k: usize) { let settled = self.settled_count(); let Some(p) = self.pieces.get(k) else { return }; - let pts = &self.sq[p.from..=p.to]; let width = 2.0 * self.radius[p.from]; - self.work.outlined += pts.len(); - let area = po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath(); + self.work.outlined += p.to + 1 - p.from; + // A piece whose tip has its own angle and roundness (one segment) is outlined where that + // tip is round and taken back to the grid's space. + let area = match self.to_round.get(p.from) { + Some(&round) => { + let pts = [round * self.sq[p.from], round * self.sq[p.to]]; + round.inverse() + * po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath() + } + None => { + let pts = &self.sq[p.from..=p.to]; + po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath() + } + }; let outline = segments(&area); let shown = self.stretch * area; if let Some(p) = self.pieces.get_mut(k) { @@ -454,7 +535,11 @@ impl AreaPreview { /// The stretches of `seg` (from and to, 0 at its start, 1 at its end) that lie inside no area /// of a segment of the drag but `own`. fn visible(&mut self, seg: PathSeg, own: std::ops::Range) -> Vec<(f64, f64)> { - let inside = |s: &Self, q: Point, m: usize| distance_to_segment(q, s.sq[m], s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE); + // Each segment's area is tested where its tip is round. + let inside = |s: &Self, q: Point, m: usize| { + let round = s.round_of(m); + distance_to_segment(round * q, round * s.sq[m], round * s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE) + }; match seg { PathSeg::Line(line) => { let len = line.p0.distance(line.p1); @@ -482,7 +567,14 @@ impl AreaPreview { keys }; let near = self.candidates(keys, &own); - let spans = near.iter().filter_map(|&m| capsule_span(line, self.sq[m], self.sq[m + 1], self.radius[m] * (1.0 - INSIDE))).collect(); + // A map keeps a line's points where they are along it. + let spans = near + .iter() + .filter_map(|&m| { + let round = self.round_of(m); + capsule_span(round * line, round * self.sq[m], round * self.sq[m + 1], self.radius[m] * (1.0 - INSIDE)) + }) + .collect(); gaps(&merge_spans(spans)) } _ => { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..98efc4dee0 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2933,6 +2933,149 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0)); } +/// The outline of the area an Eraser drag covers takes, at each step, the tip the pen gives there +/// on the modes that follow it, as the release erases: turned, made rounder or larger, turned +/// again when the pen turns in place, and turned anew when a Variation changes. A round tip whose Size follows the pen shows each step as +/// wide as that tip, and a mouse, which reads no tilt or rotation, keeps the set tip. +#[test] +fn the_eraser_drag_area_follows_its_variation_modes() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + // Precise cursors: no tip outline, only the outline of the area. + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let set = |t: &mut GestureTool, options: &[(&str, Value)]| { + for (k, v) in options { + t.set_option(k, v); + } + }; + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); + let press = |t: &mut GestureTool, pen: Option, kind: PointerKind, x: f64| { + t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(kind, x, 150.0) }); + }; + + // A tip 20 by 5 pt lying level, its angle on the barrel's rotation by up to 90°. + let mut t = GestureTool::new("eraser"); + set(&mut t, &[("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))]); + // With the barrel turned half way round all along, the tip stands upright: along the + // horizontal drag from x 50 to x 150 the area reaches 2.5 pt either side and 10 pt above and + // below. + press(&mut t, turned, PointerKind::Down, 50.0); + press(&mut t, turned, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + // The barrel turns back with the pointer still: the step takes the tip halfway between the + // two, turned 45°, which reaches √(10² + 2.5²) / √2 pt from the drag every way. + press(&mut t, level, PointerKind::Drag, 150.0); + let r = (100.0f64 + 6.25).sqrt() / 2f64.sqrt(); + near(bounds(&t), (50.0 - r, 150.0 - r, 150.0 + r, 150.0 + r)); + press(&mut t, level, PointerKind::Up, 150.0); + // A Variation changed during the drag gives the outline the new tip: with 45° the turned + // barrel turns the tip 45°. + press(&mut t, turned, PointerKind::Down, 50.0); + press(&mut t, turned, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + t.set_option("angleVariation", &json!(45)); + near(bounds(&t), (50.0 - r, 150.0 - r, 150.0 + r, 150.0 + r)); + press(&mut t, turned, PointerKind::Up, 150.0); + t.set_option("angleVariation", &json!(90)); + // A mouse drag keeps the set tip, lying level. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0)); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)); + + // A round tip whose Roundness follows the tilt by up to 75%, the angle 90°: with the pen + // lying flat the tip is 25% round and stands upright. + let mut t = GestureTool::new("eraser"); + set(&mut t, &[("size", json!(20)), ("angle", json!(90)), ("roundnessMode", json!("tilt")), ("roundnessVariation", json!(75))]); + let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None }); + press(&mut t, flat, PointerKind::Down, 50.0); + press(&mut t, flat, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + press(&mut t, flat, PointerKind::Up, 150.0); + + // Size on Tilt by up to 8 pt, the pen upright: a tip 28 pt long, 7 pt wide standing upright, + // and a round one 28 pt across. + for (roundness, want) in [(25.0, (46.5, 136.0, 153.5, 164.0)), (100.0, (36.0, 136.0, 164.0, 164.0))] { + let mut t = GestureTool::new("eraser"); + set( + &mut t, + &[("size", json!(20)), ("angle", json!(90)), ("roundness", json!(roundness)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(8))], + ); + press(&mut t, upright, PointerKind::Down, 50.0); + press(&mut t, upright, PointerKind::Drag, 150.0); + if roundness < 100.0 { + near(bounds(&t), want); + } else { + let o = t.overlays(&cx); + assert!(matches!(&o[..], [Overlay::Path { width, .. }] if *width == 28.0), "{o:?}"); + } + press(&mut t, upright, PointerKind::Up, 150.0); + } +} + +/// The outline of a long Eraser drag whose tip turns and changes shape with the pen is built a +/// bounded amount per frame, and once finished it shows nothing inside the area: no point of it +/// lies well inside the area of any step, each step with the tip halfway between those at its +/// ends. +#[test] +fn the_outline_of_a_long_varied_eraser_drag_is_bounded_and_shows_nothing_inside() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(12)), + ("roundness", json!(40)), + ("angleMode", json!("pressure")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("pressure")), + ("roundnessVariation", json!(30)), + ("sizeMode", json!("pressure")), + ("sizeVariation", json!(4)), + ] { + t.set_option(k, &v); + } + long_area_drag(&mut t, &cx, 700, |i| 0.2 + 0.7 * ((i % 37) as f32 / 37.0)); + drain_area(&t, &cx); + let shown = shown_points(&t.overlays(&cx)); + assert!(!shown.is_empty()); + let tips: Vec<[f64; 3]> = (0..t.points.len()).map(|i| t.tip_of_point(i)).collect(); + let steps: Vec<(Affine, Point, Point, f64)> = (0..t.points.len() - 1) + .map(|j| { + let (a, b) = (tips[j], tips[j + 1]); + let turn = (b[0] - a[0]).rem_euclid(180.0); + let turn = if turn > 90.0 { turn - 180.0 } else { turn }; + let angle = a[0] + turn / 2.0; + let round = eraser_tip(angle, (a[1] + b[1]) / 2.0).inverse(); + (round, round * t.points[j], round * t.points[j + 1], (a[2] + b[2]) / 4.0) + }) + .collect(); + for &(q, _) in &shown { + for &(round, a, b, r) in &steps { + let d = distance_to_line(round * q, (a, b)); + assert!(d > r * 0.9, "a point of the outline {d} from a step, inside its area of radius {r}, at {q:?}"); + } + } +} + #[test] fn smooth_needs_selection_and_brackets_resize() { let (d, _) = doc_with_rect(); diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..ec321e1bec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5733,7 +5733,9 @@ the drag takes what the pen read there (the points' pressure, tilt and rotation, drag without that reading, such as a mouse drag, erases at the value itself. One Random value per drag, which way Tilt, Bearing and Rotation run, and the value itself without a reading are VectorCraft's own rules. The command refuses another mode, and a variation below 0 or past its range, and erases nothing. In the desktop app -the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. +the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases, and the +outline of the area a drag covers takes, at each step, the tip halfway between those the pen gave at its ends. A Random +value shows as the value itself there, since the release draws it. `tool.setOption {tool: "eraser"}` takes the same keys. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..692791366f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1172,8 +1172,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. 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`). - 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 keeps the set Angle and Roundness, 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. With Size set to Pressure the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). + 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 halfway between those the pen gave at its ends, 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 outline of a drag with a round Eraser tip is drawn whole each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). From c0db7a84260dc9270a7923ca7dc7168d3e844fce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:14:42 -0800 Subject: [PATCH 44/63] .ai save: envelopes on a large canvas stay editable The editing copy of a large canvas wrote every envelope as its drawn art. It now writes warp, mesh and top object envelopes live at 1/10 of their size with the rest of the art, under the same checks as on a normal canvas, and the reader opens them at their size from the editing data alone or beside the PDF part. Read from the editing data alone, a Large Canvas copy also gets: - an envelope's saved box size compared with its contents at the declared scale, so a bounds margin kept with Distort Appearance is no longer lost; - every path's stroke weight, dashes and dash offset at the declared scale, not at 1/10. --- crates/eps/src/ai_editing/tests.rs | 128 +++++++++++++++++- crates/eps/src/ai_editing/writer/envelopes.rs | 10 +- crates/eps/src/import/ai/envelope.rs | 35 ++--- crates/eps/src/import/ai/read/art.rs | 35 +++-- crates/eps/src/import/ai/read/containers.rs | 7 +- crates/eps/src/import/ai/read/document.rs | 7 + docs/target-app-parity.md | 1 + 7 files changed, 185 insertions(+), 38 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index c1e1d664df..88a640ea40 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10810,6 +10810,129 @@ fn unreachable_envelope() -> ! { panic!("not an envelope") } +/// `doc` with its first artboard 20,000.5 points wide: it is written on a large canvas, at 1/10. +fn on_large_canvas(mut doc: Document) -> Document { + doc.artboards[0].rect = Rect::new(0.0, 0.0, 20_000.5, 100.0); + doc +} + +/// A route an envelope was read back by: its name, the envelope and the reader's notes. +type EnvelopeRoute = (&'static str, Node, Vec); + +/// The envelope `doc` holds alone on its first layer, read back from the editing data alone and +/// beside a page that draws as `doc` does ([`read_with_page`]); and the writer's warnings. +fn envelope_both_routes(doc: &Document) -> (Vec, Vec) { + let (alone, warnings, notes) = envelope_back(doc); + let (paged, _, page_notes) = read_with_page(doc); + assert_eq!(paged.len(), 1, "{paged:#?} {page_notes:?}"); + (vec![("alone", alone, notes), ("beside its page", (*paged[0]).clone(), page_notes)], warnings) +} + +/// On a large canvas, a warp, a mesh and a top object envelope, with Edit Contents off and on, are +/// written live at 1/10 and open as the same envelope at their size, from the editing data alone +/// and beside the page: contents, Fidelity, Edit Contents, Envelope Options, shape and name as +/// saved. Saved again as they opened, they open as the same envelope again. +#[test] +fn large_canvas_envelope_kinds_round_trip_on_both_ai_routes() { + // GUARDS: an envelope on a large canvas was written as its drawn art, with a warning. + use vectorcraft_doc::live::EnvelopeOptions; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let doc = on_large_canvas(envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW)); + let text = program(&doc); + assert!(text.contains("%AI24_LargeCanvasScale: 10\n") && text.contains("AIDeformOptionsKey"), "{what}"); + let (routes, warnings) = envelope_both_routes(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + for (route, back, notes) in routes { + let what = format!("{what}, {route}"); + assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}"); + let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { + panic!("{what}: {back:#?} {notes:?}") + }; + assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}"); + assert!(same_envelope_kind(&kind, got), "{what}: {got:?}"); + assert_eq!(back.name.as_deref(), Some("Bent"), "{what}"); + let colors: Vec> = content.iter().map(|c| c.appearance.fill_paint().color()).collect(); + assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}"); + let b = content.iter().filter_map(|c| c.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + let want = Rect::new(40.0, 20.0, 160.0, 80.0); + assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-2), "{what}: {b:?}"); + } + let (back, _, _) = envelope_back(&doc); + let mut again = on_large_canvas(Document::new(200.0, 100.0)); + let layer = again.layers[0].id; + again.insert(Some(layer), usize::MAX, back).unwrap(); + let (twice, warnings, notes) = envelope_back(&again); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}"); + let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}"); + } + } +} + +/// On a large canvas, envelopes with Distort Appearance whose stroked contents (at fractional places) +/// map from their bounds with their strokes keep that margin, the contents' 8-point strokes and the +/// Distort Linear Gradients and Distort Pattern Fills switches, from the editing data alone and +/// beside the page. +#[test] +fn large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes() { + // GUARDS: read from the editing data alone, the saved size was compared at 1/10 with contents at + // their size, and the contents' strokes came back at 1/10: the margin was lost. + use vectorcraft_doc::live::{EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let mut doc = Document::new(200.0, 100.0); + let switches = EnvelopeOptions { distort_linear_gradients: editing, distort_pattern_fills: !editing, ..EnvelopeOptions::NEW }; + let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, editing, switches); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + for c in content.iter_mut() { + let c = Arc::make_mut(c); + c.transform(Affine::translate((0.25, 0.375)), true); + let fill = c.appearance.fill_paint(); + c.appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into(); + } + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let want = *options; + assert!(want.bounds_margin.iter().all(|m| *m > 0.0), "{what}: {want:?}"); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (routes, warnings) = envelope_both_routes(&on_large_canvas(doc)); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + for (route, back, notes) in routes { + let what = format!("{what}, {route}"); + let NodeKind::Envelope { content, options, .. } = &back.kind else { panic!("{what}: {back:#?} {notes:?}") }; + let margin = options.bounds_margin; + assert!(margin.iter().zip(want.bounds_margin).all(|(a, b)| (a - b).abs() < 1e-4), "{what}: {margin:?} {want:?}"); + assert_eq!(EnvelopeOptions { bounds_margin: want.bounds_margin, ..*options }, want, "{what}"); + let widths: Vec = content.iter().filter_map(|c| c.appearance.stroke().map(|s| s.width)).collect(); + assert!(widths.len() == 2 && widths.iter().all(|w| (w - 8.0).abs() < 1e-4), "{what}: {widths:?}"); + } + } + } +} + +/// On a large canvas a path's stroke weight and dashes, written at 1/10, come back at their size +/// from the editing data alone. +#[test] +fn a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone() { + // GUARDS: read from the editing data alone, the stroke's weight, dashes and dash offset came + // back at 1/10 while the path came back at its size. + let mut doc = on_large_canvas(Document::new(200.0, 100.0)); + let mut n = + Node::path(doc.alloc_id(), shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 6.0)); + n.appearance.stroke_mut().unwrap().dash = Some(Dash { pattern: vec![12.0, 4.5], offset: 3.0, align_corners: false }); + put(&mut doc, n); + let back = read_back(&doc); + let st = back.layers[0].children().unwrap()[0].appearance.stroke().cloned().unwrap(); + assert!((st.width - 6.0).abs() < 1e-6, "{st:?}"); + let dash = st.dash.unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 12.0).abs() < 1e-6 && (dash.pattern[1] - 4.5).abs() < 1e-6, "{dash:?}"); + assert!((dash.offset - 3.0).abs() < 1e-6, "{dash:?}"); +} + /// The record is written in the order the reader reads it: on `%_` lines the group holding the /// grid, its dictionary with the options, the contents' block and the kind, then the distorted art /// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and @@ -10923,7 +11046,10 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { ("fractional fidelity", fractional), ("margin kept", margin_kept), ]; - for (what, doc) in cases { + // On a large canvas too. + let large: Vec<(String, Document)> = + cases.iter().map(|(what, doc)| (format!("{what}, on a large canvas"), on_large_canvas(doc.clone()))).collect(); + for (what, doc) in cases.into_iter().map(|(what, doc)| (what.to_string(), doc)).chain(large) { let text = program(&doc); assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}"); let (back, warnings, _) = envelope_back(&doc); diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 09c6a33550..8b4ebc880d 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -27,7 +27,7 @@ use super::{MAX_NEST, Writer, Xy, hide}; use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number}; use crate::ps; -pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; /// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the /// reader's). @@ -356,15 +356,17 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, impl Writer<'_> { /// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity - /// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. Type - /// in its contents is written as type, which the reader makes the envelope's contents again. + /// masks' art, pattern tiles and art cut to a clipping object. On a large canvas it is written at + /// the document's reduced size, its saved box size included, which the reader reads at the + /// declared scale. Type in its contents is written as type, which the reader makes the + /// envelope's contents again. /// False, writing nothing, where it is written as its art instead: where the reader would open it /// in another shape, or with its type as drawn art (threaded type, type with text wrap options, /// type written as its outlines), or some of it is left out for the object limit /// ([`Self::take_objects`]). pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool { let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false }; - if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.checks_left == 0 { + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || self.checks_left == 0 { return false; } if content.iter().any(|c| holds_type(c)) && !content.iter().all(|c| type_reads_back(c, self.doc)) { diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 3ae753b7d5..501b9f4b00 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -121,11 +121,12 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { /// The margins of `content` when the size the file saves for it (`AIDeformArtWidthKey`, /// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies -/// nearer them than its geometric bounds. None without that size, or for contents with no width or -/// no height. -fn saved_margin(o: &Obj, content: &[Arc]) -> Option<[f32; 4]> { +/// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the +/// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for +/// contents with no width or no height. +fn saved_margin(o: &Obj, content: &[Arc], scale: f64) -> Option<[f32; 4]> { let saved = |key: &str| match o.nums(key).as_slice() { - [v] if v.is_finite() => Some(*v), + [v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()), _ => None, }; let (w, h) = (saved("AIDeformArtWidthKey")?, saved("AIDeformArtHeightKey")?); @@ -508,9 +509,10 @@ fn unwrapped(mut nodes: Vec) -> Vec> { } /// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art -/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. -pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option { - envelope_as(o, before, inner, false) +/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. `scale` takes sizes in +/// art space to the space the art was read into ([`saved_margin`]). +pub(super) fn live(o: &Obj, before: Option, inner: Vec, scale: f64) -> Option { + envelope_as(o, before, inner, false, scale) } /// Is the envelope of dictionary `o` a warp? @@ -521,12 +523,12 @@ fn is_warp(o: &Obj) -> bool { /// [`live`] for a warp, as a mesh envelope on the grid its editing data saves (the mesh that shapes /// it), its points and handles as saved: it draws as that grid does, without the warp's style, bend /// and distortions. `None` for an envelope that isn't a warp, or whose grid doesn't read. -fn live_on_saved_grid(o: &Obj, before: Option, inner: Vec) -> Option { - envelope_as(o, before, inner, true) +fn live_on_saved_grid(o: &Obj, before: Option, inner: Vec, scale: f64) -> Option { + envelope_as(o, before, inner, true, scale) } /// [`live`], or with `on_grid` [`live_on_saved_grid`]. -fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool) -> Option { +fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool, scale: f64) -> Option { let editing = switch(o, "AIDeformEditModeKey")?; let (mut options, fidelity) = options(o)?; let before = before?; @@ -546,7 +548,7 @@ fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool) - return None; } if options.distort_appearance { - options.bounds_margin = saved_margin(o, &content).unwrap_or_default(); + options.bounds_margin = saved_margin(o, &content, scale).unwrap_or_default(); } let kind = match (whole(o, "AIDeformStyle")??, on_grid) { (1, false) => warp(o)?, @@ -637,14 +639,15 @@ pub(super) struct WarpedLook { /// An envelope of type read with its drawn art: its dictionary, the group on `%_` lines before it /// and the art in its `AIDeformArtKey` block, as [`live`] takes them (their text slots still -/// empty), and the id of its drawn art in the document. Type is laid out after the layers are read, -/// so it waits for that ([`WarpedType::settle_envelopes`]). +/// empty), the id of its drawn art in the document, and the scale [`live`] takes. Type is laid out +/// after the layers are read, so it waits for that ([`WarpedType::settle_envelopes`]). #[derive(Debug)] pub(crate) struct TypedEnvelope { pub(super) obj: Obj, pub(super) before: Option, pub(super) inner: Vec, pub(super) drawn: NodeId, + pub(super) scale: f64, } /// Why an envelope of type kept its drawn art. @@ -788,7 +791,7 @@ impl WarpedType { shown: &BTreeSet, waiting: usize, ) -> Result<(NodeId, Vec), TypeKept> { - let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope; + let TypedEnvelope { obj, mut before, mut inner, drawn, scale } = envelope; let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?; // The text slots in the contents, in the order the reader put their hidden copies in. let mut slots = vec![]; @@ -813,13 +816,13 @@ impl WarpedType { } // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. - let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; + let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone(), scale) } else { None }; // With Distort Appearance, a file's envelope may map its type from its glyphs grown by half // their strokes' weight or from the glyphs alone, and for type the size the file saves for // that box is often out of date (not the size of the type there now): each is checked. // After all of those, each is checked mapping from what its type paints, where that box is // another: it is measured only when such a check comes and one is left. - let kinds: Vec = live(&obj, before, inner).into_iter().chain(on_grid).collect(); + let kinds: Vec = live(&obj, before, inner, scale).into_iter().chain(on_grid).collect(); if kinds.is_empty() { return Err(TypeKept::Read); } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3338968895..c181fcb9d5 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -2,8 +2,8 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::raster::{self, Limits, Shape}; use super::types::{ - FLIP, Frame, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, - NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, + FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, + MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, @@ -224,12 +224,7 @@ impl<'a> Reader<'a> { items.push(AppearanceItem::Fill(FillLayer { overprint: gs.overprint_fill, ..FillLayer::new(fill_paint.unwrap_or(gs.fill.clone())) })); } if stroke { - let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.line_width()); - st.cap = gs.cap; - st.join = gs.join; - st.miter_limit = gs.miter; - st.dash = gs.dash.clone(); - st.overprint = gs.overprint_stroke; + let st = self.stroke_layer(stroke_paint.unwrap_or(gs.stroke.clone()), &gs); items.push(AppearanceItem::Stroke(st)); } let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide }; @@ -330,17 +325,29 @@ impl<'a> Reader<'a> { if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { return; } - let mut st = StrokeLayer::new(gs.stroke.clone(), gs.line_width()); - st.cap = gs.cap; - st.join = gs.join; - st.miter_limit = gs.miter; - st.dash = gs.dash.clone(); - st.overprint = gs.overprint_stroke; + let st = self.stroke_layer(gs.stroke.clone(), &gs); + let Some(n) = self.frames.last_mut().and_then(|f| f.children.last_mut()) else { return }; let mut a = (*n.appearance).clone(); a.items.push(AppearanceItem::Stroke(st)); n.appearance = a.into(); } + /// A stroke of `paint` with graphics state `gs`'s weight, caps, joins, miter limit, dashes and + /// overprint, its weight and dashes at the scale the art is read at ([`Self::space_scale`]). + fn stroke_layer(&mut self, paint: Paint, gs: &GState) -> StrokeLayer { + let k = self.space_scale(); + let mut st = StrokeLayer::new(paint, gs.line_width() * k); + st.cap = gs.cap; + st.join = gs.join; + st.miter_limit = gs.miter; + st.dash = gs.dash.clone().map(|mut d| { + d.scale(k); + d + }); + st.overprint = gs.overprint_stroke; + st + } + pub(super) fn set_instance(&mut self, i: &Instance) { let mut to_doc = self.space(); // In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 830e3a48d0..9db1470093 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -885,6 +885,7 @@ impl<'a> Reader<'a> { return; } let Some(p) = self.envelopes.pop() else { return }; + let scale = self.space_scale(); let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { self.warn(crate::import::ai::envelope::drawn_note(p.typed)); @@ -894,7 +895,7 @@ impl<'a> Reader<'a> { self.wait_for_type(p); return; } - let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten(); + let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner, scale)).flatten(); let Some(kind) = live else { self.warn(crate::import::ai::envelope::DRAWN); return; @@ -982,8 +983,8 @@ impl Reader<'_> { self.warn(crate::import::ai::envelope::TYPE_DRAWN); return; } - let drawn = drawn.id; - self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn }); + let (drawn, scale) = (drawn.id, self.space_scale()); + self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn, scale }); } } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 312b7cc275..258d7d584b 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -934,6 +934,13 @@ impl<'a> Reader<'a> { } } + /// How many times as long [`Self::space`] makes a length in art space: a Large Canvas copy's + /// declared scale in the document, and 1 in a pattern's or a symbol's definition. + pub(super) fn space_scale(&mut self) -> f64 { + let k = self.space().determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 { k } else { 1.0 } + } + /// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a /// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's /// origin there, as an instance's matrix in it is; `None` there without a template box. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 34344bde50..0c9d6a4cde 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1797,6 +1797,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 envelopes and images with a Warp in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). + On a large canvas ([the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html); VectorCraft writes one when the artboards together are wider or taller than 16,381 points, its own limit), that `.ai` keeps warp, mesh and top object envelopes editable too: the editing copy writes them live at 1/10 of their size with the rest of the art, and VectorCraft's `.ai` reader opens them at their size, from the editing data alone or beside the PDF part. Read from the editing data alone, an envelope's saved box size is compared with its contents at the same scale, so a bounds margin kept with Distort Appearance comes back, and every path's stroke weight, dashes and dash offset come back at their size, not at 1/10 (`large_canvas_envelope_kinds_round_trip_on_both_ai_routes`, `large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes` and `a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone` in `crates/eps/src/ai_editing/tests.rs`). An envelope whose contents hold type keeps the type editable in that `.ai`: the editing copy writes the type as type in the envelope's contents, in the form the `.ai` reader opens as a live envelope of type (`TypedEnvelope` in `crates/eps/src/import/ai/envelope.rs`), so the file opens with the type shown and editable in the envelope's contents, with Edit Contents off or on. An envelope of type in a symbol's art, and one whose type is threaded, has text wrap options or is written as its outlines (mirrored type, for example), is written as its distorted art, as before (`an_envelope_of_type_is_read_back_live_with_its_type`, `an_envelope_of_type_written_as_its_art_leaves_no_story` and `an_envelope_of_type_in_a_symbol_or_a_thread_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`). A top object whose top and bottom sides, or left and right sides, have different numbers of segments is also saved live: the side with fewer segments is split into as many as the side across from it has (each segment into equal spans of its curve, a straight one at even steps), up to the 50 a side the grid holds, so the file opens with the same corners and the same mapping of the contents, its outline holding the added anchors. Where the split side would share out the contents another way, as a side of two curves that aren't one curve can, or a side has more than 50 segments, the envelope is written as its distorted art, with the warning (`a_top_object_with_uneven_sides_is_read_back_live`, `a_top_object_split_to_the_grids_limit_is_read_back_live` and `a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes eligible paths, compound paths and groups with live effects with an art style when the writer supports their appearance and effects (not a filled path that uses the even-odd rule, and none on a large canvas), which VectorCraft's `.ai` reader opens as the same appearance with its effects live (`objects_with_live_effects_are_read_back` and `every_effect_setting_written_on_an_object_is_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the objects written without one and the effects they lose). From a6d9dd2881dc3731f4eeacedb1ad333db775644f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:34:12 -0800 Subject: [PATCH 45/63] Import PDF: artboards on trim boxes keep the bleed between them Opening a PDF with Crop To Trim Box put each artboard 36 pt after the one before, while the bleed boxes round the trim boxes became the document's bleed. With a bleed over 18 pt, one page's bleed reached into the next artboard, and a page exported with its bleed showed part of its neighbor. The document's bleed is now read from every picked page first, and the artboards are 36 pt apart plus that bleed on both sides, as linked pages on their trim boxes are laid out since #7723. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/pdf/src/import/entry.rs | 26 ++++++++++++++++-------- crates/pdf/src/lib.rs | 3 ++- crates/pdf/src/tests/import_options.rs | 21 +++++++++++++++++++ docs/mcp.md | 2 +- 5 files changed, 43 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 4a3ca6265a..657cab3060 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 8503b4fb20..8f84b9a332 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -239,6 +239,14 @@ pub fn imports_of(bytes: &[u8]) -> usize { IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) } +/// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]). +fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator>) -> [f64; 4] { + pages.fold([0.0; 4], |widest, page| { + let bleed = crate::pages::bleed(page); + std::array::from_fn(|i| widest[i].max(bleed[i])) + }) +} + /// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`. fn read_opened( bytes: &[u8], @@ -286,15 +294,17 @@ fn read_opened( let mut nesting = Nesting::new(); // The top-level groups in the order the pages mark them, bottom first. let (mut order, mut known) = (vec![], HashSet::new()); + // Artboards on the trim boxes have the bleed boxes round them as the document's bleed, so the + // art there shows and prints as bleed. + if opts.crop == CropTo::Trim { + doc.setup.bleed = widest_bleed(picked.iter().filter_map(|&n| pages.get(n))); + } + // The artboards are the gap apart plus the document's bleed on both sides, which export adds + // round every artboard, so no page's bleed reaches into the next artboard. + let [_, _, bleed_left, bleed_right] = doc.setup.bleed; + let spacing = opts.artboard_gap + bleed_left + bleed_right; for (i, &number) in picked.iter().enumerate() { let Some(page) = pages.get(number) else { continue }; - // Artboards on the trim boxes have the bleed boxes round them as the document's bleed - // (the widest of the pages' on each side), so the art there shows and prints as bleed. - if opts.crop == CropTo::Trim { - for (side, b) in doc.setup.bleed.iter_mut().zip(crate::pages::bleed(page)) { - *side = side.max(b); - } - } // The chosen box sits at (x, 0); the page draws round it. let (init, frame) = crate::pages::frame(page, opts.crop); let mut ab = Rect::new(x, 0.0, x + frame.width(), frame.height()); @@ -371,7 +381,7 @@ fn read_opened( right = right.max(art.x1); ab = art; } - x = right + opts.artboard_gap; + x = right + spacing; clear = right.max(art_right) + opts.artboard_gap; doc.artboards.push(Artboard { id: i as u32 + 1, diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8f9959c77f..0658624452 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -134,7 +134,8 @@ impl PdfOptions { pub struct ImportOptions { /// Import at most this many pages (of those picked); `None` = all of them. pub max_pages: Option, - /// Horizontal gap in points between the artboards created for consecutive pages. + /// Horizontal gap in points between the artboards created for consecutive pages (on trim + /// boxes, plus the document's bleed on both sides). pub artboard_gap: f64, /// 0-based pages to import, in this order; `None` = every page. pub pages: Option>, diff --git a/crates/pdf/src/tests/import_options.rs b/crates/pdf/src/tests/import_options.rs index 2ed84d5dc0..a419d64137 100644 --- a/crates/pdf/src/tests/import_options.rs +++ b/crates/pdf/src/tests/import_options.rs @@ -91,6 +91,27 @@ fn trim_box_artboards_take_the_bleed_box_round_them_as_the_document_bleed() { assert_eq!((d.artboards[0].rect.width(), d.setup.bleed), (300.0, [0.0; 4])); } +#[test] +fn trim_box_artboards_keep_the_bleed_between_them() { + // The second page's bleed box is its trim box: the document's bleed (10 mm, over half the + // 36 pt gap) still goes round its artboard. + let edge = Some([50.0, 50.0, 250.0, 150.0]); + let plain = PdfPage { bleed: edge, trim: edge, ..PdfPage::new(300.0, 200.0, "0 g 50 50 200 100 re f") }; + let bytes = pdf(&[bled_page(), plain, bled_page()], None); + let d = open(&bytes, ImportOptions { crop: CropTo::Trim, ..Default::default() }); + let starts: Vec = d.artboards.iter().map(|a| a.rect.x0).collect(); + let step = 200.0 + 36.0 + 2.0 * BLEED; + assert!(near([starts[0], starts[1], starts[2], 0.0], [0.0, step, 2.0 * step, 0.0]), "{starts:?}"); + // Each artboard's bleed ends 36 pt before the next one's begins. + for pair in d.artboards.windows(2) { + let (a, b) = (d.setup.bleed_rect(pair[0].rect), d.setup.bleed_rect(pair[1].rect)); + assert!((b.x0 - a.x1 - 36.0).abs() < 1e-3, "{a:?} {b:?}"); + } + // On the crop boxes there is no bleed, and the artboards are 36 pt apart. + let d = open(&bytes, ImportOptions::default()); + assert_eq!(d.artboards.iter().map(|a| a.rect.x0).collect::>(), [0.0, 336.0, 672.0]); +} + #[test] fn missing_boxes_fall_back_to_the_crop_box_and_boxes_are_clipped_to_the_media_box() { let page = PdfPage { crop: Some([10.0, 10.0, 290.0, 390.0]), art: Some([-50.0, 0.0, 100.0, 100.0]), ..PdfPage::new(300.0, 400.0, "") }; diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..b45685963d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1313,7 +1313,7 @@ unknown label is refused. The `warnings` of the result name the first three such Opening a PDF (or `.ai`) imports every page as an artboard and layer; `document.open` takes `pages` ("2-3, 5", 1-based), `cropTo` (`bounding` (the art's bounds), `art`, `crop` (default), `trim`, `bleed`, `media`: the box each artboard gets; -with `trim` the bleed box round it becomes the document's bleed, and a PDF-compatible `.ai` or a PDF saved with its editing data opens on its trim boxes for +with `trim` the bleed box round it becomes the document's bleed and the artboards are 36 pt apart plus that bleed on both sides, and a PDF-compatible `.ai` or a PDF saved with its editing data opens on its trim boxes for `crop`, its crop box taking the bleed in) and `password` for an encrypted file. `document.pdfInfo` reads a file without opening it: the page count, each page's size and boxes, `needsPassword`, and with `thumbnail: n` a PNG of page n. It reads a PostScript file (an EPS, a `.ps` file, a `.ai` in PostScript form) as one page the size of its bounding box (a US Letter page without one), with an From 878c6ba1e12032e61b592e5a22192af72b0f78c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:36:47 -0800 Subject: [PATCH 46/63] Export: nested symbol instances count their baked art against the symbol art limit An export that bakes a symbol instance with geometry effects inside the art of another such instance counted only the symbol's art before its effects against the 262,144 objects of nested symbol art one export bakes. Copies the art's effects made were not counted, so the baked art could pass the limit. The art the instance bakes to now takes the place of the symbol's art in the count; when it does not fit, the instance stays as it is with its effects and gives back what its art held while it baked, as it does when reshaping it gives nothing. --- crates/effects/src/bake.rs | 29 ++++++++-- crates/effects/src/bake/tests.rs | 96 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 121 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d8f3ae0fe4..b008f41faf 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -369,17 +369,27 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { }; // Instances baked inside the art of others stop at the depth limit, or once their art // passes the objects one export bakes that way: an instance of a symbol whose art holds - // instances of itself is kept as it is there. + // instances of itself is kept as it is there. The symbol's art is held in the count while + // it bakes, so the instances inside it bake only within what is left; the art it bakes to, + // with what its effects add, then takes its place in the count, or the instance stays as it + // is and gives its objects back when that art does not fit. let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); - if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 { + let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0; + let before = NESTED_NODES.with(|c| c.get()); + if nested { let count = symbol.as_ref().map_or(0, |a| a.count() as u64); - let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count); + let spent = before.saturating_add(count); if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES { return None; } NESTED_NODES.with(|c| c.set(spent)); } - let m = reshape(Some(d), n, symbol.as_ref())?; + let Some(m) = reshape(Some(d), n, symbol.as_ref()) else { + if nested { + NESTED_NODES.with(|c| c.set(before)); + } + return None; + }; if instance { INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); } @@ -387,7 +397,16 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { if instance { INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); } - return Some(baked.unwrap_or(m)); + let baked = baked.unwrap_or(m); + if nested { + let spent = before.saturating_add(baked.count() as u64); + if spent > crate::SYMBOL_ART_MAX_NODES { + NESTED_NODES.with(|c| c.set(before)); + return None; + } + NESTED_NODES.with(|c| c.set(spent)); + } + return Some(baked); } // Symbol instances whose art draws live effects, when the caller asks for them: the art // placed, then baked. When the baked art passes the export's budget, or would draw too deep diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index fba4f75e5f..66b34162de 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -1525,3 +1525,99 @@ fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() { let room = bake(&d, Some((true, a + e + f, ALL))).unwrap(); assert!(!is_instance(&room, 900) && !is_instance(&room, 901)); } + +/// Instance `id` of `symbol` with a geometry effect, so baking it reshapes its art. +fn offset_instance(id: u64, symbol: &str) -> Node { + let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY); + n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0}))); + n +} + +/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol +/// art already baked: the baked object, and the objects counted after it. +fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option, u64) { + INSTANCE_DEPTH.with(|c| c.set(1)); + NESTED_NODES.with(|c| c.set(spent)); + let out = bake_node(d, n); + INSTANCE_DEPTH.with(|c| c.set(0)); + (out, NESTED_NODES.with(|c| c.replace(0))) +} + +/// The object with id `id` in `n`'s subtree. +fn find(n: &Node, id: u64) -> Option<&Node> { + if n.id == NodeId(id) { + return Some(n); + } + n.children().into_iter().flatten().find_map(|c| find(c, id)) +} + +/// Is `n` an object other than a symbol instance? +fn baked(n: Option<&Node>) -> bool { + n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. })) +} + +/// An instance baked inside another instance's art counts the art it bakes to, the copies its +/// symbol's effects make included: art that fits exactly takes the last of the budget, and art +/// whose symbol fits but whose baked art does not leaves the instance as it is. +#[test] +fn nested_reshape_counts_baked_art() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Inner", gradient_copies(800)); + let n = offset_instance(900, "Inner"); + let source = d.symbols[0].art.count() as u64; + let (all, spent) = bake_nested(&mut d, &n, 0); + let baked = all.map_or(0, |m| m.count() as u64); + assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1"); + assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art"); + let max = crate::SYMBOL_ART_MAX_NODES; + let (exact, spent) = bake_nested(&mut d, &n, max - baked); + assert!(exact.is_some(), "{baked} objects fit in {baked}"); + assert_eq!(spent, max); + let (short, spent) = bake_nested(&mut d, &n, max - baked + 1); + assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not"); + assert_eq!(spent, max - baked + 1, "the instance left as it is counts nothing"); +} + +/// An instance left as it is because its baked art does not fit gives back what its art held +/// while it baked: an instance after it whose baked art fits in what is left is baked. +#[test] +fn nested_reshape_refusal_restores_budget() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Big", gradient_copies(800)); + add_symbol(&mut d, "Small", moved_square(810)); + let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small")); + let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64); + let (b, s) = (count(&mut d, &big), count(&mut d, &small)); + assert!(s < b, "{s} < {b}"); + let first = crate::SYMBOL_ART_MAX_NODES - b + 1; + let (refused, spent) = bake_nested(&mut d, &big, first); + assert!(refused.is_none(), "the big art passes the budget"); + assert_eq!(spent, first); + let (later, spent) = bake_nested(&mut d, &small, spent); + assert!(later.is_some(), "the small art fits in what the big art gave back"); + assert_eq!(spent, first + s); +} + +/// An instance inside another instance's art whose own art holds a reshaped instance counts that +/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both. +#[test] +fn nested_reshape_counts_successful_descendants_once() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Inner", gradient_copies(800)); + let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)])); + let outer = offset_instance(900, "Outer"); + let (all, spent) = bake_nested(&mut d, &outer, 0); + let all = all.unwrap_or_else(|| panic!("the outer instance is baked")); + assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}"); + let total = all.count() as u64; + assert_eq!(spent, total); + let max = crate::SYMBOL_ART_MAX_NODES; + let (exact, spent) = bake_nested(&mut d, &outer, max - total); + let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}")); + assert!(baked(find(&exact, 802)), "the inner instance is baked too"); + assert_eq!(spent, max); + let (short, spent) = bake_nested(&mut d, &outer, max - total + 1); + assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked"); + assert!(spent <= max); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..2b64f7f501 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1692,6 +1692,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). + When an export bakes a symbol instance with geometry effects inside the art of another such instance, it counts the art the inner instance bakes to, the copies its symbol's effects make included, against the 262,144 objects of symbol art one export bakes that way; it counted only the symbol's art before its effects. An instance whose baked art would pass that count stays an instance with its effects, and the objects its art held while it baked do not count against the instances after it. These are VectorCraft's own limits (effects `bake::nested_reshape_counts_baked_art`, `nested_reshape_refusal_restores_budget`, `nested_reshape_counts_successful_descendants_once`). A raster effect (Drop Shadow, Outer Glow, Gaussian Blur and the other effects that paint pixels) on a symbol instance's topmost fill draws on each filled shape of the symbol's art, and one on its topmost stroke draws on each stroked shape, after any geometry effects listed before it, under the same rules as geometry effects: only a visible fill or stroke with an opacity above 0 counts, a group's own fills and strokes in the art take the effect, and an instance inside the art passes it on. Each shape gets its own shadow or glow, which is VectorCraft's own rule. The canvas, Use Preview Bounds and the drawn bounds, SVG and PDF export draw it, and Object › Expand Appearance is enabled for such an instance and makes the effect an image at the document's raster effects resolution, in one undo step (engine `expand::a_symbol_instance_fill_shadow_shadows_its_filled_art`, `a_symbol_instance_stroke_shadow_shadows_only_its_stroked_art`, `a_symbol_instance_fill_shadow_follows_the_fill_offset_before_it`, `a_nested_symbol_instance_takes_the_outer_fill_shadow`, `export_draws_a_symbol_instance_fill_shadow`). Existing documents with a raster effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). From 2f432926b2e252488af174f7258725f9960a2167 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:41:11 -0800 Subject: [PATCH 47/63] Smooth tool: keep corners on a path cut into very many short segments The Smooth tool measured the turn around each corner by walking at most 256 segments from the anchor, and did not keep an anchor as a corner when twice the reach lay farther than that. A corner of a path cut into short segments was rounded off: an open path with 0.05 pt segments at the default 12 pt reach, or a square in 0.25 pt segments with a 40 pt reach. The walk now has no segment limit. Each segment's length is measured once per path, and the lengths are added up in blocks of 2, 4, 8 and more segments, so finding the point a reach away skips whole blocks and measures only the segment it lands in. Each block adds up only its own segments, so short segments keep their lengths next to very long ones. --- crates/engine/src/cmd/draw2/smooth.rs | 77 ++++++++++++++++++++++----- crates/engine/src/tests/draw2.rs | 33 ++++++++++++ docs/mcp.md | 2 +- 3 files changed, 98 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index 883c9ba5ed..d0f480d132 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { // eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a // loop shorter than the reach is not all corners, while a square's or a triangle's corners still are. let mut spans = [reach, 2.0 * reach]; + // The lengths along the path ahead and back, measured once when an anchor needs them. + let (mut ahead, mut back) = (None, None); if closed { - let mut total = 0.0; - for i in 0..n { - total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1; - } + let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum()); if !(total.is_finite() && total > 0.0) { return corners; } @@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) { continue; } - let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue }; - let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue }; + let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach)); + let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue }; + let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)); + let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue }; *flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])] .into_iter() .all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG)); @@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { corners } -/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each -/// anchor on a path of very many very short segments. -const MAX_CORNER_WALK: usize = 256; +/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead +/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last +/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l` +/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short +/// stretch keeps its length next to very long ones. The segment past an open path's end has no +/// length. +fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec> { + let n = anchors.len(); + let lens: Vec = + (0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect(); + let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::>()]; + while let Some(last) = blocks.last().filter(|b| b.len() > 1) { + let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect(); + blocks.push(next); + } + blocks +} + +/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back +/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None` +/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks` +/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of +/// very many short segments is not walked one segment at a time from each anchor. +fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec], reach: f64) -> Option { + let (n, (i, forward)) = (anchors.len(), from); + let start = if forward { i } else { n - 1 - i }; + let end = start + + if closed { + n + } else if forward { + n - 1 - i + } else { + i + }; + let (mut pos, mut gone) = (start, 0.0); + // The largest block that starts at `pos`, stays within the walk and ends within `dist`, until + // none does; a block whose length is not a number is never skipped. + while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| { + let size = 1usize << l; + let len = lens.get(pos >> l).copied()?; + (pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len)) + }) { + pos += size; + gone += len; + } + let at = if forward { pos % n } else { n - 1 - pos % n }; + walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0] +} /// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise, /// past no more than `segments` segments, measured along the lines between each curved segment's @@ -1099,11 +1145,12 @@ mod tests { } /// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach - /// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments - /// than it measures before it gets that far, its top is not one, as the path turns by about 51° - /// over that reach. + /// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its + /// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51° + /// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long + /// are corners too. #[test] - fn a_corner_is_not_kept_where_the_reach_is_not_measured() { + fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() { let side = 400.0 * std::f64::consts::SQRT_2; let steps = side.ceil() as usize; let mut pts = vec![(-3000.0, 0.0)]; @@ -1120,6 +1167,10 @@ mod tests { let top = steps + 1; assert_eq!(anchors[top].p, Point::new(0.0, 400.0)); assert!(smooth_corners(&anchors, false, 10.0)[top]); + assert!(smooth_corners(&anchors, false, 300.0)[top]); + let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]); + let corners = smooth_corners(&long, false, 0.5); + assert!(corners[2] && corners[3] && corners[4], "{corners:?}"); assert!(!smooth_corners(&anchors, false, 1000.0)[top]); } diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 45ff1f84c1..0a3f188fbc 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2326,6 +2326,39 @@ fn smoothing_keeps_a_corner_between_curves() { } } +/// A Smooth drag over a corner of a path cut into very many short segments keeps it, however many +/// segments twice the reach spans: an open path's 90° corner with legs of 2,000 segments 0.05 pt +/// long at the default reach, and a corner of a 200 pt square cut into 0.25 pt segments with a 40 pt +/// reach. +#[test] +fn smoothing_keeps_corners_on_a_path_of_many_short_segments() { + let mut s = session(); + let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 2000); + smooth_pass(&mut s, &drag); + let at = smooth_turn_at(&path(&s, id).subpaths[0], v); + assert!(at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the open path's corner is kept: {at:?}"); + + let mut s = session(); + let ends = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)]; + let mut anchors = vec![]; + for k in 0..4 { + let (a, b) = (ends[k], ends[(k + 1) % 4]); + anchors.extend((0..800).map(|j| { + let p = a.lerp(b, f64::from(j) / 800.0); + json!({"x": p.x, "y": p.y}) + })); + } + let id = smooth_test_path(&mut s, &anchors, true); + let v = ends[1]; + let mut drag: Vec = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect(); + drag.extend((0..=8).map(|k| v + kurbo::Vec2::new(0.0, 5.0 * f64::from(k)))); + let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 40, "fidelity": 2.5})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + let at = smooth_turn_at(sp, v); + assert!(sp.closed && at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the square's corner is kept: {at:?}"); +} + /// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its /// place and its turn. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..cecf17b3d3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5840,7 +5840,7 @@ direction. `path.smoothRegion` keeps an anchor as a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) at the anchor and also over `radius` and over twice `radius` on either side of it (on a closed path that the drag reaches all the -way round, no more than an eighth of its length), so a jag or a bump smaller than `radius` is still smoothed. The stretches on either side of a kept corner are smoothed and refitted on their +way round, no more than an eighth of its length), measured along the path however many segments it is cut into, so a jag or a bump smaller than `radius` is still smoothed. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every call and at any `fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° threshold is VectorCraft's own value. From 2123ecd397ee68144874e80df7eee226a6ec6138 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:44:37 -0800 Subject: [PATCH 48/63] Properties: the Graph section test expects the Graph Type dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Graph Type… now opens Object › Graph › Type…'s own dialog (graphType) since main made Graph Type a dialog of its own, so the test checks that kind and the graph's column type instead of the generic command dialog. --- crates/ui-egui/src/panels/properties/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index b8f702be83..7411216276 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -2061,8 +2061,7 @@ fn one_selected_graph_has_a_graph_section_whose_buttons_open_the_graph_dialogs() app.ui.dialog.take().unwrap_or_else(|| panic!("{label:?} opened no dialog")) }; let d = press(&mut app, "Graph Type…"); - assert_eq!((d.kind.as_str(), d.str("__command")), ("command", "graph.setType".to_string())); - assert_eq!(d.str("type"), "column"); + assert_eq!((d.kind.as_str(), d.str("type")), (crate::dialogs::graph_type::KIND, "column".to_string())); assert_eq!(press(&mut app, "Graph Data…").kind, crate::dialogs::graph_data::KIND); assert_eq!(press(&mut app, "Column…").kind, crate::dialogs::graph_design::COLUMN); } From 2d361e2ad7a79d3eb78a1e5903dd192fa070416d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:47:47 -0800 Subject: [PATCH 49/63] SVG import: a raster stored again as PNG keeps its ICC profile An image that SVG import writes again as PNG (a TIFF, or a PNG, JPEG, GIF or WebP whose orientation turns it) now keeps the ICC profile its file carries, as an iCCP chunk, when the profile's color space is the stored samples': gray for gray samples, RGB for RGB ones. Open and Place already keep it. Profiles of another color space, ones too short to be a profile, and the profile of a TIFF whose own reader converts its pixels to RGBA are left out, and the image still imports. Sample types a PNG doesn't hold are stored as 8-bit RGBA, as Open and Place store them. --- crates/svg/src/import/files.rs | 49 +++++++-- crates/svg/tests/it/image_orientation.rs | 127 +++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 166 insertions(+), 11 deletions(-) diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index c60d22f983..8b612f78c1 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -875,7 +875,8 @@ fn raster(format: image::ImageFormat) -> Option { /// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`], /// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes /// and fits the image as it is shown, with the resolution the file declares -/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also +/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn, and the ICC profile +/// the file carries when its color space is the written samples' (gray or RGB). A CMYK TIFF also /// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG /// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when /// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count @@ -893,7 +894,7 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { return Some(Shown { kind, bytes, cmyk: None }); } let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff); - let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; + let (mut img, icc) = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; let ppi = vectorcraft_doc::ppi::resolution(&bytes); // The resolution describes the stored pixels; a quarter turn swaps its axes. let quarter = orientation.is_some_and(|o| o.to_exif() >= 5); @@ -906,18 +907,38 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { if let Some(orientation) = orientation { img.apply_orientation(orientation); } + use image::DynamicImage as D; + let img = match img { + D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img, + D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img, + other => D::ImageRgba8(other.into_rgba8()), + }; let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?; + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + if let Some(icc) = icc.filter(|icc| png_takes_icc(&img, icc)) { + // A profile the encoder doesn't take leaves the image without one. + let _ = image::ImageEncoder::set_icc_profile(&mut encoder, icc); + } + img.write_with_encoder(encoder).ok()?; if let Some(ppi) = shown_ppi { png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi); } Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk }) } +/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples': +/// `GRAY` for gray samples, `RGB ` for RGB ones. +fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { + let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" }; + vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want) +} + /// The pixels of encoded image `bytes` (`format` when their bytes don't say), as stored, decoded /// within [`vectorcraft_doc::MAX_RASTER_ALLOC`], counted as decoded and as RGBA, as Open and Place -/// decode them; `None` when they can't be. -fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option { +/// decode them, with the ICC profile their samples are in when the file carries one the decoder +/// can read (a TIFF's read by [`vectorcraft_doc::cmyk::tiff_icc_profile`]); `None` when they +/// can't be. +fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<(image::DynamicImage, Option>)> { use image::ImageDecoder as _; let max = vectorcraft_doc::MAX_RASTER_ALLOC; let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; @@ -927,12 +948,16 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option max || u64::from(w) * u64::from(h) * 4 > max { return None; } - image::DynamicImage::from_decoder(decoder).ok() + // The image decoder reads a TIFF's tags within the size of its pixels, so a small TIFF's + // profile is read by the TIFF decoder itself. + let icc = if tiff { vectorcraft_doc::cmyk::tiff_icc_profile(bytes) } else { decoder.icc_profile().ok().flatten() }; + Some((image::DynamicImage::from_decoder(decoder).ok()?, icc)) } /// The pixels of TIFF `bytes`, as stored, read as Open and Place read them: a TIFF with extra @@ -940,15 +965,17 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option Option { +/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). Pixels the image decoder reads come with the +/// TIFF's ICC profile; the other readers give sRGB pixels, without one. `None` when they can't be +/// read. +fn tiff_pixels(bytes: &[u8]) -> Option<(image::DynamicImage, Option>)> { use image::DynamicImage::ImageRgba8; let cms = vectorcraft_color::cms::active(); if let Some(img) = vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) { - return Some(ImageRgba8(img)); + return Some((ImageRgba8(img), None)); } if let Some(read) = vectorcraft_doc::cmyk::group3_tiff_rgba(bytes) { - return read.ok().map(ImageRgba8); + return read.ok().map(|img| (ImageRgba8(img), None)); } decoded(bytes, image::ImageFormat::Tiff).or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, image::ImageFormat::Tiff)) } diff --git a/crates/svg/tests/it/image_orientation.rs b/crates/svg/tests/it/image_orientation.rs index d9de61290b..e824337857 100644 --- a/crates/svg/tests/it/image_orientation.rs +++ b/crates/svg/tests/it/image_orientation.rs @@ -362,6 +362,133 @@ fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() { } } +/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color +/// space `space`; the bytes after the header differ from place to place. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec { + let mut icc: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc +} + +/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first +/// directory copied to the end of the file with the tag added in order. +fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec { + let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap(); + let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]])); + let mut entries: Vec> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect(); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + let data = u32::try_from(out.len()).unwrap(); + out.extend(icc); + if out.len() % 2 == 1 { + out.push(0); + } + let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n); + let count = u32::try_from(icc.len()).unwrap(); + entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat()); + let ifd = u32::try_from(out.len()).unwrap(); + out[4..8].copy_from_slice(&ifd.to_le_bytes()); + out.extend(u16::try_from(n + 1).unwrap().to_le_bytes()); + out.extend(entries.concat()); + out.extend([0; 4]); + out +} + +/// A little-endian EXIF block (a TIFF header and one directory) giving Orientation `orientation`. +fn exif_block(orientation: u16) -> Vec { + let o = orientation.to_le_bytes(); + [b"II".as_slice(), &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, o[0], o[1], 0, 0], &[0, 0, 0, 0]].concat() +} + +/// The ICC profile and the bits per sample of the PNG `im` is stored as. +fn stored_icc(d: &Document, im: &ImageObject) -> (Option>, u16) { + use image::ImageDecoder as _; + let blob = &d.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + let mut dec = image::codecs::png::PngDecoder::new(std::io::Cursor::new(blob.bytes.as_slice())).unwrap(); + let color = dec.original_color_type(); + (dec.icc_profile().unwrap(), color.bits_per_pixel() / u16::from(color.channel_count())) +} + +/// A raster that import writes again as PNG keeps the gray or RGB ICC profile its file carries, +/// byte for byte, linked and as a data URL: a TIFF, turned or not, and a turned PNG and JPEG, with +/// 16-bit samples kept at 16 bits and the resolution kept beside the profile. A profile of another +/// color space than the written samples', one too short to be a profile, and one on a TIFF whose +/// pixels are read as RGBA by its own reader are left out, and the image still imports. +#[test] +fn a_raster_written_again_as_png_keeps_its_icc_profile() { + use image::{DynamicImage, ImageEncoder as _}; + let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400)); + let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13]))); + let gray8 = DynamicImage::ImageLuma8(image::GrayImage::from_fn(3, 2, |x, y| image::Luma([u8::try_from(x * 80 + y * 7).unwrap()]))); + let rgb16 = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(3, 2, |x, y| { + let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap(); + image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v]) + })); + let tiff_of = |img: &DynamicImage, icc: &[u8]| { + let mut out = Vec::new(); + let mut enc = image::codecs::tiff::TiffEncoder::new(std::io::Cursor::new(&mut out)); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + out + }; + let png = { + let mut out = Vec::new(); + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + enc.set_exif_metadata(exif_block(6)).unwrap(); + rgb16.write_with_encoder(enc).unwrap(); + out + }; + let jpg = { + let mut out = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6)].concat(); + let mut turned = out[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&out[2..]); + turned + }; + let gray = [0, 0, 255, 255, 0, 0, 255, 255]; + let turned_gray = tiff_with_icc(&tiff_at(4, 2, 1, &gray, 6, Some((300, 150))), &gray_icc); + let gray_alpha = [0, 255, 0, 255, 255, 255, 255, 255, 0, 255, 0, 255, 255, 255, 255, 255]; + // (what, file, the ICC profile to keep, bits per sample, resolution) + type Case<'a> = (&'a str, Vec, Option<&'a [u8]>, u16, Option<(f64, f64)>); + let cases: Vec = vec![ + ("RGB TIFF", tiff_of(&rgb8, &rgb_icc), Some(&rgb_icc), 8, None), + ("gray TIFF", tiff_of(&gray8, &gray_icc), Some(&gray_icc), 8, None), + ("16-bit RGB TIFF", tiff_of(&rgb16, &rgb_icc), Some(&rgb_icc), 16, None), + ("gray TIFF, orientation 6, with a resolution", turned_gray, Some(&gray_icc), 8, Some((150.0, 300.0))), + ("16-bit RGB PNG, orientation 6", png, Some(&rgb_icc), 16, None), + ("JPEG, orientation 6", jpg, Some(&rgb_icc), 8, None), + ("RGB TIFF with a gray profile", tiff_of(&rgb8, &gray_icc), None, 8, None), + ("gray TIFF with an RGB profile", tiff_of(&gray8, &rgb_icc), None, 8, None), + ("RGB TIFF with a CMYK profile", tiff_of(&rgb8, &cmyk_icc), None, 8, None), + ("RGB TIFF with a profile too short to be one", tiff_of(&rgb8, &rgb_icc[..40]), None, 8, None), + ("gray TIFF with alpha, read as RGBA", tiff_with_icc(&tiff(4, 2, 2, &gray_alpha, 1), &rgb_icc), None, 8, None), + ]; + let dir = folder("icc"); + for (what, file, icc, bits, ppi) in cases { + std::fs::write(dir.join("photo.img"), &file).unwrap(); + let data = format!("data:;base64,{}", base64_encode(&file)); + for href in ["photo.img", data.as_str()] { + let what = format!("{what}, {}", &href[..href.len().min(12)]); + let (d, im) = import_one(&format!(r#""#), Some(&dir)); + assert_eq!(stored_icc(&d, &im), (icc.map(<[u8]>::to_vec), bits), "{what}"); + assert_eq!(stored_ppi(&d, &im), ppi, "{what}"); + } + } +} + /// A turned JPEG that a linked SVG file links to is turned too. #[test] fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..0ec6393db2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1939,6 +1939,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export with Output › Convert to Destination and a CMYK destination, or an RGB destination other than sRGB that images are converted to, converts an RGB image that carries an ICC profile from that profile to sRGB and then to the destination, with the color settings' rendering intent, instead of reading its numbers as sRGB ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). An untagged image converts from sRGB as before, a gray image keeps its profile, and a profile the color engine can't read leaves the numbers read as sRGB, with a warning. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there (`convert_to_destination_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`). - An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk () or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`). + - An image that SVG import stores again as PNG keeps the ICC profile its TIFF, PNG, JPEG or WebP file carries, as Open and Place keep it, as a PNG `iCCP` chunk, when the profile's color space is the stored samples': gray for gray samples, RGB for RGB ones (). By default, SVG reads an image's colors in the profile built into the image (). A profile of another color space, one too short to be a profile, and the profile of a TIFF whose pixels its own reader converts to RGBA (one with an alpha or other extra channel, or CCITT Group 3) are left out, and the image is still imported (`a_raster_written_again_as_png_keeps_its_icc_profile` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). - SVG import decodes each image data URL (RFC 2397, ) of an `` or `` once, in the imported SVG and in the SVGs shown as its images, however many `` elements, filters or SVG images show it; every use gets the same image. The data URLs of one import decode to at most 512 MB together, VectorCraft's own limit: decoding stops where a URL would pass it, and that image is left out with a warning (`crates/svg/src/import/files.rs`, `crates/svg/tests/it/import_details.rs`). - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `` shows (), chains of ``s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`). From d154d7289021462d83ecbb6029eced32f07837f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:48:26 -0800 Subject: [PATCH 50/63] SVG import: absolutely placed characters one text object cannot place import as a group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SVG reorders right-to-left characters only within a text chunk, while one text object reorders the whole line. In אbג the left-to-right b is drawn right before ג with no kerning between them, so ג stayed where the line put it and the import warned. When kerning cannot put every absolutely placed character on its x, the text is now cut before each such character and each piece is placed again, and the text imports as a group of point type objects named after the element. A text one object can place stays one object. A split text in a clip path clips by the outlines of all its objects. --- crates/svg/src/import/importer.rs | 76 +++++---- crates/svg/src/import/text.rs | 240 +++++++++++++++++++++++------ crates/svg/tests/it/clip_text.rs | 14 ++ crates/svg/tests/it/import_text.rs | 84 +++++++++- docs/target-app-parity.md | 3 +- 5 files changed, 329 insertions(+), 88 deletions(-) diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2eede1f7be..6e3ecb955e 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -243,48 +243,59 @@ impl Importer { if !matches!(kids.get(main), Some(usvg::Node::Path(p)) if p.is_visible()) { return Some(vec![]); } - let text::PendingText { name, mut obj, servers, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); - // The scale the type draws at becomes its size (last, below): text space grows by `grow`. - let xf = ts * obj.xf; - let grow = text::size_scale(&obj, xf); - // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user - // space; runs paint in text space. - let to_text = Affine::scale(grow) * obj.xf.inverse(); + let text::PendingText { name, obj, servers, rest, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); let slot_paint = |im: &mut Self, k: usize, m: Affine| match kids.get(main + 1 + k) { Some(usvg::Node::Path(p)) => p.fill().map_or(Paint::None, |f| im.paint(f.paint(), m)), _ => Paint::None, }; - let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); - let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); - for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { - if let Some(k) = fill { - run.style.fill = server(k); + // A text split into several objects becomes a group of them, named after the element. + let whole = rest.is_empty(); + let mut skewed = false; + let mut nodes = Vec::with_capacity(rest.len() + 1); + for (mut obj, servers) in std::iter::once((obj, servers)).chain(rest) { + // The scale the type draws at becomes its size (last, below): text space grows by `grow`. + let xf = ts * obj.xf; + let grow = text::size_scale(&obj, xf); + // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user + // space; runs paint in text space. + let to_text = Affine::scale(grow) * obj.xf.inverse(); + let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); + let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); + for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { + if let Some(k) = fill { + run.style.fill = server(k); + } + if let Some(k) = stroke { + run.style.stroke = server(k); + } } - if let Some(k) = stroke { - run.style.stroke = server(k); + obj.xf = xf; + skewed |= non_scaling && !vector_effect::unscale_text(&mut obj, self.screen); + // A stroke under the characters is the object's own: it paints in the document. + let under = under.clone().map(|(mut sl, k)| { + if let Some(k) = k { + sl.paint = slot_paint(self, k, ts); + } + let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; + ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); + ap.set_contents_at(1); + ap + }); + text::fold_scale(&mut obj, grow); + let mut n = self.named(if whole { &name } else { "" }, NodeKind::Text(Box::new(obj)))?; + if let Some(ap) = under { + n.appearance = ap.into(); } + nodes.push(Arc::new(n)); } - obj.xf = xf; - if non_scaling && !vector_effect::unscale_text(&mut obj, self.screen) { + if skewed { let label = if name.is_empty() || made_up(&name) { "a text".to_string() } else { format!("text '{name}'") }; self.warn(format!("non-scaling stroke on {label} approximated: the text is stretched or skewed")); } - // A stroke under the characters is the object's own: it paints in the document. - let under = under.map(|(mut sl, k)| { - if let Some(k) = k { - sl.paint = slot_paint(self, k, ts); - } - let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; - ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); - ap.set_contents_at(1); - ap - }); - text::fold_scale(&mut obj, grow); - let mut n = self.named(&name, NodeKind::Text(Box::new(obj)))?; - if let Some(ap) = under { - n.appearance = ap.into(); + if whole { + return Some(nodes); } - Some(vec![Arc::new(n)]) + Some(vec![Arc::new(self.named(&name, NodeKind::Group { children: nodes, clip: false })?)]) } fn group_node(&mut self, g: &usvg::Group, acc: Affine) -> Option { @@ -584,7 +595,8 @@ impl Importer { if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) { return None; } - let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone(); + // A text split into several objects clips by its outlines. + let mut obj = self.slots.texts.get(self.slots.find(p)?).filter(|t| t.rest.is_empty())?.obj.clone(); obj.xf = m * self.slots.inner(p) * obj.xf; let grow = text::size_scale(&obj, obj.xf); for run in &mut obj.runs { diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index ef3934c2d6..d783c04319 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -130,6 +130,7 @@ const BIDI_NESTED: &str = "a unicode-bidi embedding inside another imported one const BIDI_TEXT_OVERRIDE: &str = "unicode-bidi override on the text imported as its paragraph direction; directional override is not supported"; /// One character of a text and the adjustments its position needs. +#[derive(Clone)] struct Cell { ch: char, style: CharStyle, @@ -178,6 +179,9 @@ pub(super) struct PendingText { pub obj: TextObject, /// For each run, the index of its fill's and stroke's `url(#…)` paint, if any. pub servers: Vec<(Option, Option)>, + /// The other point type objects of a text whose absolutely placed characters one object cannot + /// put on their x ([`split`]), after `obj` in text order, each with its runs' paint indices. + pub rest: Vec<(TextObject, Vec)>, /// Number of `url(#…)` paints (the placeholder paths after the main one, in order). pub paints: usize, /// `vector-effect="non-scaling-stroke"`: the character strokes keep their width on screen. @@ -233,7 +237,14 @@ impl TextSlots { return Some(bp.clone()); } let t = self.texts.get(i)?; - let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath()); + let mut bp = vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath(); + // The other objects of a split text, in the first one's text space. + for (o, _) in &t.rest { + let mut more = vectorcraft_text::layout(FontDb::global(), o).to_bezpath(); + more.apply_affine(t.obj.xf.inverse() * o.xf); + bp.extend(more.elements().iter().copied()); + } + let bp = Rc::new(bp); self.outlines.borrow_mut().insert(i, bp.clone()); Some(bp) } @@ -534,7 +545,10 @@ fn use_slot( shown.build(style_xml, style_t, &label, &mut found) }; let differs = |(text, paints): &(PendingText, Vec)| { - slots.texts.get(shared).is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.under != text.under) + slots + .texts + .get(shared) + .is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.rest != text.rest || old.under != text.under) || inst.paints.get(shared) != Some(paints) }; let slot = built.filter(differs).map(|(text, paints)| { @@ -1337,7 +1351,7 @@ impl Ctx { } let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); - Some((PendingText { name, obj, servers, paints: 0, non_scaling: false, under: None, marker }, Vec::new())) + Some((PendingText { name, obj, servers, rest: vec![], paints: 0, non_scaling: false, under: None, marker }, Vec::new())) } /// Read one ``: the pending text and its `url(#…)` paints. @@ -1469,6 +1483,7 @@ impl Ctx { let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); let mut breaks: Vec = vec![]; let mut para_styles: Vec = vec![]; + let mut rest = vec![]; if let Some((tp, followed)) = path { let bp = &followed.path; // Along the path: dx is extra advance, dy shifts off the path. @@ -1549,46 +1564,37 @@ impl Ctx { obj.kind = TextKind::OnPath { path: PathData::from_bezpath(&bp), start: 0.0, end: None }; obj.xf = Affine::IDENTITY; } else { - let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); - let (justify, left, starts, unplaced) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks); - if unplaced > 0 { + let whole = cells.clone(); + let mut ys = vec![]; + let (b, p, unplaced) = place(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, &mut obj, &mut ys); + (breaks, para_styles) = (b, p); + if !unplaced.is_empty() { + // One object cannot put every absolutely placed character on its x: the text becomes + // several, the first of them `obj`. + let mut pieces = split(&whole, &x, &y, &dx, &dy, &ys, &anchor_of, &pin, unplaced).into_iter(); + if let Some(first) = pieces.next() { + (obj, cells, breaks, para_styles) = (first.obj, first.cells, first.breaks, first.paras); + } + rest = pieces + .map(|mut p| { + let servers = finish(&mut p.obj, &p.cells, &p.breaks, p.paras, &pin); + (p.obj, servers) + }) + .collect(); warnings.push(format!( - "{label}: {unplaced} absolutely placed character(s) between characters of the other direction keep their place in the line" + "{label}: imported as {} point type objects in a group, since one object cannot put every character on its own x", + rest.len() + 1 )); } - obj.para.justify = justify; - obj.xf = Affine::translate((finite(left), finite(origin.y))); - // Lines anchored differently or at different x (paragraphs aligned or indented - // differently): each line's paragraph takes its alignment, and indents that put it - // where it was. - if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { - for (k, &(_, a, ax)) in starts.iter().enumerate() { - let d = finite(ax - left); - let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; - match pa.justify { - Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, - Justify::Center => pa.right_indent = -2.0 * d, - Justify::Right => pa.right_indent = -d, - _ => pa.left_indent = d, - } - let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; - para_styles.extend(std::iter::repeat_n(pa, count)); - } - } } - let (runs, servers) = assemble(&cells, &breaks).0; - obj.runs = runs; - if !para_styles.is_empty() { - obj.set_paragraph_styles(para_styles); - } - pin(&mut obj); - keep_reader_anchors(&mut obj); + let servers = finish(&mut obj, &cells, &breaks, para_styles, &pin); // The placeholder covers the text (laid out when a paint server needs its bounding box). - let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default(); + let bounds = |o: &TextObject| if paints.is_empty() { o.bounds() } else { Some(o.xf.transform_rect_bbox(measure(o).bounds)) }; + let b = rest.iter().filter_map(|(o, _)| bounds(o)).fold(bounds(&obj), |all, b| Some(all.map_or(b, |a| a.union(b)))).unwrap_or_default(); let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); let non_scaling = vector_effect::is_non_scaling(&self.css, t); - Some((PendingText { name, obj, servers, paints: paints.len(), non_scaling, under, marker }, paints)) + Some((PendingText { name, obj, servers, rest, paints: paints.len(), non_scaling, under, marker }, paints)) } } @@ -1683,13 +1689,145 @@ fn leading_tolerance(spacing: f64) -> f64 { 0.01_f64.min(spacing.abs() * 1e-3) } +/// Point type `obj` of `cells` placed by the positioning lists ([`lines`]): sets its justification +/// and transform, and returns its line breaks, its paragraph styles and the absolutely placed +/// characters kerning cannot put on their x. `ys` takes each character's line baseline and y. +#[allow(clippy::too_many_arguments)] +fn place( + cells: &mut [Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + obj: &mut TextObject, + ys: &mut Vec<(f64, f64)>, +) -> (Vec, Vec, Vec) { + let mut breaks = vec![]; + let mut para_styles = vec![]; + let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); + let (justify, left, starts, unplaced) = lines(cells, x, y, dx, dy, anchor_of, pin, origin.x, &mut breaks, ys); + obj.para.justify = justify; + obj.xf = Affine::translate((finite(left), finite(origin.y))); + // Lines anchored differently or at different x (paragraphs aligned or indented + // differently): each line's paragraph takes its alignment, and indents that put it + // where it was. + if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { + for (k, &(_, a, ax)) in starts.iter().enumerate() { + let d = finite(ax - left); + let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; + match pa.justify { + Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, + Justify::Center => pa.right_indent = -2.0 * d, + Justify::Right => pa.right_indent = -d, + _ => pa.left_indent = d, + } + let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; + para_styles.extend(std::iter::repeat_n(pa, count)); + } + } + (breaks, para_styles, unplaced) +} + +/// Gives `obj` the runs of `cells` with `breaks`, its paragraph styles and its paragraph +/// directions; returns the paint indices of its runs. +fn finish(obj: &mut TextObject, cells: &[Cell], breaks: &[Break], para_styles: Vec, pin: &dyn Fn(&mut TextObject)) -> Vec { + let (runs, servers) = assemble(cells, breaks).0; + obj.runs = runs; + if !para_styles.is_empty() { + obj.set_paragraph_styles(para_styles); + } + pin(obj); + keep_reader_anchors(obj); + servers +} + +/// One point type object of a text [`split`] into several, before [`finish`]. +struct Piece { + obj: TextObject, + cells: Vec, + breaks: Vec, + paras: Vec, +} + +/// How many times [`split`] cuts a piece before the characters kerning cannot place; a piece that +/// still has such characters is then cut before each of its chunks. +const MAX_SPLITS: usize = 3; + +/// Point type objects, in text order, that together put every absolutely placed character of +/// `cells` (before [`place`] kerned them) on its x. SVG anchors each chunk on its own and reorders +/// right-to-left characters only within a chunk (SVG 2 › Text, https://www.w3.org/TR/SVG2/text.html), +/// while one object reorders the whole +/// line: a left-to-right character drawn right before a right-to-left one has no kerning between +/// them. The text is cut before each character `unplaced` lists, and each piece placed again. `ys` +/// holds each character's line baseline and y, so that a piece keeps its characters' baselines. +#[allow(clippy::too_many_arguments)] +fn split( + cells: &[Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + ys: &[(f64, f64)], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + unplaced: Vec, +) -> Vec { + let piece = |r: Range| { + let s = r.start; + let mut cells = cells[r.clone()].to_vec(); + let (base, cur) = ys.get(s).copied().unwrap_or((0.0, 0.0)); + // The piece starts on its line's baseline, and its first character keeps its own y. + cells[0].style.baseline_shift += base - cur; + let py: Vec> = r + .clone() + .map(|i| match i - s { + 0 => Some(base), + 1 => y[i].or(Some(cur)), + _ => y[i], + }) + .collect(); + let mut pdy = dy[r.clone()].to_vec(); + pdy[0] = 0.0; + let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); + let (breaks, paras, unplaced) = place(&mut cells, &x[r.clone()], &py, &dx[r], &pdy, &|j| anchor_of(s + j), pin, &mut obj, &mut vec![]); + (Piece { obj, cells, breaks, paras }, unplaced.into_iter().map(|j| s + j).collect::>()) + }; + let mut done = vec![]; + let mut todo = vec![(0..cells.len(), unplaced, 0)]; + while let Some((range, failed, round)) = todo.pop() { + // Past the last round every chunk of the piece is a piece of its own, and so has no + // characters to place. + let mut cuts: Vec = if round < MAX_SPLITS { failed } else { (range.start + 1..range.end).filter(|&i| x[i].is_some()).collect() }; + cuts.sort_unstable(); + cuts.dedup(); + let mut from = range.start; + for to in cuts.into_iter().chain([range.end]) { + if to <= from || to > range.end { + continue; + } + match piece(from..to) { + (p, failed) if failed.is_empty() => done.push((from, p)), + (_, failed) => todo.push((from..to, failed, round + 1)), + } + from = to; + } + } + done.sort_by_key(|p| p.0); + done.into_iter().map(|p| p.1).collect() +} + +/// A line's first character, alignment (as for [`justify_of`]) and anchor x. +type LineStart = (usize, f64, f64); + /// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the /// justification, the x of the first line's left (or anchor) edge and each line's first /// character, alignment (as for [`justify_of`]) and anchor x. `anchor_of` gives where the chunk /// starting at a character sits on its anchor, and `pin` sets the paragraph directions of the /// text ([`pin_direction`]). When characters are placed on their own, every line is left-aligned -/// and its anchor x is its left edge. Also returns how many absolutely placed characters kerning -/// cannot put on their x. +/// and its anchor x is its left edge. Also returns the absolutely placed characters kerning cannot +/// put on their x. `ys` takes each character's line baseline and y. #[allow(clippy::too_many_arguments)] fn lines( cells: &mut [Cell], @@ -1701,10 +1839,13 @@ fn lines( pin: &dyn Fn(&mut TextObject), x0: f64, breaks: &mut Vec, -) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) { + ys: &mut Vec<(f64, f64)>, +) -> (Justify, f64, Vec, Vec) { let n = cells.len(); let y0 = y[0].unwrap_or(0.0) + dy[0]; let (mut base, mut cur) = (y0, y0); + ys.clear(); + ys.push((y0, y0)); // Line starts (first character, anchor x) and absolutely placed characters (index, x). let mut lines = vec![(0, x0)]; let mut targets: Vec<(usize, f64)> = vec![]; @@ -1723,9 +1864,11 @@ fn lines( breaks.push(Break { at: i, count: count as usize, leading: gap / count }); lines.push((i, ax + dx[i])); (base, cur) = (ny, ny); + ys.push((base, cur)); continue; } cur = ny; + ys.push((base, cur)); match x[i] { Some(ax) => targets.push((i, ax + dx[i])), None => cells[i - 1].kern += dx[i], @@ -1744,7 +1887,7 @@ fn lines( } if targets.is_empty() { let starts = lines.iter().map(|&(s, lx)| (s, anchor_of(s), lx)).collect(); - return (justify_of(anchor_of(0)), x0, starts, 0); + return (justify_of(anchor_of(0)), x0, starts, vec![]); } // Absolutely placed characters: lay the text out left-aligned and kern each one onto its x. // SVG anchors every absolutely placed chunk on its own, so a chunk not anchored at its left @@ -1774,7 +1917,7 @@ fn lines( let mut wants: Vec<(usize, f64)> = vec![]; // Absolutely placed characters drawn right next to a placed neighbor with no kerning between // them (a left-to-right character between right-to-left ones): they stay where the layout puts them. - let mut unplaced = 0; + let mut unplaced = vec![]; // Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until // every character sits on its x. for round in 0..4 { @@ -1811,7 +1954,7 @@ fn lines( // character's horizontal scale, so each correction is divided by it. let mut worst = 0.0f64; let mut from = 0; - unplaced = 0; + unplaced.clear(); while from < wants.len() { let l = line_of(wants[from].0); let to = from + wants[from..].partition_point(|&(i, _)| line_of(i) == l); @@ -1831,35 +1974,35 @@ fn lines( .filter_map(|&(i, _)| (lines[l].0..i).rev().find_map(|j| pens[j]).map(|k| (2 * k.rank + if k.rtl { 1 } else { 3 }, i - 1))) .collect(); cuts.sort_unstable(); - let mut points: Vec<(usize, f64, f64)> = - on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want))).collect(); + let mut points: Vec<(usize, f64, f64, usize)> = + on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want, i))).collect(); points.sort_by_key(|p| p.0); // The character kerned at the first cut between places `a` and `b`. let cut = |a: usize, b: usize| cuts.get(cuts.partition_point(|c| c.0 <= a)).filter(|c| c.0 < b).map(|c| c.1); let split = points.partition_point(|p| p.0 < home); // Drawn right of the line's first chunk: kerning moves the character away from it. let (mut prev, mut moved) = (home, 0.0); - for &(place, start, want) in &points[split..] { + for &(place, start, want, i) in &points[split..] { if let Some(k) = cut(prev, place) { let d = want - (start - p0 + moved); cells[k].kern += d / spacing_scale(&cells[k].style, false); moved += d; worst = worst.max(d.abs()); } else { - unplaced += 1; + unplaced.push(i); } prev = place; } // Drawn left of it: kerning moves the chunk (and what lies between) away from the character. (prev, moved) = (home, 0.0); - for &(place, start, want) in points[..split].iter().rev() { + for &(place, start, want, i) in points[..split].iter().rev() { if let Some(k) = cut(place, prev) { let d = start - p0 - moved - want; cells[k].kern += d / spacing_scale(&cells[k].style, false); moved += d; worst = worst.max(d.abs()); } else { - unplaced += 1; + unplaced.push(i); } prev = place; } @@ -2064,7 +2207,8 @@ fn pens(lay: &TextLayout, bytes: &[usize], cells: &[Cell]) -> Vec> { .collect() } -type Key = (Option, Option); +/// The indices of a run's fill and stroke `url(#…)` paints. +pub(super) type Key = (Option, Option); type Runs = (Vec, Vec); /// Runs (and their paint indices) from the characters, with `breaks` inserted; also the byte offset diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs index bb92802e60..4cbcc9a812 100644 --- a/crates/svg/tests/it/clip_text.rs +++ b/crates/svg/tests/it/clip_text.rs @@ -125,6 +125,20 @@ fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines( assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); } +#[test] +fn a_text_imported_as_several_objects_clips_by_all_their_outlines() { + // One object cannot put ג on its x, so the text is several objects; the clip outlines all of them. + let d = open( + r##"אbג + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let b = clip_bounds(clip); + // ג ends at 220, the first object at 160. + assert!(b.x1 > 200.0 && b.x1 <= 220.0 + 1e-6 && b.x0 < 100.0, "{b:?}"); +} + #[test] fn tspans_and_type_on_a_path_clip_too() { let d = open( diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index fa91f8d162..c8a1cfd4ed 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -974,7 +974,7 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { vec![(0..2, 20.0), (3..4, 100.0), (4..5, 160.0)], ), ]; - let unplaced = |w: &[String]| w.iter().any(|w| w.contains("absolutely placed")); + let unplaced = |w: &[String]| w.iter().any(|w| w.contains("point type objects")); for (body, share, chunks) in cases { let (d, w) = import_with_report(&svg(&body)).unwrap(); assert!(!unplaced(&w), "{body}: {w:?}"); @@ -988,12 +988,82 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { assert!(close(left, want, 0.05), "{body}: the chunk {bytes:?} spans {left}..{right}, so it does not start at {want}"); } } - // A left-to-right character between right-to-left ones is drawn right next to the one after - // it, with no kerning between them: that one keeps its place in the line, and a warning says so. - let (d, w) = import_with_report(&svg(r#"אbג"#)).unwrap(); - assert!(unplaced(&w), "{w:?}"); - let (left, right) = chunk_edges(only_text(&d), 2..3); - assert!(close(right, 160.0, 0.05), "b spans {left}..{right}"); +} + +/// The document-space edges of character `ch`, in whichever text of `d` holds it (as +/// [`chunk_edges`] measures them), and the y it is drawn at (its baseline moved by its baseline +/// shift). +fn char_edges(d: &Document, ch: char) -> (f64, f64, f64) { + let t = texts(d).into_iter().find(|t| t.plain_text().contains(ch)).unwrap_or_else(|| panic!("no text holds {ch}")); + let at = t.plain_text().find(ch).unwrap(); + let (left, right) = chunk_edges(t, at..at + ch.len_utf8()); + let shift = t.runs.iter().find(|r| r.text.contains(ch)).unwrap().style.baseline_shift; + let y = layout(FontDb::global(), t).glyphs.iter().find(|g| g.byte == at).map(|g| (t.xf * g.origin).y).unwrap() - shift; + (left, right, y) +} + +/// SVG 2 › Text (https://www.w3.org/TR/SVG2/text.html): each absolute position starts a chunk, +/// and bidi reordering happens only within a chunk. A left-to-right character drawn right before a +/// right-to-left one has no kerning between them in one text object, so such a text imports as a +/// group of point type objects, each character on its own x. +#[test] +fn absolutely_placed_characters_one_object_cannot_place_import_as_a_group() { + // (markup, the characters of its objects in order, each character with the x its right edge + // sits on and its baseline) + type Case = (&'static str, &'static str, Vec<(char, f64, f64)>); + let cases: Vec = vec![ + ( + r#"אbג"#, + "אbג", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0)], + ), + ( + r#"אbגd"#, + "אbגd", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0), ('d', 280.0, 80.0)], + ), + // x values that decrease. + ( + r#"אbג"#, + "אbג", + vec![('א', 220.0, 80.0), ('b', 160.0, 80.0), ('ג', 100.0, 80.0)], + ), + // On a second line, and with a baseline of its own. + ( + r#"אבגbד"#, + "אבגbד", + vec![('א', 40.0, 40.0), ('ג', 100.0, 80.0), ('b', 160.0, 80.0), ('ד', 220.0, 90.0)], + ), + ]; + for (body, text, chars) in cases { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(w.iter().any(|w| w.contains("point type objects in a group")), "{body}: {w:?}"); + let top = d.layers[0].children().unwrap(); + assert_eq!(top.len(), 1, "{body}: {top:?}"); + assert_eq!(top[0].name.as_deref(), Some("t"), "{body}: the group takes the element's id"); + let NodeKind::Group { children, clip: false } = &top[0].kind else { panic!("{body}: {:?}", top[0].kind) }; + assert!(children.len() > 1 && children.iter().all(|c| matches!(c.kind, NodeKind::Text(_))), "{body}: {children:?}"); + let all: String = texts(&d).iter().map(|t| t.plain_text().replace('\n', "")).collect(); + assert_eq!(all, text, "{body}: every character once, in order"); + for (ch, x, y) in chars { + let (left, right, base) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + assert!(close(base, y, 1e-6), "{body}: {ch} sits on {base}, not {y}"); + } + } + // Placed characters one object can place stay one object, also when their x values decrease. + for (body, chars) in [ + (r#"אbc"#, [('א', 100.0), ('b', 160.0), ('c', 220.0)]), + (r#"אבג"#, [('א', 220.0), ('ב', 160.0), ('ג', 100.0)]), + ] { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(!w.iter().any(|w| w.contains("point type objects")), "{body}: {w:?}"); + only_text(&d); + for (ch, x) in chars { + let (left, right, _) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + } + } } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..520ec4fc09 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1783,7 +1783,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A gap between glyphs of two sizes is measured against the smaller one, so a word set beside a much larger one with no space glyph between them (a browser's margin between two sizes, as in `≤ 4` and a small `hours`) keeps its word space (#3623). SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `