From 1533f2b8218917ef212d5d9a0301eb2a5ac0f8eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:46:15 -0800 Subject: [PATCH 01/50] i18n: the justification order error is translated in every complete catalog The error that text.setFormat and the paragraph style commands give when a justification setting's Minimum, Desired and Maximum are out of order had a message row only in Hindi and Swedish, so the other complete-message languages showed it in English. Each of them now has a row, built from the catalog's own translation of the dialog's sentence. The Catalan sentence read as "nor the desired maximum" and now says that Desired must not exceed Maximum. The Hindi label for Desired, the sentence and its message row now use the word for desired. --- crates/ui-egui/src/i18n/ca.tsv | 3 ++- crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 6 +++--- crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 16 ++++++++++++++++ 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 + 22 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..ee2a80be61 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2565,7 +2565,8 @@ digits Malayalam Malaiàlam Minimal Mínim Minimize Minimitza Minimum Mínim - Minimum must not exceed Desired, nor Desired Maximum. El mínim no pot superar el desitjat ni el màxim desitjat. + Minimum must not exceed Desired, nor Desired Maximum. El mínim no pot superar el desitjat, ni el desitjat el màxim. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: el mínim no pot superar el desitjat, ni el desitjat el màxim Minus Back Resta al darrere Minus Front Resta al davant Mirror Reflexa diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..cd3ef13daa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6201,6 +6201,7 @@ mark-style Japanese Japonské Single Word Justification: Zarovnání jednoho slova: Full Justify Zarovnat do bloku Minimum must not exceed Desired, nor Desired Maximum. Minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum Justification Zarovnání do bloku Add filters from the list above Přidejte filtry ze seznamu výše Add to Stack Přidat na zásobník diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..2ec37ba36f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5789,6 +5789,7 @@ effect Soft Weich Single Word Justification: Ausrichtung einzelner Wörter: Full Justify Blocksatz Minimum must not exceed Desired, nor Desired Maximum. Das Minimum darf den optimalen Wert nicht übersteigen, der optimale Wert nicht das Maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Das Minimum darf den optimalen Wert nicht übersteigen, der optimale Wert nicht das Maximum Minimum Minimum Justification Abstände Add filters from the list above Filter aus der Liste oben hinzufügen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..d23cc73278 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6152,6 +6152,7 @@ effect Points Σημεία Single Word Justification: Στοίχιση μεμονωμένης λέξης: Full Justify Στοίχιση και στα δύο άκρα Minimum must not exceed Desired, nor Desired Maximum. Το ελάχιστο δεν πρέπει να υπερβαίνει το επιθυμητό, ούτε το επιθυμητό το μέγιστο. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: το ελάχιστο δεν πρέπει να υπερβαίνει το επιθυμητό, ούτε το επιθυμητό το μέγιστο Justification Πλήρης στοίχιση Add filters from the list above Προσθέστε φίλτρα από τη λίστα παραπάνω Add to Stack Προσθήκη στη στοίβα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..4f8eeab026 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6143,6 +6143,7 @@ mark-style Japanese Japonesas Single Word Justification: Justificación de una sola palabra: Full Justify Justificar completamente Minimum must not exceed Desired, nor Desired Maximum. El mínimo no puede superar el deseado, ni el deseado el máximo. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: el mínimo no puede superar el deseado, ni el deseado el máximo Justification Justificación Add filters from the list above Añada filtros de la lista de arriba Add to Stack Añadir a la pila diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..cf38cf328d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6164,6 +6164,7 @@ mark-style Japanese Japanilainen Single Word Justification: Yksittäisen sanan tasaus: Full Justify Täysi tasaus Minimum must not exceed Desired, nor Desired Maximum. Minimi ei saa ylittää haluttua arvoa eikä haluttu arvo maksimia. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimi ei saa ylittää haluttua arvoa eikä haluttu arvo maksimia Justification Tasaus Add filters from the list above Lisää suodattimia yllä olevasta luettelosta Add to Stack Lisää pinoon diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..2e6e8232f7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6196,6 +6196,7 @@ theme Appearance Apparence Single Word Justification: Justification d’un mot isolé : Full Justify Justification complète Minimum must not exceed Desired, nor Desired Maximum. Le minimum ne doit pas dépasser la valeur optimale, ni la valeur optimale le maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}` : le minimum ne doit pas dépasser la valeur optimale, ni la valeur optimale le maximum Justification Justification Add filters from the list above Ajoutez des filtres à partir de la liste ci-dessus Add to Stack Ajouter à la pile diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..cc4e0f1504 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1306,7 +1306,7 @@ antiAlias Sharp शार्प Description: विवरण: Deselect डीसिलेक्ट करें Design… डिजाइन… - Desired देसी + Desired वांछित Destination Folder: गंतव्य फ़ोल्डर: Destination: गंतव्य: Detail डिटेल @@ -2802,7 +2802,7 @@ antiAlias Sharp शार्प Minimize छोटा करें Minimum न्यूनतम Minimum angle न्यूनतम कोण - Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम से अधिक नहीं होना चाहिए, न ही अधिकतम होना चाहिए। + Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम मान वांछित मान से अधिक नहीं होना चाहिए, और न ही वांछित मान अधिकतम मान से। Minimum: न्यूनतम: Minus Back पीछे वाला घटाएँ Minus Front सामने वाला घटाएँ @@ -5901,7 +5901,7 @@ antiAlias Sharp शार्प @msg `{name}` is no recovery entry name `{name}` कोई वसूली प्रविष्टि नाम नहीं है @msg `{name}` isn't a colour swatch `{name}` is not a color swatch @msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` अपने खुद के प्रकार (रंग, ग्रेडिएंट या पैटर्न) का एक रंग लेता है। -@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम इच्छा से अधिक नहीं होना चाहिए, न ही इच्छा अधिकतम +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम मान वांछित मान से अधिक नहीं होना चाहिए, और न ही वांछित मान अधिकतम मान से @msg `{other}` doesn't trace an image `{other}` एक इमेज का पता नहीं लगा @msg `{path}` must be a bool or an object of bools `{path}` एक bool होना चाहिए या एक ऑब्जेक्ट होना चाहिए। @msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` एक रंग नहीं है (#rrggbb या एक पूर्व निर्धारित नाम) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..79a4a46d44 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6184,6 +6184,7 @@ imageTrace Outline Körvonal Single Word Justification: Egyetlen szó igazítása: Full Justify Teljes sorkizárás Minimum must not exceed Desired, nor Desired Maximum. A minimum nem haladhatja meg a kívánt értéket, sem a kívánt érték a maximumot. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: a minimum nem haladhatja meg a kívánt értéket, sem a kívánt érték a maximumot Justification Sorkizárás Add filters from the list above Adjon hozzá szűrőket a fenti listából Add to Stack Hozzáadás a veremhez diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..7616fbcdcc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5823,6 +5823,7 @@ lighting Light Luce Single Word Justification: Giustificazione parola singola: Full Justify Giustificazione completa Minimum must not exceed Desired, nor Desired Maximum. Il minimo non può superare il valore desiderato, né il desiderato il massimo. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: il minimo non può superare il valore desiderato, né il desiderato il massimo Minimum Minimo Justification Giustificazione Add filters from the list above Aggiungi filtri dall'elenco sopra diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..e8e1304bc6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5866,6 +5866,7 @@ lighting Light ライト Single Word Justification: 単語のみの行の揃え: Full Justify 両端揃え Minimum must not exceed Desired, nor Desired Maximum. 最小値は最適値を、最適値は最大値を超えることはできません。 +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: 最小値は最適値を、最適値は最大値を超えることはできません Minimum 最小 Justification 文字組み Add filters from the list above 上のリストからフィルターを追加 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..298e879fc2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6104,6 +6104,7 @@ imageTrace Outline კონტური Letter Spacing: ასოებს შორის დაშორება: Word Spacing: სიტყვებს შორის დაშორება: Minimum must not exceed Desired, nor Desired Maximum. მინიმალური არ უნდა აღემატებოდეს სასურველს, ხოლო სასურველი — მაქსიმალურს. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: მინიმალური არ უნდა აღემატებოდეს სასურველს, ხოლო სასურველი — მაქსიმალურს Single Word Justification: ერთი სიტყვის სწორება: Apply {name} სტილის „{name}“ გამოყენება Redefine {name} სტილის „{name}“ ხელახლა განსაზღვრა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..fa8242ed4d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5784,6 +5784,7 @@ lighting Light 광원 Single Word Justification: 단일 단어 정렬: Full Justify 강제 양쪽 정렬 Minimum must not exceed Desired, nor Desired Maximum. 최소값은 희망값을, 희망값은 최대값을 넘을 수 없습니다. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: 최소값은 희망값을, 희망값은 최대값을 넘을 수 없습니다 Minimum 최소 Justification 양끝 맞춤 Add filters from the list above 위 목록에서 필터 추가 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..42bb50c398 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6055,6 +6055,7 @@ mark-style Japanese Japońskie Single Word Justification: Justowanie pojedynczego wyrazu: Full Justify Pełne justowanie Minimum must not exceed Desired, nor Desired Maximum. Minimum nie może przekraczać wartości optymalnej, a wartość optymalna maksimum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimum nie może przekraczać wartości optymalnej, a wartość optymalna maksimum Justification Justowanie Add filters from the list above Dodaj filtry z listy powyżej Add to Stack Dodaj do stosu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..2c04b76271 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6116,6 +6116,7 @@ mark-style Japanese Japonesas Single Word Justification: Justificação de Palavra Única: Full Justify Justificação Completa Minimum must not exceed Desired, nor Desired Maximum. O mínimo não pode passar do desejado, nem o desejado do máximo. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: o mínimo não pode passar do desejado, nem o desejado do máximo Justification Justificação Add filters from the list above Adicione filtros da lista acima Add to Stack Adicionar à Pilha diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..37f11f9a0e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5809,6 +5809,7 @@ lighting Light Свет Single Word Justification: Выключка одного слова: Full Justify Полная выключка Minimum must not exceed Desired, nor Desired Maximum. Минимум не может превышать желательное значение, а желательное — максимум. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: минимум не может превышать желательное значение, а желательное — максимум Minimum Минимум Justification Выключка Add filters from the list above Добавьте фильтры из списка выше diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..bc62fceaef 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1739,6 +1739,22 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// The error that `text.setFormat` and the paragraph style commands give when a justification +/// setting's Minimum, Desired and Maximum are out of order is translated in every +/// complete-message language, with the setting's name kept. +#[test] +fn justification_order_error_translates_with_the_setting_name() { + for name in ["wordSpacing", "justification.glyph_scaling"] { + let error = format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &error); + assert!(shown != error && !shown.contains("Desired"), "{code}: {shown}"); + assert!(shown.contains(&format!("`{name}`")), "{code}: {shown}"); + } + } +} + #[test] fn package_status_message_templates_parse() { let c = Catalog::parse(concat!( diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..6a6d12d460 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2966,6 +2966,7 @@ digits Malayalam Malayalam Letter Spacing: Harf Boşluğu: Lights Işıklar Minimum must not exceed Desired, nor Desired Maximum. Minimum, İstenen'i; İstenen ise Maksimum'u aşmamalıdır. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum, İstenen'i; İstenen ise Maksimum'u aşmamalıdır Select by Color Renge Göre Seç Set History Limit… Geçmiş Sınırını Ayarla… Single Word Justification: Tek Sözcük Yaslama: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..fe8299bd50 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5803,6 +5803,7 @@ lighting Light Світло Single Word Justification: Вирівнювання одного слова: Full Justify Повне вирівнювання Minimum must not exceed Desired, nor Desired Maximum. Мінімум не може перевищувати бажане значення, а бажане — максимум. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: мінімум не може перевищувати бажане значення, а бажане — максимум Minimum Мінімум Justification Вирівнювання за шириною Add filters from the list above Додайте фільтри зі списку вище diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..f27f139875 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5804,6 +5804,7 @@ theme Appearance Giao diện Single Word Justification: Căn đều một từ: Full Justify Căn đều hoàn toàn Minimum must not exceed Desired, nor Desired Maximum. Giá trị tối thiểu không được vượt quá giá trị mong muốn, và giá trị mong muốn không được vượt quá tối đa. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: giá trị tối thiểu không được vượt quá giá trị mong muốn, và giá trị mong muốn không được vượt quá tối đa Minimum Tối thiểu Justification Căn đều Add filters from the list above Thêm bộ lọc từ danh sách phía trên diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..e1253a8e31 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6037,6 +6037,7 @@ lighting Light 光源 Single Word Justification: 单字对齐: Full Justify 全部强制双齐 Minimum must not exceed Desired, nor Desired Maximum. 最小值不能超过所需值,所需值不能超过最大值。 +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`:最小值不能超过所需值,所需值不能超过最大值 Minimum 最小值 Justification 对齐设置 Add filters from the list above 从上方列表添加滤镜 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..2d1981d28c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5834,6 +5834,7 @@ lighting Light 光源 Single Word Justification: 單字對齊: Full Justify 全部強迫齊行 Minimum must not exceed Desired, nor Desired Maximum. 最小值不可超過所需值,所需值不可超過最大值。 +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`:最小值不可超過所需值,所需值不可超過最大值 Minimum 最小值 Justification 對齊設定 Add filters from the list above 從上方清單新增濾鏡 From 4c5b63c28aebb4a036f763ce345404146d74e8dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:49:15 -0800 Subject: [PATCH 02/50] i18n: Dutch row for the justification order message --- crates/ui-egui/src/i18n/nl.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 40facfda42..fb3af3a18e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6484,6 +6484,7 @@ swatch Bright Violet Felviolet Single Word Justification: Uitvullen van één woord: Full Justify Volledig uitvullen Minimum must not exceed Desired, nor Desired Maximum. Minimum mag niet groter zijn dan Gewenst, en Gewenst niet groter dan Maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum mag niet groter zijn dan Gewenst, en Gewenst niet groter dan Maximum Justification Uitvullen Add filters from the list above Voeg filters toe uit de lijst hierboven Add to Stack Toevoegen aan stapel From 5002b6ac8c45e08c8548fb744f132363cb59e4b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 16:40:54 -0800 Subject: [PATCH 03/50] Eraser: path.eraseRegion refuses an angle or roundness outside its range path.eraseRegion clamped roundness to 1-100 and used any finite angle as given, so a stroke with roundness 400 or 0 erased like one with 100 or 1, an angle of 540 erased like 180, and the call did not report the bad value. It now refuses an angle outside -180 to 180 degrees and a roundness outside 1 to 100% with an error naming the key and the range, and the document does not change. A key left out or null still takes its default (0 degrees, 100%). path.split refuses a t outside 0 to 1 the same way. Before, such a t cut at the segment's end anchor with `segment` and was ignored with `anchor`. The Eraser's ranges match its Tool Options fields and are VectorCraft's own values. The help page gives no range for Angle or Roundness: https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html Adds @msg rows for the two Eraser messages to every complete catalog. --- crates/engine/src/cmd/draw2/commands.rs | 4 +- crates/engine/src/cmd/draw2/cut.rs | 11 +++- crates/engine/src/tests/draw2.rs | 73 ++++++++++++++++++++++++- crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tests.rs | 30 ++++++++++ crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 6 ++ docs/target-app-parity.md | 1 + 29 files changed, 165 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 53949fdaf0..9009c7ec9a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -74,7 +74,7 @@ pub fn specs() -> Vec { "Split Path", [], None, - "{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}", + "{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes", has_doc, split ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. An angle or roundness outside its range is refused with an error, and nothing changes", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 645c184b14..9ff3601a61 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -181,6 +181,9 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) { return Err(bad(C, "invalid t")); } + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } let ids = s.edit("Split Path", |d, sel| { let path = path_mut(d, id)?; let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?; @@ -277,13 +280,19 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "size must be positive")); } let angle = number_or(p, "angle", 0.0, C)?; + if !(-180.0..=180.0).contains(&angle) { + return Err(bad(C, "`angle` must be from -180 to 180 degrees")); + } let roundness = number_or(p, "roundness", 100.0, C)?; + if !(1.0..=100.0).contains(&roundness) { + return Err(bad(C, "`roundness` must be from 1 to 100%")); + } let pressure = size_pressure(p, &samples, C)?; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); let r = size / 2.0; // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0)); - let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0; + let short = narrowest * roundness / 100.0; let st = s.doc()?; // A point is under the tip when, with the tip squashed back into a circle, it is within the // circle's radius of the squashed drag. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 79dbd366f6..3128dc32fe 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1313,9 +1313,76 @@ fn the_eraser_tip_takes_its_angle_and_roundness() { // At 45°, half axes 10 and 2.5: the band is 2·√((10² + 2.5²) / 2), about 14.58 pt, and the // chord 2 / √(0.5 / 10² + 0.5 / 2.5²), about 6.86 pt. close(erase(json!({"angle": 45, "roundness": 25})), 2.0 * ((100.0f64 + 6.25) / 2.0).sqrt(), 2.0 / (0.5f64 / 100.0 + 0.5 / 6.25).sqrt()); - // A roundness past 100 is kept to 100, and one below 1 to 1. - close(erase(json!({"angle": 90, "roundness": 400})), 20.0, 20.0); - close(erase(json!({"angle": 90, "roundness": 0})), 0.2, 0.2); + // The ends of the Roundness range: 100% is round, and 1% leaves a tip 0.2 pt across. + close(erase(json!({"angle": 90, "roundness": 100})), 20.0, 20.0); + close(erase(json!({"angle": 90, "roundness": 1})), 0.2, 0.2); +} + +/// The Eraser refuses an `angle` outside -180 to 180 degrees and a `roundness` outside 1 to 100%, +/// naming the key and the range, and erases nothing. The ends of each range erase, and a key left +/// out or null takes its default: 0 degrees and 100%. +#[test] +fn the_eraser_refuses_an_angle_or_roundness_outside_its_range() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + let stroke = json!({"points": [[90, 150], [210, 150]], "size": 10}); + for angle in [json!(-181), json!(-180.001), json!(180.001), json!(200), json!(1e300), json!(-1e300)] { + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": angle})), "`angle` must be from -180 to 180 degrees"); + } + for roundness in [json!(0), json!(0.999), json!(-25), json!(100.001), json!(400), json!(1e300)] { + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"roundness": roundness})), "`roundness` must be from 1 to 100%"); + } + // A key out of its range is refused when the other key is in range. + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 90, "roundness": 400})), "`roundness` must be from 1 to 100%"); + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 540, "roundness": 25})), "`angle` must be from -180 to 180 degrees"); + // The pieces a stroke leaves, undone again. + let mut erased = |tip: serde_json::Value| { + let r = s.execute("path.eraseRegion", &with(&stroke, tip.clone())).unwrap(); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(2), "{tip}: the stroke cuts the square in two: {r}"); + let pieces: Vec = paths(&s).into_iter().map(|p| p.1).collect(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + pieces + }; + // Both ends of each range are inside it. + for tip in [json!({"angle": -180}), json!({"angle": 180}), json!({"angle": 90, "roundness": 1}), json!({"roundness": 100})] { + erased(tip); + } + let default = erased(json!({})); + assert_eq!(erased(json!({"angle": 0, "roundness": 100})), default, "left out, the tip is round at 0 degrees"); + assert_eq!(erased(json!({"angle": null, "roundness": null})), default, "null is read as a key left out"); + assert!(erased(json!({"angle": 0, "roundness": 25})) != default, "a quarter-round level tip erases a narrower band"); +} + +/// The Scissors command refuses a `t` outside 0 to 1 instead of cutting at the nearer end of the +/// segment, with or without an `anchor` beside it; 0 and 1 cut at the segment's two anchors. +#[test] +fn scissors_refuse_a_t_outside_the_segment() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let before = path(&s, id); + for t in [json!(-0.1), json!(-1e-9), json!(1.000001), json!(1.1), json!(1e300), json!(-1e300)] { + refuses_with(&mut s, "path.split", &json!({"id": id.0, "segment": 0, "t": t}), "`t` must be from 0 to 1"); + refuses_with(&mut s, "path.split", &json!({"id": id.0, "anchor": 1, "t": t}), "`t` must be from 0 to 1"); + } + // 0 opens the square at the segment's first anchor, 1 at its second, and 0.5 at a new anchor + // between them. + for (t, anchors, start) in [ + (json!(0), 5, before.subpaths[0].anchors[0].p), + (json!(1), 5, before.subpaths[0].anchors[1].p), + (json!(0.5), 6, before.subpaths[0].anchors[0].p.midpoint(before.subpaths[0].anchors[1].p)), + ] { + s.execute("path.split", &json!({"id": id.0, "segment": 0, "t": t})).unwrap(); + let cut = path(&s, id); + assert!(!cut.subpaths[0].closed && cut.subpaths[0].anchors.len() == anchors, "t {t}: {cut:?}"); + assert!((cut.subpaths[0].anchors[0].p - start).hypot() < 1e-9, "t {t}: the cut starts at {:?}", cut.subpaths[0].anchors[0].p); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), before, "t {t}: undo"); + } + // Left out, `t` is 0.5. + s.execute("path.split", &json!({"id": id.0, "segment": 0})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 6); } #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9dfc5458b5..556b4767d3 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7457,6 +7457,8 @@ breakText Glyphs Glifs @msg No bridge of this width fits across the selected art Cap pont d’aquesta amplada no cap a la il·lustració seleccionada @msg Some islands could not be joined to the area around the art Algunes illes no s’han pogut unir a l’àrea que envolta la il·lustració @msg `width` must be from {lo} to {hi} pt `width` ha d’estar entre {lo} i {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` ha d’estar entre -180 i 180 graus +@msg `roundness` must be from 1 to 100% `roundness` ha d’estar entre 1 i 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` ha de ser un nombre enter d’1 a {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caixa i línies de pelat… Weed Box and Lines Caixa i línies de pelat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index edaad350a0..6df7fbb0ae 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7476,6 +7476,8 @@ breakText Glyphs Glyfy @msg No bridge of this width fits across the selected art Přes vybranou kresbu se nevejde žádný můstek této šířky @msg Some islands could not be joined to the area around the art Některé ostrůvky nebylo možné připojit k oblasti kolem kresby @msg `width` must be from {lo} to {hi} pt `width` musí být od {lo} do {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` musí být od -180 do 180 stupňů +@msg `roundness` must be from 1 to 100% `roundness` musí být od 1 do 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musí být celé číslo od 1 do {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Rámeček a linie pro vybírání… Weed Box and Lines Rámeček a linie pro vybírání diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index cd6a428631..c741feed21 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7072,6 +7072,8 @@ breakText Glyphs Glyphen @msg No bridge of this width fits across the selected art Kein Steg dieser Breite passt über das ausgewählte Bildmaterial @msg Some islands could not be joined to the area around the art Einige Inseln konnten nicht mit der Fläche um das Bildmaterial verbunden werden @msg `width` must be from {lo} to {hi} pt `width` muss zwischen {lo} und {hi} pt liegen +@msg `angle` must be from -180 to 180 degrees `angle` muss zwischen -180 und 180 Grad liegen +@msg `roundness` must be from 1 to 100% `roundness` muss zwischen 1 und 100 % liegen @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` muss eine ganze Zahl von 1 bis {MAX_BRIDGES_PER_ISLAND} sein Weed Box and Lines… Entgitterrahmen und -linien… Weed Box and Lines Entgitterrahmen und -linien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index fc76658c72..c200824ea6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7429,6 +7429,8 @@ breakText Glyphs Γλύφοι @msg No bridge of this width fits across the selected art Καμία γέφυρα αυτού του πλάτους δεν χωράει στο επιλεγμένο γραφικό @msg Some islands could not be joined to the area around the art Ορισμένες νησίδες δεν ήταν δυνατό να συνδεθούν με την περιοχή γύρω από το γραφικό @msg `width` must be from {lo} to {hi} pt Το `width` πρέπει να είναι από {lo} έως {hi} pt +@msg `angle` must be from -180 to 180 degrees Το `angle` πρέπει να είναι από -180 έως 180 μοίρες +@msg `roundness` must be from 1 to 100% Το `roundness` πρέπει να είναι από 1 έως 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} Το `count` πρέπει να είναι ακέραιος από 1 έως {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Πλαίσιο και γραμμές αφαίρεσης περισσευμάτων… Weed Box and Lines Πλαίσιο και γραμμές αφαίρεσης περισσευμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c7c9c8bc1e..5e21038c6f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7420,6 +7420,8 @@ breakText Glyphs Glifos @msg No bridge of this width fits across the selected art Ningún puente de este ancho cabe en la ilustración seleccionada @msg Some islands could not be joined to the area around the art Algunas islas no se pudieron unir al área que rodea la ilustración @msg `width` must be from {lo} to {hi} pt `width` debe estar entre {lo} y {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` debe estar entre -180 y 180 grados +@msg `roundness` must be from 1 to 100% `roundness` debe estar entre 1 y 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` debe ser un número entero entre 1 y {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caja y líneas de pelado… Weed Box and Lines Caja y líneas de pelado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 126e7854f9..1fdf0238d2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7511,6 +7511,8 @@ breakText Glyphs Merkit @msg No bridge of this width fits across the selected art Näin leveä silta ei mahdu valitun grafiikan poikki @msg Some islands could not be joined to the area around the art Joitakin saarekkeita ei voitu yhdistää grafiikkaa ympäröivään alueeseen @msg `width` must be from {lo} to {hi} pt `width`-arvon on oltava {lo}–{hi} pt +@msg `angle` must be from -180 to 180 degrees `angle`-arvon on oltava -180–180 astetta +@msg `roundness` must be from 1 to 100% `roundness`-arvon on oltava 1–100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` on oltava kokonaisluku 1–{MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Karsintakehys ja -viivat… Weed Box and Lines Karsintakehys ja -viivat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3941bf0497..dc470479d9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7471,6 +7471,8 @@ breakText Glyphs Glyphes @msg No bridge of this width fits across the selected art Aucun pont de cette largeur ne tient en travers de l’illustration sélectionnée @msg Some islands could not be joined to the area around the art Certains îlots n’ont pas pu être reliés à la zone autour de l’illustration @msg `width` must be from {lo} to {hi} pt `width` doit être compris entre {lo} et {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` doit être compris entre -180 et 180 degrés +@msg `roundness` must be from 1 to 100% `roundness` doit être compris entre 1 et 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` doit être un nombre entier compris entre 1 et {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Cadre et lignes d’échenillage… Weed Box and Lines Cadre et lignes d’échenillage diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index bf2f223fc0..6223c46850 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8868,6 +8868,8 @@ theme Appearance अपीयरेंस @msg No bridge of this width fits across the selected art इस चौड़ाई का कोई ब्रिज चुने गए आर्टवर्क के पार नहीं आता @msg Some islands could not be joined to the area around the art कुछ आइलैंड आर्टवर्क के आसपास के क्षेत्र से नहीं जोड़े जा सके @msg `width` must be from {lo} to {hi} pt `width` {lo} से {hi} pt तक होना चाहिए +@msg `angle` must be from -180 to 180 degrees `angle` -180 से 180 डिग्री तक होना चाहिए +@msg `roundness` must be from 1 to 100% `roundness` 1 से 100% तक होना चाहिए @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 से {MAX_BRIDGES_PER_ISLAND} तक पूरी संख्या होना चाहिए Weed Box and Lines… वीड बॉक्स और लाइनें… Weed Box and Lines वीड बॉक्स और लाइनें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 969b923a1c..18a6aa854c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7460,6 +7460,8 @@ breakText Glyphs Glifák @msg No bridge of this width fits across the selected art Ilyen széles híd nem fér el a kijelölt grafikán @msg Some islands could not be joined to the area around the art Egyes szigeteket nem sikerült összekötni a grafikát körülvevő területtel @msg `width` must be from {lo} to {hi} pt A `width` értéke {lo} és {hi} pt között lehet +@msg `angle` must be from -180 to 180 degrees Az `angle` értéke -180 és 180 fok között lehet +@msg `roundness` must be from 1 to 100% A `roundness` értéke 1 és 100% között lehet @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`: 1 és {MAX_BRIDGES_PER_ISLAND} közötti egész szám kell Weed Box and Lines… Gyomláló keret és vonalak… Weed Box and Lines Gyomláló keret és vonalak diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ea10433ebd..8cf076dbe6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7106,6 +7106,8 @@ breakText Glyphs Glifi @msg No bridge of this width fits across the selected art Nessun ponte di questa larghezza entra nella grafica selezionata @msg Some islands could not be joined to the area around the art Non è stato possibile collegare alcune isole all’area intorno alla grafica @msg `width` must be from {lo} to {hi} pt `width` deve essere compreso tra {lo} e {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` deve essere compreso tra -180 e 180 gradi +@msg `roundness` must be from 1 to 100% `roundness` deve essere compreso tra 1 e 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve essere un numero intero compreso tra 1 e {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Riquadro e linee di spellicolatura… Weed Box and Lines Riquadro e linee di spellicolatura diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ca80ba3a83..b328f86691 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7172,6 +7172,8 @@ breakText Glyphs 字形 @msg No bridge of this width fits across the selected art この幅のブリッジは選択したアートワークに収まりません @msg Some islands could not be joined to the area around the art 一部のアイランドをアートワークの周囲の領域につなげられませんでした @msg `width` must be from {lo} to {hi} pt `width` は {lo}~{hi} pt の範囲で指定してください +@msg `angle` must be from -180 to 180 degrees `angle` は -180~180 度の範囲で指定してください +@msg `roundness` must be from 1 to 100% `roundness` は 1~100% の範囲で指定してください @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` には 1 から {MAX_BRIDGES_PER_ISLAND} の整数を指定してください Weed Box and Lines… カス取り枠とライン… Weed Box and Lines カス取り枠とライン diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0778b2e405..0aacf8c61c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7590,6 +7590,8 @@ font-script Japanese იაპონური @msg No bridge of this width fits across the selected art ამ სიგანის ხიდი მონიშნულ ნახატზე არ ეტევა @msg Some islands could not be joined to the area around the art ზოგიერთი კუნძული ვერ დაუკავშირდა ნახატის გარშემო არეს @msg `width` must be from {lo} to {hi} pt `width` უნდა იყოს {lo}-დან {hi} pt-მდე +@msg `angle` must be from -180 to 180 degrees `angle` უნდა იყოს -180-დან 180 გრადუსამდე +@msg `roundness` must be from 1 to 100% `roundness` უნდა იყოს 1-დან 100%-მდე @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` უნდა იყოს მთელი რიცხვი 1-დან {MAX_BRIDGES_PER_ISLAND}-მდე Weed Box and Lines… ნარჩენის მოსაცილებელი ჩარჩო და ხაზები… Weed Box and Lines ნარჩენის მოსაცილებელი ჩარჩო და ხაზები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d0e5750000..bc61615ca7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7067,6 +7067,8 @@ breakText Glyphs 글리프 @msg No bridge of this width fits across the selected art 이 너비의 브리지가 선택한 아트워크에 들어가지 않습니다 @msg Some islands could not be joined to the area around the art 일부 섬을 아트워크 주변 영역에 연결할 수 없습니다 @msg `width` must be from {lo} to {hi} pt `width`는 {lo}에서 {hi}pt 사이여야 합니다 +@msg `angle` must be from -180 to 180 degrees `angle`는 -180도에서 180도 사이여야 합니다 +@msg `roundness` must be from 1 to 100% `roundness`는 1%에서 100% 사이여야 합니다 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`는 1에서 {MAX_BRIDGES_PER_ISLAND} 사이의 정수여야 합니다 Weed Box and Lines… 위딩 상자 및 선… Weed Box and Lines 위딩 상자 및 선 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0d4ceaf795..2330630d23 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -526,6 +526,8 @@ @msg No bridge of this width fits across the selected art Geen brug van deze breedte past over de geselecteerde illustratie @msg Some islands could not be joined to the area around the art Sommige eilanden konden niet worden verbonden met het gebied rond de illustratie @msg `width` must be from {lo} to {hi} pt `width` moet van {lo} tot {hi} pt zijn +@msg `angle` must be from -180 to 180 degrees `angle` moet van -180 tot 180 graden zijn +@msg `roundness` must be from 1 to 100% `roundness` moet van 1 tot 100% zijn @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` moet een geheel getal van 1 tot {MAX_BRIDGES_PER_ISLAND} zijn File Bestand diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7911a22071..d9fdc0094f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7333,6 +7333,8 @@ breakText Glyphs Glify @msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej grafice @msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół grafiki @msg `width` must be from {lo} to {hi} pt `width` musi mieścić się w zakresie od {lo} do {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` musi mieścić się w zakresie od -180 do 180 stopni +@msg `roundness` must be from 1 to 100% `roundness` musi mieścić się w zakresie od 1 do 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musi być liczbą całkowitą od 1 do {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Ramka i linie do wybierania… Weed Box and Lines Ramka i linie do wybierania diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c2349359ed..31a9a6f4cc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7549,6 +7549,8 @@ swatch Yellow Green Verde-amarelado @msg No bridge of this width fits across the selected art Nenhuma ponte desta largura cabe na arte selecionada @msg Some islands could not be joined to the area around the art Algumas ilhas não puderam ser unidas à área ao redor da arte @msg `width` must be from {lo} to {hi} pt `width` deve estar entre {lo} e {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` deve estar entre -180 e 180 graus +@msg `roundness` must be from 1 to 100% `roundness` deve estar entre 1 e 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve ser um número inteiro de 1 a {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caixa e Linhas de Descasque… Weed Box and Lines Caixa e Linhas de Descasque diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f878461da5..969865383d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7565,6 +7565,8 @@ shape Open Открытый @msg No bridge of this width fits across the selected art Мостик такой ширины не помещается поперёк выделенной графики @msg Some islands could not be joined to the area around the art Некоторые островки не удалось соединить с областью вокруг графики @msg `width` must be from {lo} to {hi} pt `width` должно быть от {lo} до {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` должно быть от -180 до 180 градусов +@msg `roundness` must be from 1 to 100% `roundness` должно быть от 1 до 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` должно быть целым числом от 1 до {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Рамка и линии выборки… Weed Box and Lines Рамка и линии выборки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 70efcf795f..974b1ca996 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8915,6 +8915,8 @@ digits Hindi Hindi @msg No bridge of this width fits across the selected art Ingen brygga med den här bredden får plats över den markerade teckningen @msg Some islands could not be joined to the area around the art Vissa öar kunde inte förbindas med området runt teckningen @msg `width` must be from {lo} to {hi} pt `width` måste vara från {lo} till {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` måste vara från -180 till 180 grader +@msg `roundness` must be from 1 to 100% `roundness` måste vara från 1 till 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` måste vara ett heltal från 1 till {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Rensningsram och rensningslinjer… Weed Box and Lines Rensningsram och rensningslinjer diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 6c9deb97d0..0dae608b75 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2280,6 +2280,36 @@ fn three_d_refusals_are_translated_in_every_complete_catalog() { assert!(missing.is_empty(), "{} 3D messages have no @msg row:\n{}", missing.len(), missing.join("\n")); } +/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`) and the Scissors' (`path.split` +/// `t`) show in every complete-message language with the key and the range numbers as given; the +/// error the command returns stays English. +#[test] +fn eraser_and_scissors_range_refusals_translate_with_their_values() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + let refusals = [ + ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "angle": 200}), "`angle`", ["-180", "180"]), + ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "roundness": 0}), "`roundness`", ["1", "100"]), + ("path.split", json!({"id": id, "segment": 0, "t": 1.5}), "`t`", ["0", "1"]), + ]; + for (cmd, p, key, numbers) in &refusals { + let e = s.execute(cmd, p).unwrap_err().to_string(); + assert!(e.starts_with(&format!("invalid parameters for `{cmd}`: ")) && e.contains(key) && e.contains(" must be from "), "{e}"); + assert_eq!(message(Lang::EN, &e), e); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &e); + assert!(!shown.contains(" must be from ") && shown.contains(&format!("`{cmd}`")) && shown.contains(key), "{code}: {e} -> {shown}"); + assert!(numbers.iter().all(|n| shown.contains(n)), "{code}: {e} -> {shown}"); + } + } + assert_eq!( + message(de(), &s.execute("path.eraseRegion", &json!({"points": [[10, 10], [60, 10]], "roundness": 101})).unwrap_err().to_string()), + "ungültige Parameter für `path.eraseRegion`: `roundness` muss zwischen 1 und 100 % liegen" + ); +} + /// A 3D effect's refusal shows in the interface language whole, with the effect's translated /// name, and with its numbers, the parameter keys it names and a symbol's name as given; the /// error the command returns stays English. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ff88601736..33ca733e85 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7432,6 +7432,8 @@ breakText Glyphs Glifler @msg No bridge of this width fits across the selected art Bu genişlikte bir köprü seçili çizime sığmıyor @msg Some islands could not be joined to the area around the art Bazı adalar çizimin çevresindeki alana bağlanamadı @msg `width` must be from {lo} to {hi} pt `width` {lo} ile {hi} pt arasında olmalıdır +@msg `angle` must be from -180 to 180 degrees `angle` -180 ile 180 derece arasında olmalıdır +@msg `roundness` must be from 1 to 100% `roundness` %1 ile %100 arasında olmalıdır @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 ile {MAX_BRIDGES_PER_ISLAND} arasında bir tam sayı olmalıdır Weed Box and Lines… Ayıklama Kutusu ve Çizgileri… Weed Box and Lines Ayıklama Kutusu ve Çizgileri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a7b3ea2c2e..d3b43cda6a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7086,6 +7086,8 @@ breakText Glyphs Гліфи @msg No bridge of this width fits across the selected art Місток такої ширини не вміщується впоперек виділеної графіки @msg Some islands could not be joined to the area around the art Деякі острівці не вдалося з’єднати з областю навколо графіки @msg `width` must be from {lo} to {hi} pt `width` має бути від {lo} до {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` має бути від -180 до 180 градусів +@msg `roundness` must be from 1 to 100% `roundness` має бути від 1 до 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` має бути цілим числом від 1 до {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Рамка й лінії вибірки… Weed Box and Lines Рамка й лінії вибірки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 518d89e4b6..18d84b1c50 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7087,6 +7087,8 @@ breakText Glyphs Glyph @msg No bridge of this width fits across the selected art Không có cầu nối nào rộng như vậy vừa với hình vẽ đã chọn @msg Some islands could not be joined to the area around the art Không thể nối một số đảo với vùng xung quanh hình vẽ @msg `width` must be from {lo} to {hi} pt `width` phải từ {lo} đến {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` phải từ -180 đến 180 độ +@msg `roundness` must be from 1 to 100% `roundness` phải từ 1 đến 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` phải là số nguyên từ 1 đến {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Khung và đường bóc phần thừa… Weed Box and Lines Khung và đường bóc phần thừa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 26fb9e0c1b..c0c9fcc282 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7315,6 +7315,8 @@ breakText Glyphs 字形 @msg No bridge of this width fits across the selected art 此宽度的连接桥无法放入所选图稿 @msg Some islands could not be joined to the area around the art 部分孤岛无法连接到图稿周围的区域 @msg `width` must be from {lo} to {hi} pt `width` 必须介于 {lo} 到 {hi} pt 之间 +@msg `angle` must be from -180 to 180 degrees `angle` 必须介于 -180 到 180 度之间 +@msg `roundness` must be from 1 to 100% `roundness` 必须介于 1 到 100% 之间 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必须是 1 到 {MAX_BRIDGES_PER_ISLAND} 之间的整数 Weed Box and Lines… 除废框和除废线… Weed Box and Lines 除废框和除废线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5685430cc8..978c1ceac1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7122,6 +7122,8 @@ breakText Glyphs 字符 @msg No bridge of this width fits across the selected art 此寬度的連接橋無法放入所選圖稿 @msg Some islands could not be joined to the area around the art 部分孤島無法連接到圖稿周圍的區域 @msg `width` must be from {lo} to {hi} pt `width` 必須介於 {lo} 到 {hi} pt 之間 +@msg `angle` must be from -180 to 180 degrees `angle` 必須介於 -180 到 180 度之間 +@msg `roundness` must be from 1 to 100% `roundness` 必須介於 1 到 100% 之間 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必須是介於 1 到 {MAX_BRIDGES_PER_ISLAND} 的整數 Weed Box and Lines… 除廢框與除廢線… Weed Box and Lines 除廢框與除廢線 diff --git a/docs/mcp.md b/docs/mcp.md index 912ac32562..fd0ddea798 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5160,6 +5160,12 @@ rotation that is neither a number nor null with `` `pressure` must be a number, (`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `at`, `in` or `out` that is not `[x, y]` with `` `in` must be [x, y] ``, naming the key. +`path.eraseRegion` refuses an `angle` outside -180° to 180° with `` `angle` must be from -180 to 180 degrees `` and a +`roundness` outside 1% to 100% with `` `roundness` must be from 1 to 100% ``. `path.split` refuses a `t` outside 0 to 1 +with `` `t` must be from 0 to 1 ``, with `segment` or with `anchor`. The document does not change and no undo step is +recorded. Left out or null, `angle` is 0° and `roundness` is 100%; left out, `t` is 0.5. The Eraser's ranges are +VectorCraft's own values. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 26681e5b7f..581e6aa31d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1071,6 +1071,7 @@ 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`). + `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. 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`). - **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 dce6524ada0e52cbe43d53ae7a12c7f794c52689 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:54:20 -0800 Subject: [PATCH 04/50] i18n: Danish row for the justification order message --- crates/ui-egui/src/i18n/da.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ca27bdd2f9..23e0faf4b2 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6560,6 +6560,7 @@ swatch Bright Violet Kraftig violet Single Word Justification: Justering af enkeltord: Full Justify Lige margener Minimum must not exceed Desired, nor Desired Maximum. Minimum må ikke overstige Ønsket, og Ønsket ikke Maksimum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum må ikke overstige Ønsket, og Ønsket ikke Maksimum Justification Justering Add filters from the list above Tilføj filtre fra listen ovenfor Add to Stack Tilføj til stak From efaf10a76a78452d985eaf9b57f6ecf06ce5b2a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:57:08 -0800 Subject: [PATCH 05/50] i18n: Danish rows for the Eraser range refusals --- crates/ui-egui/src/i18n/da.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ca27bdd2f9..5eaa8da41a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -632,6 +632,8 @@ @msg No bridge of this width fits across the selected art Ingen bro med denne bredde passer hen over den markerede grafik @msg Some islands could not be joined to the area around the art Nogle øer kunne ikke forbindes med området omkring grafikken @msg `width` must be from {lo} to {hi} pt `width` skal være fra {lo} til {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` skal være fra -180 til 180 grader +@msg `roundness` must be from 1 to 100% `roundness` skal være fra 1 til 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` skal være et heltal fra 1 til {MAX_BRIDGES_PER_ISLAND} File Filer From 42e722e9d018c48cfe867fe78c67d24726e13c0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 05:02:52 -0800 Subject: [PATCH 06/50] Expand Appearance: symbol instances with raster effects in a fill or stroke become art, nested ones included A symbol instance whose topmost fill or stroke has only a shadow or glow now expands to its art over the effect's image, instead of a live instance over the image. When the outer instance's art expands, an instance inside it whose topmost fill or stroke has a raster effect (its own or one the outer instance passes on) becomes its art too: a shadow or glow becomes an image under that art, and a blur, feather or inner glow replaces it with the image. This repeats for the instances in that art, within the nesting depth and symbol art limits. An instance of a missing symbol stays an instance. --- crates/effects/src/lib.rs | 4 +- crates/effects/src/reshape.rs | 10 ++ crates/engine/src/cmd/effectcmd.rs | 74 ++++++++++----- crates/engine/src/tests/expand.rs | 144 ++++++++++++++++++++++++++++- docs/mcp.md | 14 ++- docs/target-app-parity.md | 1 + 6 files changed, 216 insertions(+), 31 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e3915797f2..3d72d145ea 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -87,8 +87,8 @@ pub use raster::{ }; pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry, - has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art, - outline_text, paint_type_piece, reshape, + has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, + outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 4c8191fd2b..d17dd784c0 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -845,6 +845,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod as_art(doc, n, symbol_art) } +/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the +/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`] +/// gives. `None` for other kinds of objects and for an instance without `symbol_art`. +pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { + if !matches!(n.kind, NodeKind::SymbolInstance { .. }) { + return None; + } + as_art(doc, n, symbol_art) +} + /// [`reshape`] without its checks (no geometry effects: just the art). pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default()) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 42113c9578..308305fe04 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", can_expand, expand_appearance ), @@ -1007,12 +1007,10 @@ fn expand_pieces( } /// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose -/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as -/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so -/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more -/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art -/// would take the objects placed so far past `budget`. -fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) { +/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`], +/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in +/// that art in turn, so [`expand_pieces`] bakes their effects with the rest. +fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64) { for c in m.children_mut().into_iter().flatten() { if !matches!(c.kind, NodeKind::SymbolInstance { .. }) { if c.children().is_some() { @@ -1020,24 +1018,53 @@ fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mu } continue; } - let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue }; - if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) { - continue; - } - let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue }; - let count = sym.art.count() as u64; - if count > *budget { - continue; - } - *budget -= count; - let art = vectorcraft_render::instance_art(&sym.art, c); - if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) { - expand_nested_instances(d, &mut a, depth + 1, budget); + if let Some(a) = expanded_instance(d, c, depth, budget) { *c = Arc::new(a); } } } +/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster +/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art +/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as +/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when +/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance +/// staying as it is, when its active fill and stroke have no such effect, it is more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would +/// take the objects placed so far past `budget`. When the image of its raster effects can't be +/// made, they stay on the art its geometry effects make, and without one it stays as it is. +fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None }; + let raster = effects::has_instance_row_raster(c); + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(raster || effects::has_item_geometry(c)) { + return None; + } + let sym = d.symbols.iter().find(|s| s.name == *symbol)?; + let count = sym.art.count() as u64; + if count > *budget { + return None; + } + *budget -= count; + let art = vectorcraft_render::instance_art(&sym.art, c); + let image = if raster { raster_image(d, c) } else { None }; + let mut v = c.clone(); + if image.is_some() { + rasterfx::strip_raster(&mut v, false); + } + let below = match image { + Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)), + Some((image, true)) => Some(image), + None => None, + }; + let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art)) + .or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?; + expand_nested_instances(d, &mut a, depth + 1, budget); + if let Some(image) = below { + rasterfx::put_below(d, &mut a, image); + } + Some(a) +} + /// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids? fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { let mut ids = std::collections::HashSet::new(); @@ -1192,7 +1219,12 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } _ => None, }; - effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { + // A symbol instance whose active fill or stroke has only effects that paint below it + // (now in the image) becomes its art as well. + let row_raster = image.is_some() && effects::has_instance_row_raster(&n); + let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref()) + .or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None }); + outlined.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); diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index e4bfa26b2f..0d2ce9d9f5 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() { assert!(expandable(&s), "the fill's shadow can be expanded"); run(&mut s, "effect.expandAppearance", json!({})); - let ch = node(&s, id).children().cloned().expect("the instance becomes a group"); + let n = node(&s, id); + let ch = n.children().cloned().expect("the instance becomes a group"); assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label()); - assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label()); - no_effects_left(&ch[1]); + n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance")); + no_effects_left(&n); let after = render(&s); assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); run(&mut s, "edit.undo", json!({})); @@ -508,6 +509,143 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() { assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100)); } +/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner` +/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new +/// fill without paint on top. Returns the Outer instance and its new row's index. +fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) { + let (inner_id, inner_row) = instance_with_row(s, "Inner", true); + inner(s, inner_id, inner_row); + let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +/// The symbol instances and the images in `n`. +fn instances_and_images(n: &Node) -> (usize, usize) { + let mut found = (0, 0); + n.walk(&mut |part| match part.kind { + NodeKind::SymbolInstance { .. } => found.0 += 1, + NodeKind::Image(_) => found.1 += 1, + _ => {} + }); + found +} + +/// Replace the art of every symbol with an empty group. +fn empty_symbols(s: &mut Session) { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + for (i, sym) in d.symbols.iter_mut().enumerate() { + sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![])); + } +} + +/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art +/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result +/// no longer follows either symbol. +#[test] +fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert!(images >= 1, "the inner shadow is an image"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); + empty_symbols(&mut s); + assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols"); +} + +/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's +/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in +/// one undo step. +#[test] +fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + shadow_row(&mut s, id, row); + let before = render(&s); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert!(images >= 2, "the outer and inner shadows are images: {images}"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); + + run(&mut s, "edit.undo", json!({})); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back"); + run(&mut s, "edit.redo", json!({})); + empty_symbols(&mut s); + assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols"); +} + +/// A blur on the nested instance's fill: the nested instance becomes the image. +#[test] +fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() { + let mut s = session(); + let blur = |s: &mut Session, id: NodeId, row: usize| { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}})); + }; + let (id, row) = nested_with_row(&mut s, blur); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert_eq!(images, 1, "the blurred inner art is one image"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it. +#[test] +fn a_hidden_nested_instance_fill_shadow_makes_no_image() { + let mut s = session(); + let hidden = |s: &mut Session, id: NodeId, row: usize| { + shadow_row(s, id, row); + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false})); + }; + let (id, row) = nested_with_row(&mut s, hidden); + offset_row(&mut s, id, row, 10.0); + assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow"); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image"); + no_effects_left(&n); +} + +/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art +/// expands around it. +#[test] +fn a_nested_instance_of_a_missing_symbol_stays_an_instance() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + offset_row(&mut s, id, row, 10.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.symbols.retain(|sym| sym.name != "Inner"); + } + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image"); +} + /// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the /// shadow on the art's fill, not its stroke, and PDF export makes an image of it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index bb0fba8d46..c04cc21b37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5242,11 +5242,15 @@ the object with the image). Type with a geometry effect (Outline Object included is outlined; type that has no fills or strokes of its own and whose only effects are shadows or outer glows stays type, with the image under it. A group's or layer's own fills and strokes become objects among its members, and its members are expanded too. A symbol instance whose topmost fill or topmost stroke is visible, has an opacity above 0 -and has a geometry effect becomes a group of its art: that fill's effects reshape the filled shapes of the art and that -stroke's effects reshape its stroked shapes, which keep their colors, as the canvas draws them (VectorCraft's own -rule); the instance's other fills and strokes are dropped. A raster effect on that fill or stroke draws on the filled -or stroked shapes of the art, and expanding makes it an image as for other objects; with no geometry effect, the -instance stays an instance over a shadow or glow image, and a blur, feather or inner glow replaces it with the image. +and has a geometry or raster effect becomes a group of its art: that fill's effects reshape the filled shapes of the +art and that stroke's effects reshape its stroked shapes, which keep their colors, as the canvas draws them +(VectorCraft's own rule); the instance's other fills and strokes are dropped. A raster effect on that fill or stroke +draws on the filled or stroked shapes of the art, and expanding makes it an image as for other objects: a shadow or +glow image goes under the art, and a blur, feather or inner glow replaces the instance with the image. A symbol +instance in the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance +passes on, becomes its art and image the same way, and so do the instances in that art (VectorCraft's own rule). +Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster +effect on an instance in the art stayed live. The result is `{ids}`; when an image in the art can't be decoded, the images made from raster effects do not show it, and the result also carries the `warning` that Flatten Transparency gives. A path's strokes stay strokes, as the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f08f2b9f19..2e08ff6a3a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1690,6 +1690,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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`). 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. + Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. No live instance or raster effect is left from those effects, so the result no longer changes with the symbols. The help page describes Expand Appearance turning appearance attributes into objects, and the help page describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. 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). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. From 9e88bfe698c6baed576fcc280e15dd3f6521e7ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:09:57 -0800 Subject: [PATCH 07/50] Revolve: a partial sweep with Cap closes its cut sides With an Angle below 360 and Cap on, Revolve and Revolve (Classic) now close the two angular cut sides instead of leaving them open. Each side is flat and evenly shaded and is drawn in depth order with the rest of the surface: the region between each open subpath and the axis, and the area of each closed subpath, one face per region. A subpath that walls a hole under the object's fill rule leaves the hole open, and a self-intersecting subpath fills what the nonzero rule fills. The cut sides appear in preview, SVG/PDF export, Expand Appearance, Expand as Wireframes, shadows and exported 3D meshes. Cap off keeps the surface hollow. Painter visibility now looks for covers over every piece of a face, so a face drawn as several contours is trimmed where any of them is covered. Docs: docs/revolve.md, docs/three-d.md, docs/mcp.md, the effects-parity row, the Cap tooltip and its catalog rows. --- crates/effects/src/catalog.rs | 4 +- crates/effects/src/revolve.rs | 53 +++-- crates/three-d/src/lib.rs | 260 ++++++++++++++++++++++++- crates/three-d/src/mesh.rs | 9 +- crates/three-d/src/mesh/tests.rs | 8 +- crates/three-d/src/shadow.rs | 4 +- crates/three-d/src/tests.rs | 1 + crates/three-d/src/tests/cut_sides.rs | 235 ++++++++++++++++++++++ crates/three-d/src/visibility.rs | 7 +- crates/three-d/src/visibility_parts.rs | 19 ++ crates/ui-egui/src/dialogs/revolve.rs | 2 +- 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 +- docs/effects-parity.md | 2 +- docs/mcp.md | 11 +- docs/revolve.md | 19 +- docs/three-d.md | 3 +- 43 files changed, 614 insertions(+), 79 deletions(-) create mode 100644 crates/three-d/src/tests/cut_sides.rs diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 1c1ca96d9f..a2bebe2fd1 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -182,7 +182,7 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[]}), ), g( @@ -217,7 +217,7 @@ pub fn effect_catalog() -> Vec { CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}), ), g( diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a9c9482d1d..51d51628c6 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; -use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; +use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; use crate::solids::wireframe::WireFace; @@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve { shade: flag(p, "shade", true), smooth_shading: true, cap_ends: flag(p, "cap", true), + fill_rule: FillRule::NonZero, curve_samples: None, map_surface: false, } @@ -222,7 +223,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: return Ok(()); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); - paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ())) + paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ())) } /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of @@ -380,7 +381,7 @@ fn cast_surface( None => { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); - caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options) + caster.revolve(path, options.fill_rule, b, options) } } } @@ -411,7 +412,7 @@ fn group_shadow( if ink.opacity <= 0.0 { continue; } - let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; + let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?; cast.push((s.scopes.as_slice(), ink, faces)); } Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) @@ -607,13 +608,16 @@ fn in_order(items: Vec, order: &[usize]) -> Vec { order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect() } -/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and -/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count -/// [`surface`] adds to; its graphics take the symbols of `doc`. +/// A surface of one object about the bounds of `path`, filled with `rule`, built with options +/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast +/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of +/// `doc`. +#[allow(clippy::too_many_arguments)] fn object_surface( doc: Option<&Document>, n: &Node, path: &PathData, + rule: FillRule, fx: &Effect, item: &AppearanceItem, expand: bool, @@ -622,7 +626,13 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept)) + surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept)) +} + +/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides +/// leave open the holes `rule` leaves in the profile. +fn rule_options(fx: &Effect, rule: FillRule) -> Revolve { + Revolve { fill_rule: rule, ..fx_options(fx) } } /// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of @@ -750,11 +760,11 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result, n: &Node) -> Result, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; + let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?; if let Some(b) = path.bounds() - && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()? + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()? { children.push(Arc::new(shadow)); } @@ -850,10 +860,10 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); if let Some(b) = p.bounds() - && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()? + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()? { shadow.appearance.effects = art.appearance.effects.clone(); shadows.push(Arc::new(shadow)); @@ -1021,6 +1031,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); + let options = Revolve { fill_rule: s.rule, ..options }; let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); @@ -1771,7 +1782,7 @@ mod tests { let mut fx = crate::new_effect(id, &json!({})).unwrap(); fx.params = params.clone(); let n = profile_node(); - let (path, _) = profile(&n).unwrap(); + let (path, rule) = profile(&n).unwrap(); let b = path.bounds().unwrap(); let mut half = n.clone(); if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] { @@ -1779,9 +1790,9 @@ mod tests { } for n in [n, half] { let item = surface_item(&n.appearance.items).unwrap(); - let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); - let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(); - let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(); + let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap(); + let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap(); + let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap(); assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}"); assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 4290bc1c75..2790458cc8 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -1,7 +1,7 @@ //! Portable 3D effect geometry: Revolve, Extrude & Bevel, Inflate and Rotate. No windowing, GPU or //! document dependencies. //! -//! Open profiles optionally close their circular ends with caps. Faces are projected and sorted back to front, +//! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front, //! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer: //! intersecting profiles can have ambiguous visibility and are not solid modelling inputs. #![forbid(unsafe_code)] @@ -102,9 +102,14 @@ pub struct Revolve { pub shade: bool, /// Interpolate profile normals using vector gradients. Enabled by default. pub smooth_shading: bool, - /// Close circular endpoint rings of open profiles. Partial sweeps get sectors; - /// the angular cut sides are left open. Enabled by default. + /// Close circular endpoint rings of open profiles (sectors on a partial sweep), and the two + /// angular cut sides of a partial sweep: each is one flat face of the region between an open + /// profile and the axis, and of a closed profile's own area with its holes left open. Off, the + /// surface is hollow. Enabled by default. pub cap_ends: bool, + /// The profile's fill rule, which decides the holes the cut sides leave open in [`revolve`] and + /// [`revolve_shadowed`]. Nonzero by default. + pub fill_rule: FillRule, /// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of /// one object. `None` plans them from the profile alone. pub curve_samples: Option, @@ -140,6 +145,7 @@ impl Default for Revolve { shade: true, smooth_shading: true, cap_ends: true, + fill_rule: FillRule::NonZero, curve_samples: None, map_surface: false, } @@ -729,7 +735,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi /// Evaluate a profile in document space. All subpaths share one axis from `bounds`. /// Invalid or excessively complex inputs return an error, never a partial surface. pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result, String> { - revolve_faces(path, FillRule::NonZero, bounds, options, None) + revolve_faces(path, options.fill_rule, bounds, options, None) } /// [`revolve`]'s faces as facets, back to front, for the classic surfaces: each keeps its @@ -772,7 +778,10 @@ pub fn revolve_curve_samples<'a>(paths: impl IntoIterator, if lines.saturating_add(curves.saturating_mul(MIN_CURVE_SAMPLES)) > points { return Err(TOO_COMPLEX_PROFILE.into()); } - let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)) / per_edge).min(points); + // A partial sweep with caps closes each of its two cut sides with a face for each outline, + // planned here as one for each contour. + let cut_sides = if o.cap_ends && o.angle > 0.0 && o.angle < 360.0 { contours.saturating_mul(2) } else { 0 }; + let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)).saturating_sub(cut_sides) / per_edge).min(points); if curves == 0 { return if lines > edges { Err(TOO_COMPLEX_SURFACE.into()) } else { Ok(CURVE_SAMPLES) }; } @@ -1055,6 +1064,242 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i Ok(()) } +/// Twice the signed area of the polygon `ring`. +fn ring_area(ring: &[Point]) -> f64 { + ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum() +} + +/// The region a cut side of a partial sweep closes for one contour's profile `points`, in the +/// profile's plane and in the order the profile runs: a closed contour's own area, or an open one +/// closed along the axis at `axis` from its last end back to its first. An open contour whose ends +/// meet is taken as closed. The region is given as the loops the nonzero rule fills, so one that +/// crosses itself, such as a bow tie, gives a loop for each part it encloses. None when the contour +/// encloses no area. +fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec> { + let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return vec![] }; + let mut ring = points.to_vec(); + if !closed && first.distance(last) > 1e-10 { + ring.extend([Point::new(axis, last.y), Point::new(axis, first.y)]); + } + ring.dedup_by(|a, b| a.distance(*b) <= 1e-10); + while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-10) { + ring.pop(); + } + if ring.len() < 3 { + return vec![]; + } + let crossed = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ring, true)]); + match vectorcraft_pathops::try_unite_all_with(&[(&crossed, FillRule::NonZero)], 1e-6) { + Ok(loops) => loops + .subpaths + .iter() + .map(|s| s.anchors.iter().map(|a| a.p).collect::>()) + .filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10) + .collect(), + // Past the boolean's limits, the region is kept as the profile draws it. + Err(_) if ring_area(&ring).abs() > 1e-10 => vec![ring], + Err(_) => vec![], + } +} + +/// The steps at whose ends the two cut sides of a partial sweep lie, each with its outward normal +/// before the view's rotation: the start faces back against the sweep, the end on along it. +fn cut_sides(at: &Sweeping) -> [(usize, V3); 2] { + // The profile lies on one side of the axis: the sweep turns it forward on the left and back on + // the right. + let side = if at.o.edge == Edge::Left { 1.0 } else { -1.0 }; + let (s, c) = at.sweep.sin_cos(); + [(0, V3(0.0, 0.0, -side)), (at.steps, V3(-s * side, 0.0, c * side))] +} + +/// Whether `p` lies inside the polygon `ring`. +fn ring_contains(ring: &[Point], p: Point) -> bool { + let mut inside = false; + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()) { + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + inside = !inside; + } + } + inside +} + +/// The regions `regions` (turned as [`oriented`] gives them) grouped into the faces of one cut +/// side: each outline, counterclockwise, first, with the holes, clockwise, that the smallest outline +/// around them holds. +fn cut_groups(regions: &[Vec]) -> Vec>> { + let bounds = |r: &[Point]| r.iter().fold(Rect::new(f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |b, p| b.union_pt(*p)); + // Each outline with its bounds and area, and the holes it holds. + let mut groups: Vec<(Rect, f64, Vec<&Vec>)> = + regions.iter().filter(|r| ring_area(r) > 0.0).map(|r| (bounds(r), ring_area(r), vec![r])).collect(); + for hole in regions.iter().filter(|r| ring_area(r) < 0.0) { + let Some(&p) = hole.first() else { continue }; + let owner = + groups.iter_mut().filter(|(b, _, g)| b.contains(p) && g.first().is_some_and(|o| ring_contains(o, p))).min_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((_, _, g)) = owner { + g.push(hole); + } + } + groups.into_iter().map(|(_, _, g)| g).collect() +} + +/// One face of the cut side of a partial sweep at the end of step `step`: an outline among the +/// regions ([`cut_groups`]) and its holes, turned there and drawn as one flat, evenly shaded face, +/// filled with the nonzero rule, so its holes stay open. The outline gives the face's shading, +/// depth and polygon. `None` when it is seen edge on. +fn cut_face(at: &Sweeping, regions: &[&Vec], step: usize, eye: Option, light: V3) -> Result, String> { + let origin = Point::new(at.axis, at.center_y); + let turned: Vec> = regions.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); + let Some(vertices) = turned.first() else { return Ok(None) }; + let Some(mut face) = project_face(vertices, None, at.o, origin, eye, light)? else { return Ok(None) }; + let project = |v: &V3| { + let factor = perspective_scale(eye, v.2); + Point::new(origin.x + v.0 * factor, origin.y + v.1 * factor) + }; + let drawn: Vec> = turned.iter().map(|c| c.iter().map(project).collect()).collect(); + if drawn.iter().flatten().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return Err("Revolve projection is not finite".into()); + } + face.outline = Some(PathData::new(drawn.iter().map(|c| vectorcraft_geom::SubPath::polyline(c, true)).collect())); + Ok(Some(face)) +} + +/// Both cut sides of a partial sweep drawn, a face for each outline among `regions` with its holes +/// ([`cut_face`]), those seen edge on left out; none for no regions. +fn cut_faces(at: &Sweeping, regions: &[Vec], eye: Option, light: V3) -> Result, String> { + let groups = cut_groups(regions); + let mut out = vec![]; + for (step, _) in cut_sides(at) { + for group in &groups { + out.extend(cut_face(at, group, step, eye, light)?); + } + } + Ok(out) +} + +/// The regions the cut sides of a partial sweep close ([`cut_region`]), contour by contour: those +/// of the profile drawn, each with its contour's index, and those of the profile kept for a mesh, +/// each with whether it walls a hole. +struct CutRegions { + /// A partial sweep with caps: there are cut sides to close. + on: bool, + drawn: Vec<(Vec>, usize)>, + kept: Vec<(Vec>, bool)>, +} + +/// The loops of each contour's region in `regions` turned so a region runs counterclockwise in the +/// profile's plane, or clockwise when it is marked as a hole: filled with the nonzero rule, the +/// holes stay open and every outline fills. A region's largest loop decides, and loops inside it +/// that run the other way stay holes of it. +fn oriented(regions: impl IntoIterator>, bool)>) -> Vec> { + let mut out = vec![]; + for (mut loops, hole) in regions { + let largest = loops.iter().map(|l| ring_area(l)).max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or_default(); + if (largest < 0.0) != hole { + loops.iter_mut().for_each(|l| l.reverse()); + } + out.extend(loops); + } + out +} + +/// Whether each of the closed contours `contours` of `path` walls a hole under `rule`: the fill is +/// outside it and not inside at most of its segments' middles. An open contour, or every contour +/// when there is only one or the search passes its limits, walls none. +fn holes_of(path: &PathData, rule: FillRule, contours: &[usize]) -> Vec { + let none = vec![false; contours.len()]; + if contours.len() < 2 { + return none; + } + let Ok(mut search) = HoleSearch::new(path, rule) else { return none }; + let mut out = Vec::with_capacity(contours.len()); + for &k in contours { + let Some(sp) = path.subpaths.get(k).filter(|sp| sp.closed) else { + out.push(false); + continue; + }; + let mut walls = 0; + for segment in 0..sp.anchors.len() { + match search.is_hole(k, sp.segment(segment).eval(0.5)) { + Ok(hole) => walls += usize::from(hole), + Err(_) => return none, + } + } + out.push(walls * 2 > sp.anchors.len()); + } + out +} + +impl CutRegions { + /// The regions of a sweep with sanitized options `o`, none yet. + fn new(o: Revolve) -> Self { + Self { on: o.cap_ends && o.angle > 0.0 && o.angle < 360.0, drawn: vec![], kept: vec![] } + } + + /// Add the regions of contour `contour`'s profiles: `drawn`, when faces are drawn, and `kept`, + /// when a mesh keeps them. + fn add(&mut self, contour: usize, drawn: Option<&Swept>, kept: Option<&Swept>, closed: bool, axis: f64) { + if !self.on { + return; + } + if let Some(region) = drawn.map(|s| cut_region(&s.points, closed, axis)).filter(|r| !r.is_empty()) { + self.drawn.push((region, contour)); + } + if let Some(s) = kept { + let region = cut_region(&s.points, closed, axis); + // A contour walls a hole when most of its parts do. + let walls = s.holes.iter().filter(|h| **h).count(); + if !region.is_empty() { + self.kept.push((region, walls * 2 > s.holes.len())); + } + } + } + + /// Close the cut sides of sweep `at` of `path`: keep them for the mesh, if any, of `kept` + /// (whether faces are drawn, the mesh, and the error that stopped it, as [`lose_mesh`] takes + /// them) within `face_limit` faces, and give them drawn ([`cut_faces`]), the holes `rule` + /// leaves in `path` left open. + fn close( + &self, + at: &Sweeping, + (path, rule): (&PathData, FillRule), + kept: (bool, &mut Option<&mut Vec>, &mut Option), + face_limit: usize, + eye: Option, + light: V3, + ) -> Result, String> { + let (draw, mesh, lost) = kept; + let result = match mesh.as_deref_mut() { + Some(m) => keep_cuts(at, &self.kept, |contours, normal| { + m.push((contours, normal)); + if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } + }), + None => Ok(()), + }; + if let Err(e) = result { + lose_mesh(draw, mesh, lost, e)?; + } + let contours: Vec = self.drawn.iter().map(|(_, k)| *k).collect(); + let holes = holes_of(path, rule, &contours); + cut_faces(at, &oriented(self.drawn.iter().map(|(r, _)| r.clone()).zip(holes)), eye, light) + } +} + +/// Keep for a mesh the two cut sides of a partial sweep: the regions `regions` of every contour +/// ([`cut_region`]), each marked when it walls a hole, turned to each side. Outlines run one way +/// round and holes the other, so the mesh leaves the holes open. `keep` keeps one face with its +/// outward normal. +fn keep_cuts(at: &Sweeping, regions: &[(Vec>, bool)], mut keep: impl FnMut(Vec>, V3) -> Result<(), String>) -> Result<(), String> { + if regions.is_empty() { + return Ok(()); + } + let oriented = oriented(regions.iter().cloned()); + for (step, normal) in cut_sides(at) { + let contours = oriented.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); + keep(contours, at.o.rotate(normal))?; + } + Ok(()) +} + /// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn. fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut Option, e: String) -> Result<(), String> { if !draw { @@ -1152,6 +1397,9 @@ fn revolve_sweep( // its edges are cut into. let (mut count, mut kept_count) = (0, 0); let mut curve_budget = 0; + // With caps, a partial sweep closes its two cut sides: the regions of every contour drawn, and + // those kept for the mesh with whether each walls a hole. + let mut cuts = CutRegions::new(o); for (contour, sp) in path.subpaths.iter().enumerate() { let (mut drawn, mut kept) = (Swept::default(), Swept::default()); if let Some(first) = sp.anchors.first() { @@ -1244,6 +1492,7 @@ fn revolve_sweep( } } } + cuts.add(contour, draw.then_some(&drawn), mesh.is_some().then_some(&kept), sp.closed, axis); // Which way a profile runs round the region it sweeps (closed against the axis at its ends // when it is open), so the faces' normals point out of the solid. A closed contour that does // not touch the axis has its side cut opposite the middle of its outer side; an anchor goes @@ -1344,6 +1593,7 @@ fn revolve_sweep( } } } + cuts.close(&at, (path, rule), (draw, &mut mesh, &mut lost), face_limit, eye, light)?.into_iter().try_for_each(|face| emit(Some(face), 1))?; faces.sort_by(|a, b| a.depth.total_cmp(&b.depth)); Ok((faces, lost)) } diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index cd9623191c..14284cb1bf 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -118,8 +118,9 @@ pub fn inflate_meshed( } /// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than -/// 360° caps its ends with sectors and leaves its two cut sides open ([`Revolve::cap_ends`]). The -/// walls of holes under `rule`, such as the counter of an O, face into the hole. +/// 360° caps its ends with sectors and closes its two cut sides with flat faces ([`Revolve::cap_ends`]). +/// The walls of holes under `rule`, such as the counter of an O, face into the hole, and the cut +/// sides leave those holes open. pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result { let mut faces = vec![]; crate::revolve_faces(path, rule, bounds, options, Some(&mut faces))?; @@ -127,7 +128,7 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo } /// The area-weighted normal of `contours` (Newell's method). -fn newell(contours: &[Vec]) -> V3 { +pub(crate) fn newell(contours: &[Vec]) -> V3 { let mut n = V3::default(); for c in contours { for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { @@ -210,7 +211,7 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> { /// The triangles covering one face: `contours` (outlines one way round, holes the other) on the /// plane across `normal` (its Newell normal). -fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result, String> { +pub(crate) fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result, String> { // Cut the face on the coordinate plane it is least slanted to, turned so outlines run // counterclockwise. let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs()); diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 76f9b04ecc..8b2ec0ae75 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -239,7 +239,7 @@ fn a_revolved_profile_is_a_closed_cylinder() { } #[test] -fn a_partial_revolve_caps_its_ends_with_sectors() { +fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() { let mut b = BezPath::new(); b.move_to((20.0, 0.0)); b.line_to((20.0, 100.0)); @@ -247,8 +247,12 @@ fn a_partial_revolve_caps_its_ends_with_sectors() { let r = p.bounds().unwrap(); let o = Revolve { angle: 90.0, offset: 10.0, segments: 64, ..Revolve::default() }; let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap(); - let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0); + // The side and the two end sectors, and the two cut sides, each 10 pt from the axis by 100 pt. + let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0) + 2.0 * 10.0 * 100.0; assert!((area(&m) - exact).abs() / exact < 0.01, "{} vs {exact}", area(&m)); + assert!(closed(&m), "the quarter of a cylinder is a closed solid"); + let hollow = revolve_mesh(&p, FillRule::NonZero, r, Revolve { cap_ends: false, ..o }).unwrap(); + assert!(!closed(&hollow)); } #[test] diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index b580ddcd5f..83c9b1dc8b 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -335,11 +335,11 @@ pub fn inflate_shadowed( } /// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces -/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where +/// [`ShadowCaster::revolve`] adds for it with the fill rule of `options`. An error where /// [`crate::revolve`] gives one. pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { let mut kept = vec![]; - let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?; + let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?; let projection = Some(crate::revolve_projection(bounds, options.sanitized())); Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) } diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index 5dba29c480..ace8566816 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -2,6 +2,7 @@ use super::*; mod caps; mod classic; +mod cut_sides; mod lighting; mod multiple_lights; mod profile_limits; diff --git a/crates/three-d/src/tests/cut_sides.rs b/crates/three-d/src/tests/cut_sides.rs new file mode 100644 index 0000000000..9d78da3e9d --- /dev/null +++ b/crates/three-d/src/tests/cut_sides.rs @@ -0,0 +1,235 @@ +use crate::*; +use vectorcraft_geom::Shape; + +/// Swept with Cap on, unshaded and seen from the front. +fn options() -> Revolve { + Revolve { cap_ends: true, shade: false, ..Default::default() } +} + +fn profile(data: &str) -> PathData { + PathData::from_bezpath(&BezPath::from_svg(data).unwrap()) +} + +fn area(face: &Face) -> f64 { + face.path().to_bezpath().area().abs() +} + +/// The faces of the cut sides among `faces`: the flat faces in a plane through the axis, which these +/// tests keep upright. The strips of the swept side lie off the axis, and the endpoint caps across it. +fn cut_sides(faces: &[Face]) -> Vec<&Face> { + faces.iter().filter(|f| !f.cap && f.plane.is_some_and(|p| p.offset.abs() < 1e-6 && p.normal[1].abs() < 1e-9)).collect() +} + +#[test] +fn a_half_turn_closes_both_cut_sides_with_the_region_between_the_profile_and_the_axis() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + // Seen from the front, a half turn's two cut sides both face the viewer: the profile's plane + // to the right of the axis and to its left. + let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in &cuts { + assert!((area(cut) - 40.0 * 80.0).abs() < 1e-6, "{}", area(cut)); + assert!(cut.points.iter().all(|p| (10.0 - 1e-9..=90.0 + 1e-9).contains(&p.y))); + } + assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x >= -1e-9))); + assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x <= 1e-9))); + assert!(faces.windows(2).all(|pair| pair[0].depth <= pair[1].depth)); +} + +#[test] +fn cap_off_full_turns_and_no_turn_leave_the_cut_sides_open() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + for (o, what) in [ + (Revolve { angle: 180.0, cap_ends: false, ..options() }, "hollow"), + (Revolve { angle: 360.0, rotation_x: 90.0, ..options() }, "a full turn"), + (Revolve { angle: 0.0, ..options() }, "no turn"), + ] { + let faces = revolve(&path, bounds, o).unwrap(); + assert!(cut_sides(&faces).is_empty(), "{what}"); + } +} + +#[test] +fn a_closed_profile_closes_its_cut_sides_with_its_area_and_leaves_its_hole_open() { + // A square ring away from the axis, its hole wound the other way. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L30 40 L50 40 L50 20 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() }; + let faces = revolve(&path, bounds, o).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in &cuts { + let outline = cut.outline.as_ref().unwrap(); + assert_eq!(outline.subpaths.len(), 2, "the outline and its hole"); + // Turned 20° about the vertical axis, each side is foreshortened by cos 20°. + let expected = (40.0 * 40.0 - 20.0 * 20.0) * 20f64.to_radians().cos(); + assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut)); + } + // Visibility measures the face with its hole open. + assert!(!visible_faces(&faces).unwrap().is_empty()); +} + +#[test] +fn an_even_odd_hole_wound_with_its_outline_stays_open_in_the_drawn_cut_sides() { + // The hole runs the same way round as the outline, so only the even-odd rule leaves it open. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L50 20 L50 40 L30 40 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, ..options() }; + let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::EvenOdd, ..o }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in cuts { + // The drawn path is filled with the nonzero rule; the hole is in the middle of the side. + let filled = cut.path().to_bezpath(); + assert!(!filled.contains(filled.bounding_box().center())); + assert!((area(cut) - (40.0 * 40.0 - 20.0 * 20.0)).abs() < 1e-6, "{}", area(cut)); + } + // Under the nonzero rule the inner contour fills too: each side is the outer square and the + // inner one drawn over it. + let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::NonZero, ..o }).unwrap(); + let mut areas: Vec = cut_sides(&faces).iter().map(|f| area(f)).collect(); + areas.sort_by(f64::total_cmp); + assert_eq!(areas.len(), 4); + assert!(areas.iter().zip([400.0, 400.0, 1600.0, 1600.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{areas:?}"); +} + +#[test] +fn a_bow_tie_whose_loops_cancel_out_closes_its_cut_sides_with_both_loops() { + // Two triangles of 400 pt² that meet at (40, 30), wound opposite ways. + let path = profile("M20 10 L60 50 L60 10 L20 50 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() }; + let faces = revolve(&path, bounds, o).unwrap(); + let cuts = cut_sides(&faces); + // Each side draws each loop as a face. + assert_eq!(cuts.len(), 4); + let expected = 400.0 * 20f64.to_radians().cos(); + for cut in cuts { + assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut)); + } + let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, rotation_y: 0.0, ..o }).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - 800.0).abs() < 1e-6, "{start}"); +} + +#[test] +fn the_mesh_closes_a_cut_side_that_crosses_itself_with_both_of_its_loops() { + // Loops of 900 pt² and 100 pt² that meet at (50, 40): the mesh covers both, and nothing + // between them. + let path = profile("M20 10 L60 50 L60 30 L20 70 Z"); + let bounds = path.bounds().unwrap(); + let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, offset: 10.0, ..options() }).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - 1000.0).abs() < 1e-6, "{start}"); +} + +#[test] +fn visibility_keeps_both_of_two_separate_regions_wound_opposite_ways() { + let path = profile("M20 10 L30 10 L30 50 L20 50 Z M40 10 L40 50 L50 50 L50 10 Z"); + let bounds = path.bounds().unwrap(); + // Seen from behind, the half turn's walls are behind both cut sides, which nothing covers. Seen + // from the front, the walls the outer square sweeps cover both sides completely. + for (rotation_y, all) in [(180.0, 4.0 * 10.0 * 40.0), (0.0, 0.0)] { + let faces = revolve(&path, bounds, Revolve { angle: 180.0, offset: 10.0, rotation_y, ..options() }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 4, "a face for each region on each side"); + let mut depths: Vec = cuts.iter().map(|f| f.depth).collect(); + depths.dedup(); + let visible = visible_faces(&faces).unwrap(); + let shown: f64 = visible + .iter() + .filter(|v| depths.contains(&v.depth)) + .flat_map(|v| v.path.subpaths.iter().map(|s| PathData::new(vec![s.clone()]).to_bezpath().area().abs())) + .sum(); + assert!((shown - all).abs() < 1e-6, "turned {rotation_y}°, the cut sides show {shown}, not {all}"); + } +} + +#[test] +fn every_open_contour_of_a_compound_profile_closes_its_own_region_on_each_side() { + let path = profile("M40 10 L40 40 M20 60 L50 90"); + let bounds = Rect::new(0.0, 10.0, 50.0, 90.0); + let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap(); + let mut areas: Vec = cut_sides(&faces).iter().map(|f| area(f)).collect(); + areas.sort_by(f64::total_cmp); + // The trapezoid between the slanted line and the axis, (20 + 50) / 2 × 30, and 40 × 30. + let expected = [35.0 * 30.0, 35.0 * 30.0, 40.0 * 30.0, 40.0 * 30.0]; + assert_eq!(areas.len(), 4); + assert!(areas.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-6), "{areas:?}"); +} + +#[test] +fn a_cut_side_seen_edge_on_is_not_drawn() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + // A quarter turn ends in the plane through the axis toward the viewer. + let faces = revolve(&path, bounds, Revolve { angle: 90.0, ..options() }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 1); + assert!((area(cuts[0]) - 40.0 * 80.0).abs() < 1e-6); +} + +#[test] +fn cut_sides_are_shaded_evenly_by_their_plane() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + let o = Revolve { angle: 180.0, shade: true, rotation_y: 30.0, ..options() }; + let faces = revolve(&path, bounds, o).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in cuts { + assert!(cut.gradient.is_none(), "a flat face is shaded evenly"); + assert!(cut.plane.is_some()); + assert!((0.0..=1.0).contains(&cut.brightness)); + // Both sides lie in the plane through the axis turned 30°, whose normal faces the viewer. + let n = cut.normal; + assert!((n[0].abs() - 30f64.to_radians().sin()).abs() < 1e-9 && n[2] > 0.0, "{n:?}"); + } +} + +/// The area of the triangles of `mesh` whose normal is `normal`. +fn area_facing(mesh: &Mesh, normal: [f64; 3]) -> f64 { + mesh.triangles + .iter() + .filter(|t| t.iter().all(|&i| mesh.normals[i as usize].iter().zip(normal).all(|(a, b)| (a - b).abs() < 1e-9))) + .map(|t| { + let [a, b, c] = t.map(|i| mesh.positions[i as usize]); + let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]); + let x = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + (x[0] * x[0] + x[1] * x[1] + x[2] * x[2]).sqrt() / 2.0 + }) + .sum() +} + +#[test] +fn the_mesh_closes_both_cut_sides_and_leaves_holes_open_under_either_fill_rule() { + let ring = "M20 10 L60 10 L60 50 L20 50 Z"; + let o = Revolve { angle: 90.0, offset: 10.0, ..options() }; + let expected = 40.0 * 40.0 - 20.0 * 20.0; + // The hole wound against the outline, and wound with it under even-odd. + for (hole, rule) in [("M30 20 L30 40 L50 40 L50 20 Z", FillRule::NonZero), ("M30 20 L50 20 L50 40 L30 40 Z", FillRule::EvenOdd)] { + let path = profile(&format!("{ring} {hole}")); + let mesh = revolve_mesh(&path, rule, path.bounds().unwrap(), o).unwrap(); + // The start faces back, against the sweep; a quarter turn ends facing left, along it. + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + let end = area_facing(&mesh, [-1.0, 0.0, 0.0]); + assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}"); + assert!((end - expected).abs() < 1e-6, "{rule:?}: {end}"); + } + let path = profile(ring); + let hollow = revolve_mesh(&path, FillRule::NonZero, path.bounds().unwrap(), Revolve { cap_ends: false, ..o }).unwrap(); + assert_eq!(area_facing(&hollow, [0.0, 0.0, -1.0]), 0.0); +} + +#[test] +fn the_mesh_cut_sides_face_out_of_a_sweep_on_the_left_of_its_axis() { + // The axis is 40 pt to the right of the line, which sweeps from the left of the axis to its back. + let path = profile("M40 10 L40 90"); + let o = Revolve { angle: 90.0, edge: Edge::Right, offset: 40.0, ..options() }; + let mesh = revolve_mesh(&path, FillRule::NonZero, Rect::new(40.0, 10.0, 40.0, 90.0), o).unwrap(); + assert!((area_facing(&mesh, [0.0, 0.0, 1.0]) - 40.0 * 80.0).abs() < 1e-6); + assert!((area_facing(&mesh, [1.0, 0.0, 0.0]) - 40.0 * 80.0).abs() < 1e-6); +} diff --git a/crates/three-d/src/visibility.rs b/crates/three-d/src/visibility.rs index 3ed491ae10..71c5af62c3 100644 --- a/crates/three-d/src/visibility.rs +++ b/crates/three-d/src/visibility.rs @@ -199,7 +199,8 @@ pub fn visible_faces(faces: &[Face]) -> Result, String> { }) { return Err("Revolve visibility requires finite projected faces".into()); } - let all = faces.iter().flat_map(|f| &f.points).copied().collect::>(); + let outlines = faces.iter().filter_map(|f| f.outline.as_ref()).flat_map(|o| o.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p))); + let all = faces.iter().flat_map(|f| f.points.iter().copied()).chain(outlines).collect::>(); let total = bounds(&all); if total.width() <= 0.0 || total.height() <= 0.0 { return Ok(vec![]); @@ -222,7 +223,9 @@ pub fn visible_faces(faces: &[Face]) -> Result, String> { if pieces.is_empty() { continue; } - let source_bounds = bounds(&face.points); + // A face drawn as several contours, such as a cut side of a partial sweep, reaches past its + // own polygon: look for covers over all of its pieces. + let source_bounds = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)).unwrap_or_else(|| bounds(&face.points)); let mut fragments: Vec<_> = pieces.iter().map(|p| p.points.clone()).collect(); let mut clipped = false; 'covers: for tile in index.tiles(source_bounds) { diff --git a/crates/three-d/src/visibility_parts.rs b/crates/three-d/src/visibility_parts.rs index 2a14435025..ebf1d47b4b 100644 --- a/crates/three-d/src/visibility_parts.rs +++ b/crates/three-d/src/visibility_parts.rs @@ -91,6 +91,22 @@ fn triangulate(mut points: Vec, epsilon: f64, work: &mut usize, depth: us Ok(out) } +/// Triangles covering a flat face drawn as several straight-edged contours, such as a cut side of a +/// partial Revolve whose profile has holes: outlines one way round and holes the other, the holes +/// left uncovered. The work is checked before the face is cut, at four times its corners squared. +fn with_holes(outline: &vectorcraft_geom::PathData, epsilon: f64, work: &mut usize) -> Result>, String> { + const LIMIT: &str = "Revolve visibility exceeds its geometry work limit"; + let rings: Vec> = outline.subpaths.iter().map(|s| s.anchors.iter().map(|a| crate::V3(a.p.x, a.p.y, 0.0)).collect()).collect(); + let corners: usize = rings.iter().map(Vec::len).sum(); + *work = work.saturating_add(corners.saturating_mul(corners).saturating_mul(4)); + if *work > MAX_WORK { + return Err(LIMIT.into()); + } + let mut spent = 0; + let triangles = crate::mesh::triangulate(&rings, crate::mesh::newell(&rings), &mut spent)?; + Ok(triangles.into_iter().map(|t| clean(t.iter().map(|v| Point::new(v.0, v.1)).collect(), epsilon)).filter(|t| !t.is_empty()).collect()) +} + pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result>, String> { if let Some(strips) = &face.visibility_pieces { let mut out = vec![]; @@ -99,6 +115,9 @@ pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result 1) { + return with_holes(outline, epsilon, work); + } if !face.cap { return triangulate(clean(face.points.clone(), epsilon), epsilon, work, 0); } diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a547c8fbb7..e213291c5a 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -118,7 +118,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) number(ui, d, "offset", tl!("Offset"), (0.0, 100000.0), "", 1, Some(unit)); ui.horizontal(|ui| { let cap = flag(d, "cap", true); - let tip = tl!("Close the circular ends of open profiles. Partial sweeps keep their cut sides open."); + let tip = tl!("Close the circular ends of open profiles. Partial sweeps also close their cut sides."); if widgets::check3_tip(ui, c3("Cap"), cap, true, tip) { d.fields.insert("cap".into(), json!(cap != Some(true))); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8534505172..21603afe18 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5817,7 +5817,7 @@ theme Appearance Външен вид @msg Unknown dimension orientation Непозната ориентация на размера @msg Unknown dimension style Непознат стил на размера @msg Unknown unit Непозната единица - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни остават отворени. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни също се затварят. # Strings added with Drop Shadow Darkness, Isolate Selected Object, Pencil Keep selected, Sample Color from Screen, Tritanopia proofing, Panels Except Tools and Control Darkness Затъмняване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1a1b1bdbff..93a65d0ddf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5867,7 +5867,7 @@ mark-style Japanese Japanski @msg Unknown dimension orientation Nepoznata orijentacija kote @msg Unknown dimension style Nepoznat stil kote @msg Unknown unit Nepoznata jedinica - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zadržavaju otvorene rezane strane. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zatvaraju i svoje rezane strane. @msg span must be "object" or "selection", got {v} span mora biti "object" ili "selection", dobiveno {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" postavlja `gradient`, a ne uzorak boje @msg span: "selection" places a gradient: give `gradient` span: "selection" postavlja gradijent: navedite `gradient` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a7fcccfe2f..7f13dfde9a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -753,7 +753,7 @@ antiAlias Sharp Nítid Close Panel Tanca el panell Close Path Tanca el traçat Close paths when ends are within: Tanca els traçats quan els extrems siguin a menys de: - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Tanca els extrems circulars dels perfils oberts. Els escombrats parcials mantenen oberts els costats tallats. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Tanca els extrems circulars dels perfils oberts. Els escombrats parcials també tanquen els costats tallats. Closed Tancat Closing bracket with no opening one Delimitador de tancament sense un d’obertura Clumped Agrupat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index acab417f65..47bf5b79f7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6176,7 +6176,7 @@ mark-style Japanese Japonské @msg Unknown dimension style Neznámý styl kóty @msg Unknown unit Neznámá jednotka # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Uzavře kruhové konce otevřených profilů. Boční řezy částečného otočení zůstávají otevřené. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Uzavře kruhové konce otevřených profilů. Boční řezy částečného otočení se také uzavřou. @msg span must be "object" or "selection", got {v} span musí být "object" nebo "selection", ne {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" umísťuje `gradient`, ne vzorník @msg span: "selection" places a gradient: give `gradient` span: "selection" umísťuje přechod: zadejte `gradient` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9e74a00a64..5ea9342e1e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6194,7 +6194,7 @@ mark-style Japanese Japansk @msg Unknown dimension orientation Ukendt målretning @msg Unknown dimension style Ukendt målstil @msg Unknown unit Ukendt enhed - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Luk de runde ender af åbne profiler. Delvise omdrejninger beholder deres skårne sider åbne. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Luk de runde ender af åbne profiler. Delvise omdrejninger lukker også deres skårne sider. Darkness Mørke Isolate Selected Object Isolér markeret objekt Keep selected Behold markeret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 527b1c89e8..e8e19bff9d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5758,7 +5758,7 @@ effect Soft Weich @msg Unknown dimension style Unbekannter Bemaßungsstil @msg Unknown unit Unbekannte Einheit # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Schließt die kreisförmigen Enden offener Profile. Bei einer Teildrehung bleiben die Schnittseiten offen. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Schließt die kreisförmigen Enden offener Profile. Bei einer Teildrehung werden auch die Schnittseiten geschlossen. Distance Abstand @msg span must be "object" or "selection", got {v} span muss "object" oder "selection" sein, nicht {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" platziert einen `gradient`, kein Farbfeld diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a7dd7ed926..4f6337aed7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6030,7 +6030,7 @@ effect Points Σημεία By Object Ανά αντικείμενο Check an artboard to save. Επιλέξτε έναν πίνακα σχεδίασης για αποθήκευση. Clear All Εκκαθάριση όλων - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Κλείσιμο των κυκλικών άκρων των ανοιχτών προφίλ. Οι μερικές περιστροφές κρατούν ανοιχτές τις πλευρές τομής τους. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Κλείσιμο των κυκλικών άκρων των ανοιχτών προφίλ. Οι μερικές περιστροφές κλείνουν επίσης τις πλευρές τομής τους. Color Panel Options Επιλογές πίνακα χρώματος Color blindness – Tritanopia-type Αχρωματοψία – τύπου τριτανοπίας Create Dimension Δημιουργία διάστασης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cf3d0bbf96..220e2d11f9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6120,7 +6120,7 @@ mark-style Japanese Japonesas @msg Unknown dimension style Estilo de cota desconocido @msg Unknown unit Unidad desconocida # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Cierra los extremos circulares de los perfiles abiertos. Los giros parciales mantienen abiertos sus lados de corte. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Cierra los extremos circulares de los perfiles abiertos. Los giros parciales también cierran sus lados de corte. Distance Distancia @msg span must be "object" or "selection", got {v} span debe ser "object" o "selection", no {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" coloca un `gradient`, no una muestra diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 24b7858169..8a8413199c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6041,7 +6041,7 @@ mark-style Japanese Japanilainen By Object Objektin mukaan Check an artboard to save. Valitse tallennettava piirtoalusta. Clear All Tyhjennä kaikki - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sulje avointen profiilien pyöreät päät. Osittaiset pyöräytykset jättävät leikkauspintansa auki. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Sulje avointen profiilien pyöreät päät. Osittaiset pyöräytykset sulkevat myös leikkauspintansa. Color Panel Options Väri-paneelin asetukset Color blindness – Tritanopia-type Värisokeus – tritanopia Create Dimension Luo mitta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8303bbae94..75f10a3dfd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6171,7 +6171,7 @@ theme Appearance Apparence @msg Unknown dimension style Style de cote inconnu @msg Unknown unit Unité inconnue # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Ferme les extrémités circulaires des profils ouverts. Les rotations partielles conservent leurs faces de coupe ouvertes. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Ferme les extrémités circulaires des profils ouverts. Les rotations partielles ferment aussi leurs faces de coupe. @msg span must be "object" or "selection", got {v} span doit être "object" ou "selection", pas {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" place un `gradient`, pas une nuance @msg span: "selection" places a gradient: give `gradient` span: "selection" place un dégradé : indiquez `gradient` diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 551c39d1f8..341c8aeead 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -601,7 +601,7 @@ Close Path… પાથ બંધ કરો… Close or Join બંધ કરો અથવા જોડો Close paths when ends are within: છેડા આ અંતરમાં હોય ત્યારે પાથ બંધ કરો: - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ખુલ્લી પ્રોફાઇલના ગોળ છેડા બંધ કરો. આંશિક સ્વીપ તેમની કાપેલી બાજુઓ ખુલ્લી રાખે છે. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. ખુલ્લી પ્રોફાઇલના ગોળ છેડા બંધ કરો. આંશિક સ્વીપ તેમની કાપેલી બાજુઓ પણ બંધ કરે છે. Closing bracket with no opening one ખુલતા કૌંસ વગરનો બંધ થતો કૌંસ Coincidence: સંયોગ: Collapse Panel Group પેનલ ગ્રૂપ સંકોચો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6a135dccaa..102ad3f05a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -879,7 +879,7 @@ antiAlias Sharp शार्प Close Path: बंद पाथ: Close Path… बंद पाथ… Close paths when ends are within: जब समाप्त होता है तो बंद पाथ भीतर होते हैं: - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड खुली रहती हैं। + Close the circular ends of open profiles. Partial sweeps also close their cut sides. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड भी बंद होती हैं। Closed बंद Closing bracket with no opening one बंद करने वाला ब्रैकेट, जिसका कोई खोलने वाला ब्रैकेट नहीं है Clumped गुच्छेदार diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 09a9797d3e..1aceaa1300 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6158,7 +6158,7 @@ imageTrace Outline Körvonal @msg Unknown dimension style Ismeretlen méretezési stílus @msg Unknown unit Ismeretlen mértékegység # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Nyitott profilok kör alakú végeinek lezárása. Részleges körforgatás esetén a vágott oldalak nyitva maradnak. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Nyitott profilok kör alakú végeinek lezárása. Részleges körforgatás esetén a vágott oldalak is lezáródnak. Distance Távolság @msg span must be "object" or "selection", got {v} a span értéke "object" vagy "selection" lehet, nem {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" egy `gradient` értéket helyez el, nem színmintát diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 32283beade..7421f0f607 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5584,7 +5584,7 @@ mark-style Japanese Jepang @msg Unknown dimension orientation Orientasi dimensi tidak dikenal @msg Unknown dimension style Gaya dimensi tidak dikenal @msg Unknown unit Satuan tidak dikenal - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Menutup ujung melingkar profil terbuka. Sapuan parsial mempertahankan sisi potongannya tetap terbuka. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Menutup ujung melingkar profil terbuka. Sapuan parsial juga menutup sisi potongannya. Darkness Kegelapan Isolate Selected Object Isolasikan objek terpilih Keep selected Tetap terseleksi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2c8cc708dc..b94aa6cc34 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5795,7 +5795,7 @@ lighting Light Luce @msg Unknown dimension style Stile di quota sconosciuto @msg Unknown unit Unità sconosciuta # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Chiude le estremità circolari dei profili aperti. Le rotazioni parziali mantengono aperti i lati di taglio. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Chiude le estremità circolari dei profili aperti. Le rotazioni parziali chiudono anche i lati di taglio. Distance Distanza @msg span must be "object" or "selection", got {v} span deve essere "object" o "selection", non {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" posiziona un `gradient`, non un campione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index bd03123f11..8e7db179c3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5839,7 +5839,7 @@ lighting Light ライト @msg Unknown dimension style 寸法のスタイルが不明です @msg Unknown unit 単位が不明です # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 開いたプロファイルの円形の端を閉じます。部分的な回転では切断面は開いたままです。 + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 開いたプロファイルの円形の端を閉じます。部分的な回転では切断面も閉じます。 Distance 距離 @msg span must be "object" or "selection", got {v} span は "object" または "selection" で指定してください ({v} は指定できません) @msg span: "selection" places a `gradient`, not a swatch span: "selection" は `gradient` を配置します。スウォッチは配置できません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 54445dffb9..a3616ad36b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5804,7 +5804,7 @@ imageTrace Outline კონტური @msg Unknown dimension orientation ზომის უცნობი ორიენტაცია @msg Unknown dimension style ზომის უცნობი სტილი @msg Unknown unit უცნობი ერთეული - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეები ღია რჩება. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეებიც იხურება. Distance მანძილი # Upstream sync 2026-10-16 (2): Smart Blur modes, Layers panel filter, Color panel options, templates, PostScript files. Mode რეჟიმი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2f91553467..d1a182b4b6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5756,7 +5756,7 @@ lighting Light 광원 @msg Unknown dimension style 알 수 없는 치수 스타일 @msg Unknown unit 알 수 없는 단위 # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 열린 프로파일의 원형 끝을 닫습니다. 부분 회전에서는 절단 측면이 열린 상태로 유지됩니다. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 열린 프로파일의 원형 끝을 닫습니다. 부분 회전에서는 절단 측면도 닫힙니다. Distance 거리 @msg span must be "object" or "selection", got {v} span은 "object" 또는 "selection"이어야 합니다. {v}은(는) 사용할 수 없습니다 @msg span: "selection" places a `gradient`, not a swatch span: "selection"은 `gradient`를 배치합니다. 견본은 배치할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b8eede91bd..2a0121465c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7988,7 +7988,7 @@ mark-style Japanese Japans @msg Unknown dimension orientation Onbekende maatlijnrichting @msg Unknown dimension style Onbekende maatlijnstijl @msg Unknown unit Onbekende eenheid - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen houden hun afgesneden zijden open. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen sluiten ook hun afgesneden zijden. Darkness Donkerte Isolate Selected Object Geselecteerd object isoleren Keep selected Geselecteerd houden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b846ae308c..7414b00635 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6029,7 +6029,7 @@ mark-style Japanese Japońskie @msg Unknown dimension style Nieznany styl wymiaru @msg Unknown unit Nieznana jednostka # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zamknij okrągłe końce otwartych profili. Przy częściowym obrocie boki przekroju pozostają otwarte. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Zamknij okrągłe końce otwartych profili. Przy częściowym obrocie boki przekroju również zostają zamknięte. Distance Odległość @msg span must be "object" or "selection", got {v} span musi mieć wartość "object" lub "selection", a nie {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" umieszcza `gradient`, a nie próbkę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9b74bba16e..fc13f816d0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6057,7 +6057,7 @@ mark-style Japanese Japonesas Create Dimension Criar Cota Update Dimensions Atualizar Cotas # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Fecha as extremidades circulares dos perfis abertos. Giros parciais mantêm as faces de corte abertas. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Fecha as extremidades circulares dos perfis abertos. Giros parciais também fecham as faces de corte. @msg span must be "object" or "selection", got {v} span deve ser "object" ou "selection", não {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" posiciona um `gradient`, não uma amostra @msg span: "selection" places a gradient: give `gradient` span: "selection" posiciona um degradê: informe `gradient` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cd904e1224..cde27b031a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5782,7 +5782,7 @@ lighting Light Свет @msg Unknown dimension style Неизвестный стиль размера @msg Unknown unit Неизвестная единица # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Закрывает круглые торцы открытых профилей. При неполном вращении боковые срезы остаются открытыми. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Закрывает круглые торцы открытых профилей. При неполном вращении боковые срезы тоже закрываются. Distance Расстояние @msg span must be "object" or "selection", got {v} span должен быть "object" или "selection", а не {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" размещает `gradient`, а не образец diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5d20472e7b..f2c808db5c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6025,7 +6025,7 @@ theme Appearance Utseende By Object Efter objekt Check an artboard to save. Markera en rityta som ska sparas. Clear All Rensa alla - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Stäng de cirkulära ändarna på öppna profiler. Partiella svep behåller sina snittsidor öppna. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Stäng de cirkulära ändarna på öppna profiler. Partiella svep stänger även sina snittsidor. Color Panel Options Alternativ för panelen Färg Color blindness – Tritanopia-type Färgblindhet – tritanopi Create Dimension Skapa mått diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9bdf0c5036..7e4b793b95 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5939,7 +5939,7 @@ theme Appearance Görünüm @msg Unknown dimension orientation Bilinmeyen boyut yönü @msg Unknown dimension style Bilinmeyen boyut stili @msg Unknown unit Bilinmeyen birim - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını açık tutar. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını da kapatır. @msg span must be "object" or "selection", got {v} span "object" veya "selection" olmalıdır, {v} değil @msg span: "selection" places a `gradient`, not a swatch span: "selection" bir renk örneği değil, bir `gradient` yerleştirir @msg span: "selection" places a gradient: give `gradient` span: "selection" bir degrade yerleştirir: `gradient` verin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7395cdec64..7e5caf0332 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5775,7 +5775,7 @@ lighting Light Світло @msg Unknown dimension style Невідомий стиль розміру @msg Unknown unit Невідома одиниця # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Закриває круглі торці відкритих профілів. За неповного обертання бічні зрізи залишаються відкритими. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Закриває круглі торці відкритих профілів. За неповного обертання бічні зрізи теж закриваються. Distance Відстань @msg span must be "object" or "selection", got {v} span має бути "object" або "selection", а не {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" розміщує `gradient`, а не зразок diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8df980ee37..38d3ffa42f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5780,7 +5780,7 @@ theme Appearance Giao diện @msg Unknown dimension style Kiểu kích thước không xác định @msg Unknown unit Đơn vị không xác định # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Đóng các đầu tròn của biên dạng mở. Khi xoay một phần, các mặt cắt bên vẫn mở. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Đóng các đầu tròn của biên dạng mở. Khi xoay một phần, các mặt cắt bên cũng được đóng. Distance Khoảng cách @msg span must be "object" or "selection", got {v} span phải là "object" hoặc "selection", không phải {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" đặt một `gradient`, không phải mẫu màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ca19647856..2551462f17 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6022,7 +6022,7 @@ lighting Light 光源 @msg Choose a circle or a perfect arc 请选择圆或标准圆弧 @msg Choose a precision from 0 to 6 请选择 0 到 6 之间的精度 # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 封闭开放轮廓的圆形端部。部分旋转的切割侧面保持开放。 + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 封闭开放轮廓的圆形端部。部分旋转的切割侧面也会封闭。 Distance 距离 Make Image Dynamic 使图像动态化 Import Data Sets… 导入数据集… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 748ff1848b..241374bc4c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5856,7 +5856,7 @@ lighting Light 光源 X: X: Y: Y: # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 封閉開放輪廓的圓形端部。部分旋轉的切割側面保持開放。 + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 封閉開放輪廓的圓形端部。部分旋轉的切割側面也會封閉。 Distance 距離 Make Image Dynamic 使影像動態化 Import Data Sets… 匯入資料集… diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 342a5171b6..0ce8dc778f 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -178,7 +178,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Item | Ours | |---|---| -| 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) | +| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, 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, 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)); Map Art: none | diff --git a/docs/mcp.md b/docs/mcp.md index 494b4f4ef6..88f113e58c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4063,9 +4063,12 @@ Parameters: `angle` (degrees, 0..360, default 360), `offset` (points, 0..100000, default 0), `ambient` (Ambient Light, 0..200%, default 25; an earlier `lightAzimuth` and `lightElevation` are read as the same light), `cap` (boolean, default true), and `expandVisibleOnly` (boolean, default true). A vertical-line profile needs a positive offset to have a radius. `cap` closes each circular endpoint of an open profile with one curved, uniformly shaded -vector path. Body faces share that curved rim. Partial sweeps use sectors and leave their angular -cut sides open. Closed or coincident-end profiles are unchanged. -Missing `cap` enables caps; set it to false for open endpoints. Shaded Revolve surfaces automatically interpolate curved-surface lighting with vector gradients while preserving profile corners and flat caps. There is no separate smoothing parameter. `shade: false` disables all lighting. Visibility of intersecting surfaces is approximate. +vector path. Body faces share that curved rim. Partial sweeps use sectors, and `cap` also closes their two +angular cut sides with flat faces: the region between each open subpath and the axis and the area of each closed +subpath, one face for each region. A closed subpath that walls a hole under the object's fill rule leaves that +hole open. +Exported 3D meshes include the cut sides. +Missing `cap` enables caps; set it to false for open endpoints and open cut sides (hollow). Shaded Revolve surfaces automatically interpolate curved-surface lighting with vector gradients while preserving profile corners and flat caps. There is no separate smoothing parameter. `shade: false` disables all lighting. Visibility of intersecting surfaces is approximate. `lights` is null by default, retaining the earlier single-light controls. Set an array of one to ten objects to replace that light: `{color: "#rrggbb", intensity: 0..100, rotation: -180..180, height: 0..90, softness: 0..100, behind: bool}`. Defaults per light are white, 80%, 125.26 degrees, 30 degrees, 0%, false. Omitted fields use defaults; unknown nested keys and malformed lists are refused before mutation. `ambient` is shared and counted once. Set `lights: null` to restore the earlier controls. The list is saved in the native file and survives preview, undo and expansion. ```json @@ -4258,7 +4261,7 @@ an unknown surface or shading color is refused with an error and the document is `effect.apply {effect: "threeD.classicRevolve", params: {...}, ids?, item?}` is Effect › 3D and Materials › 3D (Classic) › Revolve (Classic)…. It sweeps the profile round a vertical axis as `threeD.revolve` does, at 64 segments for a full turn, and draws every face, back to front, with the classic surfaces. Parameters: `angle` (degrees, -0..360, default 360), `cap` (true closes the profile's open ends, false leaves the surface hollow), `offset` (points, +0..360, default 360), `cap` (true closes the profile's open ends and a partial sweep's cut sides, false leaves the surface hollow), `offset` (points, 0..1000, default 0; the axis's distance from the profile, so a value above 0 makes a ring), `edge` (`left`, the default, or `right`: the edge of the profile's bounds the axis is at), `rotationX/Y/Z` and `perspectiveAngle` as above, and `surface`, the lights, `ambient`, `highlightIntensity`, `highlightSize`, `blendSteps`, `shadingColor` and diff --git a/docs/revolve.md b/docs/revolve.md index 7e80ee3e24..99165377d9 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -75,10 +75,17 @@ orthographic view); a partial turn produces a sector. Body faces share the same so no triangle patches interrupt the cap edge. Caps share the surface's rotation, perspective and paint, and appear in preview, SVG/PDF export and Expand Appearance. The checkbox has a reset dot and is included in Reset all. -An endpoint on the axis needs no cap. Closed profiles and open profiles whose endpoints coincide -keep their existing geometry. Each open subpath of a compound profile is capped independently. -A partial revolve adds only the swept sector at each endpoint; the angular cut sides remain open. -This option does not make intersecting or compound profiles into a watertight solid. +An endpoint on the axis needs no cap. Each open subpath of a compound profile is capped independently. + +With an Angle below 360°, Cap also closes the two angular cut sides, so the object appears solid; with Cap +off it is hollow ([Revolve options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). +Each cut side is flat and uniformly shaded, and is drawn in depth order with the rest of the surface. It covers the +region between each open subpath and the axis, and the area each closed subpath encloses, with one face for each +region. A closed subpath that walls a hole under the object's fill rule leaves that hole open in the face of the +region around it, and the other regions are filled. A self-intersecting subpath fills what the nonzero rule fills, +with one face for each loop it encloses; this is VectorCraft's own rule. A cut side seen edge on is not drawn. +The cut sides appear in preview, SVG/PDF export, Expand Appearance, Expand as Wireframes, Revolve (Classic) and +exported 3D meshes. Cap does not make intersecting profiles into a watertight solid. In **Advanced**, **Keep visible surfaces only when expanding** is on by default. Expansion removes completely covered faces and trims partially covered ones using the current rotation and perspective. @@ -98,12 +105,12 @@ with the standard command. - Lighting offers Standard, Diffuse, Top Left and Right, using the [shared original rigs](three-d.md#presets). Other effective settings show Custom; changing the view does not change the recognized lighting preset. - Paths, compound paths, type, clipping groups, blends, symbol instances, and groups or layers of them. A clipping group, a blend or a symbol instance sweeps the art it shows about one axis, as described in [three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances). Images must be traced first with Object › Image Trace › Make, and other live objects expanded. -- Open profiles have circular end caps by default; turning Cap off keeps them open. Partial-sweep angular cut sides remain open. Closed profile boundaries are swept as provided. +- Open profiles have circular end caps by default, and a partial sweep closes its angular cut sides; turning Cap off keeps both open. Closed profile boundaries are swept as provided. - One Revolve per source object. Edit its options rather than applying another. - Object-level Revolve uses the top visible fill, falling back to a stroke. Per-item Revolve uses that item's paint. - Smooth diffuse shading, one to ten directional lights, no textures, cast shadows or physical materials. Smooth shading interpolates lighting in projected triangles; it does not smooth the silhouette or add specular highlights. - Faces are drawn back to front by the depths of their centers. When that order draws the nearer of two overlapping faces of a surface first, every pair of overlapping faces goes in the order of their depths at the middle of where they overlap; the sort compares at most 4,000,000 pairs (VectorCraft's own limit), and the pairs past that keep the depths of their centers. Caps facing the camera cover their rim seams; a cap facing away is drawn behind the body except where it is nearer than a body face it overlaps. Intersecting profiles can have incorrect visibility. -- Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. +- Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit, and each region of a cut side counts as one face. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. - Axis, bounds and ordinary selection handles continue to refer to the editable 2D source profile. - Extrude & Bevel, Inflate and Rotate are described in [three-d.md](three-d.md). Materials remain unimplemented. diff --git a/docs/three-d.md b/docs/three-d.md index 871b28772c..4adc5716ee 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -528,7 +528,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. across the shape) is refused because the 3D surface is too complex; a closed path of 65,536 points round a circle builds. - **3D (Classic)**: Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) are built, with their surface - types and blend steps. Revolve (Classic) sweeps the surface Revolve sweeps, at 64 segments for a full turn, and draws + types and blend steps. Revolve (Classic) sweeps the surface Revolve sweeps, with Cap closing a partial sweep's cut + sides ([revolve.md](revolve.md)), at 64 segments for a full turn, and draws every face back to front, so it has no Draw Hidden Faces setting. Rotate (Classic) turns the plane Rotate turns, seen from either side, with the No Shading and Diffuse surfaces only. The track cube, map art, Turntable and 3D export are separate, unbuilt items. From b484a0d1bf9ee2c49d385f187a7475b71678f6b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:10:44 -0800 Subject: [PATCH 08/50] Expand Appearance: limit the raster images one expansion makes Each image of raster effects that Expand Appearance makes, at the top level, for group members and for symbol instances nested in expanded art, now draws from one budget of 1,024 images and 256 megapixels per command. The pixels are counted before the image is made, from the same region and resolution the image uses. An object or instance whose image would go past the budget keeps its raster effects and stays as it is. The result reports how many with `rasterLeft` and a warning, and when nothing else expands the command fails with that message. A legacy .ai save notes it the same way. --- crates/engine/src/cmd/effectcmd.rs | 130 ++++++++++++++++------ crates/engine/src/cmd/effectcmd/tests.rs | 25 +++++ crates/engine/src/cmd/fileio/legacy_ai.rs | 13 ++- crates/engine/src/cmd/rasterfx.rs | 126 +++++++++++++++------ crates/engine/src/tests/expand.rs | 40 +++++++ 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 + docs/mcp.md | 4 + 30 files changed, 291 insertions(+), 71 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 308305fe04..cafe5daa23 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -960,13 +960,62 @@ fn is_container(n: &Node) -> bool { /// all paint below it (shadows and outer glows: the image then holds just them). A group's or /// layer's image leaves out its members' raster effects, which are expanded with them. `None` /// when it has none. -fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { +/// `Err` when that image would take `budget` past its limits: the object then stays as it is. +fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result, OverBudget> { let fx = rasterfx::raster_fx(n); if fx.is_empty() { - return None; + return Ok(None); } let below = fx.iter().all(effects::RasterFx::is_below); - Some((rasterfx::raster_image(d, n, below, true)?, below)) + let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?; + let image = rasterfx::raster_image(d, n, below, true); + if image.is_none() { + // No image was made: it takes nothing from the budget. + budget.images += 1; + budget.pixels += pixels; + } + Ok(image.map(|image| (image, below))) +} + +/// The most images of raster effects one Expand Appearance makes. +const MAX_RASTER_IMAGES: u32 = 1_024; + +/// The most pixels the images of raster effects one Expand Appearance makes hold in all. +const MAX_RASTER_PIXELS: u64 = 256_000_000; + +/// The note when objects keep their raster effects because their images would take an Expand +/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`]. +pub(crate) const RASTER_EFFECTS_LEFT: &str = + "some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all"; + +/// An image of raster effects that would take a [`RasterBudget`] past its limits. +#[derive(Debug)] +struct OverBudget; + +/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the +/// objects whose raster effects it left as they are because their images would go past them. +pub(crate) struct RasterBudget { + images: u32, + pixels: u64, + pub(crate) left: usize, +} + +impl RasterBudget { + pub(crate) fn new() -> Self { + Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 } + } + + /// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return + /// them; `Err`, with its object counted in `left`, when it would go past what is left. + fn take(&mut self, pixels: u64) -> std::result::Result { + if self.images == 0 || pixels > self.pixels { + self.left += 1; + return Err(OverBudget); + } + self.images -= 1; + self.pixels -= pixels; + Ok(pixels) + } } /// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that @@ -982,6 +1031,7 @@ fn expand_pieces( all: bool, brushes: &[vectorcraft_brush::Brush], stroke_art: effects::StrokeArt, + raster: &mut RasterBudget, ) -> std::collections::HashMap> { let id = m.id; let mut seen = std::collections::HashSet::from([id]); @@ -996,7 +1046,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, raster)); } fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default()); if let Some(listed) = listed { @@ -1010,15 +1060,15 @@ fn expand_pieces( /// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`], /// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in /// that art in turn, so [`expand_pieces`] bakes their effects with the rest. -fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64) { +fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) { for c in m.children_mut().into_iter().flatten() { if !matches!(c.kind, NodeKind::SymbolInstance { .. }) { if c.children().is_some() { - expand_nested_instances(d, Arc::make_mut(c), depth, budget); + expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster); } continue; } - if let Some(a) = expanded_instance(d, c, depth, budget) { + if let Some(a) = expanded_instance(d, c, depth, budget, raster) { *c = Arc::new(a); } } @@ -1031,12 +1081,13 @@ fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: /// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance /// staying as it is, when its active fill and stroke have no such effect, it is more than /// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would -/// take the objects placed so far past `budget`. When the image of its raster effects can't be -/// made, they stay on the art its geometry effects make, and without one it stays as it is. -fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64) -> Option { +/// take the objects placed so far past `budget`, or the image of its raster effects would take +/// `raster` past its limits. When that image can't be made, they stay on the art its geometry +/// effects make, and without one it stays as it is. +fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option { let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None }; - let raster = effects::has_instance_row_raster(c); - if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(raster || effects::has_item_geometry(c)) { + let has_raster = effects::has_instance_row_raster(c); + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) { return None; } let sym = d.symbols.iter().find(|s| s.name == *symbol)?; @@ -1044,9 +1095,9 @@ fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64) if count > *budget { return None; } - *budget -= count; let art = vectorcraft_render::instance_art(&sym.art, c); - let image = if raster { raster_image(d, c) } else { None }; + let image = if has_raster { raster_image(d, c, raster).ok()? } else { None }; + *budget -= count; let mut v = c.clone(); if image.is_some() { rasterfx::strip_raster(&mut v, false); @@ -1058,7 +1109,7 @@ fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64) }; let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art)) .or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?; - expand_nested_instances(d, &mut a, depth + 1, budget); + expand_nested_instances(d, &mut a, depth + 1, budget, raster); if let Some(image) = below { rasterfx::put_below(d, &mut a, image); } @@ -1079,9 +1130,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], raster: &mut RasterBudget) -> 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, &mut listed, raster) { *c = e; } listed @@ -1103,11 +1154,12 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections: /// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and /// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art), /// 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) { +/// transparency. An object whose raster effects' image would take `raster` past its limits stays +/// as it is, with what is inside it. +pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec, raster: &mut RasterBudget) { 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, &mut listed, raster); 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. @@ -1121,7 +1173,13 @@ 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 { +fn expanded_node( + d: &mut Document, + mut n: Node, + brushes: &[vectorcraft_brush::Brush], + out: &mut Vec, + raster: &mut RasterBudget, +) -> Option { let id = n.id; if !expandable(&n) { return None; @@ -1160,7 +1218,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, raster); fresh_ids_listed(d, c, &mut seen, &mut expanded); } else { effects::fresh_ids(d, c, &mut seen); @@ -1183,7 +1241,9 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } return Some(m); } - let image = raster_image(d, &n); + // Raster effects whose image would go past the budget stay: so does the object, with what is + // inside it (a color adjustment already made stays made). + let Ok(image) = raster_image(d, &n, raster) else { return changed.then_some(n) }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = @@ -1201,7 +1261,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, &mut stroke_art, raster); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) @@ -1226,8 +1286,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br .or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None }); outlined.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_nested_instances(d, &mut m, 1, &mut budget, raster); + expand_pieces(d, &mut m, true, brushes, &mut stroke_art, raster); m }) }; @@ -1261,7 +1321,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, out, raster) { *c = Arc::new(e); changed = true; } @@ -1324,6 +1384,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { } let failed = vectorcraft_render::decode_failures(); let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); + let mut raster = RasterBudget::new(); 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. A group whose @@ -1339,7 +1400,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); + expand_node(d, *id, &brushes, &mut out, &mut raster); } for id in &designs { if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) { @@ -1357,6 +1418,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // stays type under a new id takes its frame's place. super::threads::leave_threads(d, &threaded); if out.is_empty() || (kept && d.layers == before.layers) { + if raster.left > 0 { + return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into())); + } return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into())); } super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?; @@ -1364,8 +1428,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { })?; let mut out = json!({ "ids": ids_json(&ids) }); // Raster effects become images rendered from the art. - if let Some(w) = rasterfx::undecoded_warning(failed) { - out["warning"] = json!(w); + let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect(); + if !warnings.is_empty() { + out["warning"] = json!(warnings.join("; ")); + } + if raster.left > 0 { + out["rasterLeft"] = json!(raster.left); } Ok(out) } diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index b3389e190d..f7e7206c57 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1082,3 +1082,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() { let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count(); assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art"); } + +/// The raster budget charges each image its pixels before it is made: an image past what is left +/// is refused and counted, and the object keeps its blur. +#[test] +fn an_image_past_the_pixels_left_stays_unmade() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap(); + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let n = d.node(id).cloned().unwrap(); + let pixels = super::rasterfx::raster_pixels(&d, &n, false, true); + assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}"); + + let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 }; + assert!(super::raster_image(&mut d, &n, &mut budget).is_err()); + assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken"); + + let mut budget = super::RasterBudget { images: 10, pixels, left: 0 }; + let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made"); + let NodeKind::Image(img) = &image.kind else { panic!("not an image") }; + assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size"); + assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0)); + + let mut budget = super::RasterBudget { images: 0, pixels, left: 0 }; + assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left"); +} diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 23168f1e25..028d9fe5a6 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result let one = super::save::artboard_doc(doc, b); let (full, placed) = crate::cmd::place::document::full_documents(&one); let mut d = full.into_owned(); - expand_appearances(&mut d); + if expand_appearances(&mut d) { + note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT); + } if mode == SeeThrough::Flatten { expand_image_patterns(&mut d)?; } @@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result Ok(enc) } -/// Expand Appearance of every layer's art whose appearance the format can't hold. -fn expand_appearances(d: &mut Document) { +/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether +/// objects kept raster effects whose images would go past Expand Appearance's limits. +fn expand_appearances(d: &mut Document) -> bool { let brushes = vectorcraft_brush::library(d); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); let mut out = vec![]; + let mut raster = super::super::effectcmd::RasterBudget::new(); for id in layers { - super::super::effectcmd::expand_node(d, id, &brushes, &mut out); + super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster); } + raster.left > 0 } /// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint, diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index 5f412e080d..aaaef531bf 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 { (doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0) } -/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone -/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its -/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out -/// of the image, which then only holds what the effects add around it (a shadow to go under the -/// vector object). The document's raster effects settings add room around it and finish its pixels. -/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not -/// positive, or when its PNG can't be encoded. -pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option { +/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or +/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints +/// nothing, when the area it covers overflows `f64` or the scale is not positive. +fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> { // What it paints (its members' effects included), and how far its fills' and strokes' raster // effects reach beyond that. - let b = vectorcraft_render::painted_bounds(out, whole)?; - let look = out.raster_effects.clone(); - let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around; + let b = vectorcraft_render::painted_bounds(d, whole)?; + let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around; let b = b.inflate(reach, reach); // An area too large for f64 gives a zero scale and an image transform that is not finite. let area = b.width() * b.height(); @@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N return None; } let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + Some((region, scale)) +} + +/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone +/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its +/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out +/// of the image, which then only holds what the effects add around it (a shadow to go under the +/// vector object). The document's raster effects settings add room around it and finish its pixels. +/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not +/// positive, or when its PNG can't be encoded. +pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option { + let (region, scale) = effect_region(out, whole, scale)?; + let look = out.raster_effects.clone(); // Anti-alias off: hard edges (the effects themselves stay smooth). let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None }; let mut img = render(out, vec![whole.clone()], region, scale, anti_alias); @@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo if !below && let Some(image) = rasterize_effect_image(d, n) { return Some(image); } + let whole = effect_art(n, below, members); + let bare = below.then(|| { + let mut b = whole.clone(); + strip_raster(&mut b, false); + b + }); + effect_image(d, &whole, bare.as_ref(), image_scale(d, n)) +} + +/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`: +/// `n` without its transparency, a group's or layer's members without their raster effects when +/// both are set. +fn effect_art(n: &Node, below: bool, members: bool) -> Node { let mut whole = n.clone(); (whole.opacity, whole.blend) = (1.0, Default::default()); whole.extras_mut().mask = None; @@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo strip_raster(Arc::make_mut(c), true); } } - let bare = below.then(|| { - let mut b = whole.clone(); - strip_raster(&mut b, false); - b - }); - // A Rasterize effect at a finer resolution than the document's is rendered at its own. - let scale = raster_fx(n) - .iter() - .filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }) - .fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0)); - effect_image(d, &whole, bare.as_ref(), scale) + whole +} + +/// Pixels per point of the image of the raster effects of `n`: the document's raster effects +/// resolution, or a Rasterize effect's finer one, which is rendered at its own. +fn image_scale(d: &Document, n: &Node) -> f64 { + raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0)) +} + +/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below` +/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the +/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]); +/// 0 when it paints nothing. +pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 { + if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) { + // Measured as Object › Rasterize measures it. + let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0; + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| { + let b = b.inflate(r.add_around, r.add_around); + ((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0)) + }); + // Past Object › Rasterize's limits that image is not made, and the effect's image is. + if let Some((w, h)) = size + && w * h <= super::menucmds::MAX_PIXELS + && w <= side + && h <= side + { + return (w * h) as u64; + } + } + effect_region(d, &effect_art(n, below, members), image_scale(d, n)) + .map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64) } /// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when @@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo /// the image is made of the art before them and moved by them, as the canvas draws it. `None` /// otherwise, when those Transform effects flatten the image, or when the image can't be made. fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option { - let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None }; - let staged = vectorcraft_render::rasterize_stage(d, n); - if let Some((_, map)) = &staged - && !(map.determinant().is_finite() && map.determinant().abs() > 1e-12) - { - return None; - } - let n = staged.as_ref().map_or(n, |(stage, _)| stage); - let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?; + let (whole, r, map) = rasterize_effect_art(d, n)?; let p = json!({ "ppi": r.ppi.unwrap_or(d.raster_effects_ppi), "colorModel": r.color_model.id(), @@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option { "clippingMask": r.clipping_mask, "addAround": r.add_around, }); - let mut whole = n.clone(); - whole.appearance.effects.remove(at); - (whole.opacity, whole.blend) = (1.0, Default::default()); - whole.extras_mut().mask = None; // shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the // image's transparency would need one too; upgrade when CMYK images carry alpha. let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?; let mut image = image.into_node(d); - if let Some((_, map)) = staged { + if let Some(map) = map { image.transform(map, false); } Some(image) } +/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects +/// that move the image, without the Rasterize effect and without its transparency; that effect's +/// options; and the map those Transform effects move the image by. `None` when `n` has another +/// raster effect, when the Rasterize effect is not its own, or when those Transform effects +/// flatten the image. +fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option)> { + let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None }; + let staged = vectorcraft_render::rasterize_stage(d, n); + if let Some((_, map)) = &staged + && !(map.determinant().is_finite() && map.determinant().abs() > 1e-12) + { + return None; + } + let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map))); + let n = stage.as_ref().unwrap_or(n); + let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?; + let mut whole = n.clone(); + whole.appearance.effects.remove(at); + (whole.opacity, whole.blend) = (1.0, Default::default()); + whole.extras_mut().mask = None; + Some((whole, r, map)) +} + /// `v` (an object without its raster effects) replaced by `image` of the object with them: the /// image takes its place with its id, name and transparency (a layer keeps the image as its only /// member). diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 0d2ce9d9f5..1039dab493 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -646,6 +646,46 @@ fn a_nested_instance_of_a_missing_symbol_stays_an_instance() { assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image"); } +/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand +/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which +/// the result reports. +#[test] +fn nested_instance_raster_effects_stop_at_the_image_limit() { + let mut s = session(); + // Images of a pixel or two each. + run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1})); + let blur = |s: &mut Session, id: NodeId, row: usize| { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}})); + }; + let (id, row) = nested_with_row(&mut s, blur); + offset_row(&mut s, id, row, 10.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap(); + let inner = (*d.symbols[outer].art).clone(); + assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance"); + let copies = (0..1_100) + .map(|_| { + let mut copy = inner.clone(); + copy.id = d.alloc_id(); + std::sync::Arc::new(copy) + }) + .collect(); + d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies)); + } + + let r = run(&mut s, "effect.expandAppearance", json!({})); + assert_eq!(r["rasterLeft"], 76, "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}"); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay"); + n.walk(&mut |part| { + if matches!(part.kind, NodeKind::SymbolInstance { .. }) { + assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur"); + } + }); +} + /// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the /// shadow on the art's fill, not its stroke, and PDF export makes an image of it. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8bfcb382ff..147c28c065 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5778,6 +5778,7 @@ digits Malayalam Malaiàlam @msg every numbered name for {name} is taken in the document's folder tots els noms numerats per a {name} estan ocupats a la carpeta del document @msg every search thread stopped on an internal error (please report this bug) tots els fils de cerca s’han aturat per un error intern (informeu d’aquest error) @msg Expand Appearance: the selection has a basic appearance Expandeix l’aparença: la selecció té una aparença bàsica +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alguns efectes ràster no s’han convertit en imatges: ocuparien més de 1.024 imatges o 256 megapíxels en total @msg Expand: no brush strokes selected Expandeix: no s’ha seleccionat cap traç de pinzell @msg Expand: no gradient fills Expandeix: no hi ha farciments de degradat @msg Expand: nothing to expand Expandeix: no hi ha res per expandir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b56e4e4546..16a8333665 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4837,6 +4837,7 @@ imageTrace Outline Obrys @msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu @msg Downloaded {what} Staženo: {what} @msg Expand Appearance: the selection has a basic appearance Rozložit vzhled: výběr má základní vzhled +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all některé rastrové efekty nebyly převedeny na obrazy: zabraly by více než 1 024 obrazů nebo celkem 256 megapixelů @msg Expand: no brush strokes selected Rozložit: nejsou vybrány žádné tahy štětcem @msg Expand: no gradient fills Rozložit: žádné přechodové výplně @msg Expand: nothing to expand Rozložit: není co rozložit diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0856c10ddb..2e05208bca 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5044,6 +5044,7 @@ imageTrace Outline Kontur @msg Divide Objects Below: select exactly one path Opdel objekter nedenunder: markér præcis én kurve @msg Downloaded {what} Downloadede {what} @msg Expand Appearance: the selection has a basic appearance Udvid udseende: markeringen har et grundlæggende udseende +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all nogle rastereffekter blev ikke lavet om til billeder: de ville kræve mere end 1.024 billeder eller i alt 256 megapixel @msg Expand: no brush strokes selected Udvid: ingen penselstrøg er markeret @msg Expand: no gradient fills Udvid: ingen gradientfyld @msg Expand: nothing to expand Udvid: intet at udvide diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9c8a5719fb..56c644de68 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4442,6 +4442,7 @@ theme Appearance Erscheinungsbild @msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus @msg Downloaded {what} {what} heruntergeladen @msg Expand Appearance: the selection has a basic appearance Aussehen umwandeln: Die Auswahl hat ein einfaches Aussehen +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all einige Rastereffekte wurden nicht in Bilder umgewandelt: Sie würden mehr als 1.024 Bilder oder insgesamt 256 Megapixel benötigen @msg Expand: no brush strokes selected Umwandeln: keine Pinselkonturen ausgewählt @msg Expand: no gradient fills Umwandeln: keine Verlaufsflächen @msg Expand: nothing to expand Umwandeln: nichts umzuwandeln diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4593b28320..8046bfedbb 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2535,6 +2535,7 @@ axis Both Και τα δύο @msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή @msg Downloaded {what} Έγινε λήψη του {what} @msg Expand Appearance: the selection has a basic appearance Επέκταση εμφάνισης: η επιλογή έχει βασική εμφάνιση +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all ορισμένα εφέ ράστερ δεν μετατράπηκαν σε εικόνες: θα χρειάζονταν περισσότερες από 1.024 εικόνες ή συνολικά 256 megapixel @msg Expand: no brush strokes selected Επέκταση: δεν επιλέχθηκαν πινελιές @msg Expand: no gradient fills Επέκταση: δεν υπάρχουν γεμίσματα ντεγκραντέ @msg Expand: nothing to expand Επέκταση: δεν υπάρχει περιεχόμενο προς επέκταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3bc56f7710..d9e8eaeba2 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4531,6 +4531,7 @@ axis Both Ambos @msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado @msg Downloaded {what} Se descargó {what} @msg Expand Appearance: the selection has a basic appearance Expandir apariencia: la selección tiene una apariencia básica +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all algunos efectos ráster no se convirtieron en imágenes: ocuparían más de 1024 imágenes o 256 megapíxeles en total @msg Expand: no brush strokes selected Expandir: no hay trazos de pincel seleccionados @msg Expand: no gradient fills Expandir: no hay rellenos de degradado @msg Expand: nothing to expand Expandir: no hay nada que expandir diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3c650e1fae..d788bcd082 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4761,6 +4761,7 @@ imageTrace Outline Ääriviiva @msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku @msg Downloaded {what} Ladattiin {what} @msg Expand Appearance: the selection has a basic appearance Laajenna ulkoasu: valinnalla on perusulkoasu +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all joitakin rasteritehosteita ei muunnettu kuviksi: ne veisivät yli 1 024 kuvaa tai yhteensä 256 megapikseliä @msg Expand: no brush strokes selected Laajenna: sivellinviivoja ei ole valittu @msg Expand: no gradient fills Laajenna: ei liukuväritäyttöjä @msg Expand: nothing to expand Laajenna: ei laajennettavaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8fa5197575..fac071bae1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4509,6 +4509,7 @@ axis Both Les deux @msg select a path sélectionnez un tracé @msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé @msg Downloaded {what} {what} téléchargé +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all certains effets pixellisés n’ont pas été convertis en images, car ils occuperaient plus de 1024 images ou 256 mégapixels au total @msg Expand Appearance: the selection has a basic appearance Décomposer l’aspect : la sélection a un aspect de base @msg Expand: no brush strokes selected Décomposer : aucun contour de forme sélectionné @msg Expand: no gradient fills Décomposer : aucun fond en dégradé diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 46dcd33df0..738d4c2b55 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6966,6 +6966,7 @@ antiAlias Sharp शार्प @msg every search thread stopped on an internal error (please report this bug) प्रत्येक खोज धागा एक आंतरिक त्रुटि पर बंद कर दिया (कृपया इस बग की रिपोर्ट करें) @msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें @msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all कुछ रास्टर इफ़ेक्ट इमेज में नहीं बदले गए: उनके लिए 1,024 से अधिक इमेज या कुल 256 मेगापिक्सेल लगते @msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं @msg Expand: no gradient fills एक्सपैंड: कोई ग्रेडिएंट फ़िल नहीं @msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c8e2630a80..3ac13e2ece 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5359,6 +5359,7 @@ imageTrace Outline Körvonal @msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it egy diagram adatsorában a diagramminta grafikája a mintából rajzolódik újra: a módosításához szerkeszd a mintát @msg every search thread stopped on an internal error (please report this bug) minden keresési szál belső hibával leállt (kérjük, jelentsd ezt a hibát) @msg Expand Appearance: the selection has a basic appearance Megjelenés kibontása: a kijelölésnek alapmegjelenése van +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all néhány raszteres effektus nem lett képpé alakítva: több mint 1024 képet vagy összesen 256 megapixelt foglalnának @msg Expand: no brush strokes selected Kibontás: nincs kijelölt ecsetvonás @msg Expand: no gradient fills Kibontás: nincs színátmenetes kitöltés @msg Expand: nothing to expand Kibontás: nincs mit kibontani diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index fd18bf468a..1273a12a59 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4572,6 +4572,7 @@ axis Both Entrambi @msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato @msg Downloaded {what} Scaricato {what} @msg Expand Appearance: the selection has a basic appearance Espandi aspetto: la selezione ha un aspetto di base +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alcuni effetti raster non sono stati trasformati in immagini: richiederebbero più di 1.024 immagini o 256 megapixel in totale @msg Expand: no brush strokes selected Espandi: nessuna traccia di pennello selezionata @msg Expand: no gradient fills Espandi: nessun riempimento con sfumatura @msg Expand: nothing to expand Espandi: niente da espandere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ad5e529014..0fb16b8a70 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4587,6 +4587,7 @@ swatch Bright Violet ビビッドバイオレット @msg no history to clear 消去するヒストリーがありません @msg no history state {v} ヒストリーの状態 {v} はありません @msg Expand Appearance: the selection has a basic appearance アピアランスを分割: 選択範囲は基本アピアランスです +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 一部のラスター効果は画像になりませんでした: 1,024 枚または合計 256 メガピクセルを超えるためです @msg select (or target) objects whose appearance isn't basic 基本アピアランスではないオブジェクトを選択するか、ターゲットに指定してください @msg {C}: no effect at index {from} {C}: インデックス {from} に効果がありません @msg Expand: no gradient fills 拡張: グラデーションの塗りがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8012630d19..ef8dd85c77 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4221,6 +4221,7 @@ font-technology Variable ცვლადი @msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია @msg Downloaded {what} ჩამოტვირთულია: {what} @msg Expand Appearance: the selection has a basic appearance იერსახის გაშლა: მონიშნულს საბაზისო იერსახე აქვს +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all ზოგიერთი რასტრული ეფექტი გამოსახულებად არ გადაიქცა: მათ დასჭირდებოდა 1024-ზე მეტი გამოსახულება ან ჯამში 256 მეგაპიქსელი @msg Expand: no brush strokes selected გაშლა: ფუნჯის შტრიხები მონიშნული არ არის @msg Expand: no gradient fills გაშლა: გრადიენტული შევსებები არ არის @msg Expand: nothing to expand გაშლა: გასაშლელი არაფერია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 59ea323380..6aef199132 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4514,6 +4514,7 @@ theme Appearance 외관 @msg no history to clear 지울 히스토리가 없습니다 @msg no history state {v} 히스토리 상태 {v}이(가) 없습니다 @msg Expand Appearance: the selection has a basic appearance 모양새 확장: 선택 항목은 기본 모양새입니다 +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 일부 래스터 효과는 이미지로 만들지 않았습니다: 이미지 1,024개 또는 총 256메가픽셀을 넘기 때문입니다 @msg select (or target) objects whose appearance isn't basic 모양새가 기본이 아닌 개체를 선택(또는 대상 지정)하세요 @msg {C}: no effect at index {from} {C}: 인덱스 {from}에 효과가 없습니다 @msg Expand: no gradient fills 확장: 그레이디언트 칠이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3781549296..8da289b2d2 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4941,6 +4941,7 @@ imageTrace Outline Contour @msg Divide Objects Below: select exactly one path Objecten eronder verdelen: selecteer precies één pad @msg Downloaded {what} {what} gedownload @msg Expand Appearance: the selection has a basic appearance Vormgeving uitbreiden: de selectie heeft een basisvormgeving +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all sommige rastereffecten zijn niet omgezet in afbeeldingen: ze zouden meer dan 1.024 afbeeldingen of in totaal 256 megapixel nodig hebben @msg Expand: no brush strokes selected Uitbreiden: geen penseelstreken geselecteerd @msg Expand: no gradient fills Uitbreiden: geen verloopvullingen @msg Expand: nothing to expand Uitbreiden: niets om uit te breiden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e014e51459..de3b790e1c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4660,6 +4660,7 @@ imageTrace Outline Kontur @msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę @msg Downloaded {what} Pobrano {what} @msg Expand Appearance: the selection has a basic appearance Rozszerz wygląd: zaznaczenie ma wygląd podstawowy +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all niektóre efekty rastrowe nie zostały zamienione na obrazy: zajęłyby więcej niż 1024 obrazy lub łącznie 256 megapikseli @msg Expand: no brush strokes selected Rozszerz: nie zaznaczono pociągnięć pędzla @msg Expand: no gradient fills Rozszerz: brak wypełnień gradientem @msg Expand: nothing to expand Rozszerz: nie ma czego rozszerzać diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7ea80a830f..2251937be2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3904,6 +3904,7 @@ axis Both Ambos @msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado @msg Downloaded {what} {what} baixado @msg Expand Appearance: the selection has a basic appearance Expandir aparência: a seleção tem uma aparência básica +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alguns efeitos de raster não foram transformados em imagens: ocupariam mais de 1.024 imagens ou 256 megapixels no total @msg Expand: no brush strokes selected Expandir: nenhum traço de pincel selecionado @msg Expand: no gradient fills Expandir: nenhum preenchimento em gradiente @msg Expand: nothing to expand Expandir: nada para expandir diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 654bd10f09..ed090ba34f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4568,6 +4568,7 @@ axis Both Оба @msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур @msg Downloaded {what} Скачано: {what} @msg Expand Appearance: the selection has a basic appearance Разбор оформления: у выделения основное оформление +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all некоторые растровые эффекты не преобразованы в изображения: для них нужно больше 1024 изображений или 256 мегапикселей в сумме @msg Expand: no brush strokes selected Разбор: не выделены мазки кисти @msg Expand: no gradient fills Разбор: нет градиентных заливок @msg Expand: nothing to expand Разбор: нечего разбирать diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 439bda73f3..a506c93eee 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4441,6 +4441,7 @@ axis Both Båda @msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana @msg Downloaded {what} Hämtade {what} @msg Expand Appearance: the selection has a basic appearance Expandera utseende: markeringen har ett grundläggande utseende +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all vissa rastereffekter gjordes inte om till bilder: de skulle kräva mer än 1 024 bilder eller totalt 256 megapixlar @msg Expand: no brush strokes selected Expandera: inga penseldrag är markerade @msg Expand: no gradient fills Expandera: inga gradientfyllningar @msg Expand: nothing to expand Expandera: ingenting att expandera diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2d34869ac9..35cd79cf9a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4286,6 +4286,7 @@ axis Both Her İkisi @msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin @msg Downloaded {what} {what} indirildi @msg Expand Appearance: the selection has a basic appearance Görünümü Genişlet: seçimin temel bir görünümü vardır +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all bazı raster efektleri görüntüye dönüştürülmedi: toplamda 1.024'ten fazla görüntü veya 256 megapiksel gerektirirlerdi @msg Expand: no brush strokes selected Genişlet: seçili fırça darbesi yok @msg Expand: no gradient fills Genişlet: degrade dolgu yok @msg Expand: nothing to expand Genişlet: genişletilecek bir şey yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3ca32f6ee5..2899dc07d4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4556,6 +4556,7 @@ axis Both Обидві @msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур @msg Downloaded {what} Завантажено: {what} @msg Expand Appearance: the selection has a basic appearance Розбір оформлення: виділення основне оформлення +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all деякі растрові ефекти не перетворено на зображення: для них потрібно понад 1024 зображення або загалом 256 мегапікселів @msg Expand: no brush strokes selected Розбір: не виділено мазки пензлі @msg Expand: no gradient fills Розбір: немає градієнтних заливок @msg Expand: nothing to expand Розбір: нема чого розбирати diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1747a8ac37..ac42755e39 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5021,6 +5021,7 @@ theme Appearance Giao diện @msg every numbered name for {name} is taken in the document's folder mọi tên đánh số cho {name} đã được dùng trong thư mục tài liệu @msg every search thread stopped on an internal error (please report this bug) mọi luồng tìm kiếm đã dừng do lỗi nội bộ (vui lòng báo cáo lỗi này) @msg Expand Appearance: the selection has a basic appearance Mở rộng diện mạo: vùng chọn có diện mạo cơ bản +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all một số hiệu ứng raster không được chuyển thành hình ảnh: chúng sẽ cần hơn 1.024 hình ảnh hoặc tổng cộng 256 megapixel @msg Expand: no brush strokes selected Mở rộng: chưa chọn nét cọ @msg Expand: no gradient fills Mở rộng: không có tô chuyển sắc @msg Expand: nothing to expand Mở rộng: không có gì để mở rộng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a8846a9bac..90384bff68 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4288,6 +4288,7 @@ imageTrace Outline 轮廓 @msg no history to clear 没有可清除的历史记录 @msg no history state {v} 没有历史记录状态 {v} @msg Expand Appearance: the selection has a basic appearance 扩展外观:所选对象只有基本外观 +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 部分栅格效果未转换为图像:它们会超过 1,024 个图像或总计 256 兆像素 @msg select (or target) objects whose appearance isn't basic 请选择 (或定位) 外观不是基本外观的对象 @msg {C}: no effect at index {from} {C}:索引 {from} 处没有效果 @msg Expand: no gradient fills 扩展:没有渐变填色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c4235260ab..0cd675f57b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1936,6 +1936,7 @@ file-filter Templates 範本 @msg no history to clear 沒有可清除的步驟記錄 @msg no history state {v} 沒有步驟記錄 {v} @msg Expand Appearance: the selection has a basic appearance 展開外觀:選取範圍只有基本外觀 +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 部分點陣效果未轉換為影像:它們會超過 1,024 個影像或總計 256 百萬像素 @msg select (or target) objects whose appearance isn't basic 請選取 (或指定目標) 外觀不是基本外觀的物件 @msg {C}: no effect at index {from} {C}:索引 {from} 處沒有效果 @msg Expand: no gradient fills 展開:沒有漸層填色 diff --git a/docs/mcp.md b/docs/mcp.md index 17982bf02c..55ed65bec1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5251,6 +5251,10 @@ instance in the art whose topmost fill or stroke has a geometry or raster effect passes on, becomes its art and image the same way, and so do the instances in that art (VectorCraft's own rule). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. +One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own +limits). An object or symbol instance whose image would go past them stays as it is, with its effects and the objects +in it; the result then carries a `warning` and `rasterLeft`, the number of objects left so, and when nothing else +expands the command fails with the same message. A legacy `.ai` save notes it the same way. The result is `{ids}`; when an image in the art can't be decoded, the images made from raster effects do not show it, and the result also carries the `warning` that Flatten Transparency gives. A path's strokes stay strokes, as the From 34e52df5de9d0544513ae703dec0b0ad2910cecb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:26:01 -0800 Subject: [PATCH 09/50] Crop Image: the Control bar sets the cropped image's resolution, reference point and linked size While Crop Image shows its box, the Control bar has a PPI list (72, 96, 150, 200 and 300 ppi, with the ones above the image's own disabled) and a PPI field, a reference point that X and Y name and that W and H resize about, and a link icon that keeps W and H in proportion. A linked size that would not fit the image is reduced with the other side in proportion. object.cropImage takes ppi: the cut pixels are resampled to it, with colors weighted by their alpha, and the image keeps the box's size. A box over the whole image with a new ppi only resamples it, and an image scaled differently across and down comes out with square pixels. ppi is refused outside 1 to 2400, above the image's own resolution (300 ppi for a linked image), and with trim. tool.setOption sets ppi, reference and linked for the Crop Image tool and refuses values it can't use. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/menucmds.rs | 131 ++++++++++--- crates/engine/src/tests/menucmds.rs | 160 +++++++++++++++ crates/engine/src/tooling.rs | 12 ++ crates/tools/src/cropimage.rs | 294 ++++++++++++++++++++++++++-- crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/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/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/toolbar.rs | 69 +++++-- docs/mcp.md | 15 ++ docs/target-app-parity.md | 1 + 23 files changed, 661 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1ab0e0b670..e7163c13d7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -133,7 +133,7 @@ pub fn specs() -> Vec { "Crop Image", ["Object"], None, - "{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}", + "{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}", has_image, crop_image ), @@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData { PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true)) } -/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and -/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or -/// `r` not on the pixel grid), so the caller draws it instead. -fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec, u32, u32, Affine)> { +/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when +/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel +/// grid), so the caller draws it instead. +fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> { let blob = doc.images.get(&im.key)?; let [a, b, c, d, _, _] = im.xf.as_coeffs(); if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 { @@ -996,9 +996,64 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op return None; } let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image(); + Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) +} + +/// Crop Image's `ppi`: the resolution the cropped image is resampled to, in pixels per point, or `None` to keep +/// the image's own. Refuses a resolution that isn't a positive number or is above what the image allows: its own, +/// or 300 ppi for a linked image, within 1 to 2400 ppi as Rasterize's. +fn crop_resolution(p: &Value, im: &ImageObject) -> Result> { + const C: &str = "object.cropImage"; + let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) }; + let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?; + if !(1.0..=2400.0).contains(&ppi) { + return Err(bad(C, "ppi must be between 1 and 2400")); + } + let (_, max) = vectorcraft_tools::cropimage::image_ppi(im); + if ppi > max + 1e-6 { + let max = (max * 100.0 + 1e-6).floor() / 100.0; + return Err(bad(C, format!("ppi can't be more than {max} for this image"))); + } + // An image whose pixels are not square is resampled on both sides, even at its denser side's resolution. + Ok((!vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)).then_some(ppi / 72.0)) +} + +/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and +/// no side past the renderer's). +fn check_crop_size(w: f64, h: f64) -> Result<()> { + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > MAX_PIXELS || w > side || h > side { + let (w, h) = (w as u64, h as u64); + return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw"))); + } + Ok(()) +} + +/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully +/// transparent pixel does not show at the edges of what is opaque. +fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> image::RgbaImage { + let mut pre = img.clone(); + for p in pre.pixels_mut() { + let a = u32::from(p[3]); + for c in &mut p.0[..3] { + *c = ((u32::from(*c) * a + 127) / 255) as u8; + } + } + let mut out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3); + for p in out.pixels_mut() { + let a = u32::from(p[3]); + for c in &mut p.0[..3] { + *c = (u32::from(*c) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; + } + } + out +} + +/// `img` as PNG bytes. +fn encode_png(img: &image::RgbaImage) -> Result> { let mut png = Vec::new(); - cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; - Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?; + Ok(png) } fn crop_image(s: &mut Session, p: &Value) -> Result { @@ -1014,9 +1069,13 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; if switch_or(p, "trim", false, C)? { + if p.get("ppi").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi")); + } return trim_image(s, id, (**im).clone()); } let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; + let target = crop_resolution(p, im)?; let rect = match p.get("rect").filter(|v| !v.is_null()) { Some(Value::Array(a)) if a.len() == 4 => { let v: Vec = a.iter().filter_map(Value::as_f64).collect(); @@ -1038,16 +1097,40 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { if r.width() <= 0.0 || r.height() <= 0.0 { return Err(bad(C, "crop rectangle doesn't overlap the image")); } - if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 { + // A box over the whole image still resamples it to a new resolution. + let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6; + if whole && target.is_none() { return Err(bad(C, "nothing to crop")); } - // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled. - if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) { - put_pixels(s, id, png, cw, ch, xf)?; + if let Some(t) = target { + check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?; + } + // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a + // resolution is asked for. + if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) { + let (cut, xf) = match target { + Some(t) => { + let (cw, ch) = cut.dimensions(); + let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); + let resized = resize_premultiplied(&cut, w, h); + (resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h))) + } + None => (cut, xf), + }; + let (cw, ch) = cut.dimensions(); + put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?; return Ok(json!({ "id": id.0, "width": cw, "height": ch })); } - // Keep the image's pixel density. - let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); + // Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more + // than the image's own, measured on its pixel grid however it is turned, nor past the size a + // drawing may have), and resampled to it. + let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); + let scale = target.map_or(native, |t| { + let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9)); + (2.0 * t).min(own).min(budget).max(t.min(own)) + }); let mut bare = node.clone(); bare.opacity = 1.0; bare.blend = Default::default(); @@ -1062,19 +1145,23 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale); let (png, w, h, warning) = render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?; + // At a resolution asked for, the drawing is resampled to the box's size at that resolution and + // fitted to the box, so the image keeps its size. + let (png, w, h, xf) = match target { + Some(t) => { + let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.to_rgba8(); + let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); + let resized = resize_premultiplied(&drawn, tw, th); + let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th)); + (encode_png(&resized)?, tw, th, xf) + } + None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)), + }; s.edit("Crop Image", |d, _| { let key = unique_key(d, "crop"); d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png)); if let Some(n) = d.node_mut(id) { - n.kind = NodeKind::Image(Box::new(ImageObject { - key, - width: w, - height: h, - xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale), - link: None, - placement: Default::default(), - pixels: None, - })); + n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None })); } Ok(()) })?; diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1151f83910..841f6184f8 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1588,6 +1588,166 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() { assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); } +/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size. +#[test] +fn crop_image_resamples_the_cut_to_the_resolution_asked_for() { + let (mut s, img, px) = busy_image_at_two_points_a_pixel(); + // The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image(); + assert_eq!(out, image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3)); +} + +/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not +/// tint the partly transparent edge of what is opaque. +#[test] +fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() { + // Opaque white on the left half, fully transparent red on the right. + let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) }); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + // 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear. + s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap(); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent"); + for p in out.pixels().filter(|p| p[3] > 0) { + assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}"); + } +} + +/// A box between pixels is drawn at the resolution asked for, and lands on the box. +#[test] +fn crop_image_between_pixels_draws_at_the_resolution_asked_for() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + // 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box. + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}"); +} + +/// A box over the whole image with a new resolution resamples it; with the image's own there is +/// nothing to do. +#[test] +fn crop_image_over_the_whole_image_only_resamples_it() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let before = undo_len(&s); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}"); + assert_eq!(undo_len(&s), before); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}"); + assert_eq!(undo_len(&s), before + 1, "one undo step"); + let b = bounds(&s, img); + assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}"); +} + +/// An image scaled more down than across is resampled on both sides at the resolution of its denser +/// side, so its pixels come out square. +#[test] +fn crop_image_resamples_pixels_that_are_not_square() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + // 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt. + s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap(); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}"); +} + +/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one +/// with trim; the image stays as it was. +#[test] +fn crop_image_refuses_a_resolution_it_cannot_give() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let before = (undo_len(&s), node(&s, img)); + let refused = |s: &mut Session, p: Value, want: &str| { + let r = s.execute("object.cropImage", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + }; + for v in [json!(0), json!(-72), json!("high"), json!(true)] { + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}")); + } + for v in [0.5, 1e-310, 2401.0] { + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400"); + } + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image"); + refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi"); + assert_eq!((undo_len(&s), node(&s, img)), before); + // A null ppi keeps the image's own, as a missing one does. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}"); +} + +/// A turned image keeps its own resolution as the limit (not the density across its bounding box), +/// and its drawn cut is resampled to the box's size at the resolution asked for. +#[test] +fn crop_image_of_a_turned_image_resamples_its_drawing() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}"); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}"); + let c = bounds(&s, img); + assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}"); +} + +/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it. +#[test] +fn crop_image_takes_a_linked_image_up_to_300_ppi() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.edit("Link", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") }; + im.link = Some(vectorcraft_doc::LinkInfo::new("art.png")); + Ok(()) + }) + .unwrap(); + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}"); + // 72 ppi: a pixel a point. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + assert!(im.link.is_none()); +} + +/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and +/// changes nothing. +#[test] +fn crop_image_tool_options_refuse_values_they_cannot_use() { + let (mut s, _, _) = busy_image_at_two_points_a_pixel(); + s.select_tool("cropImage", ViewInfo::default()).unwrap(); + s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap(); + // 72 ppi is above the selected 36 ppi image's own. + for (key, value) in + [("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))] + { + assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}"); + } + let o = s.tool_options(); + assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}"); + s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap(); + assert!(s.tool_options().get("ppi").is_none()); +} + /// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a /// null `rect` crops to the artboard as a missing one does. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f6bc163e65..a5b9958e93 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1324,6 +1324,18 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { + use vectorcraft_tools::cropimage as crop; + // The most the selected image can be cropped to, when one is selected. + let max = self.doc().ok().and_then(|st| { + let (id, _) = crop::selected_image(&st.doc, &st.selection)?; + match &st.doc.node(id)?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1), + _ => None, + } + }); + crop::check_options(&values, max)?; + } // The Place queue is read later, by a click outside any automation scope: its files must // be readable now, under the roots of whoever sets it. if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) { diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 0245f75112..abc2b55b53 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -2,10 +2,12 @@ //! its artboard (the whole image when it lies inside one); its handles and its inside drag it, //! always within the image, and the part outside it is dimmed. Enter (or the Control bar's Apply) //! crops the image to it (`object.cropImage {rect}`), Escape (or Cancel) leaves it as it was; both -//! go back to the Selection tool. The Control bar edits the box through the `rect` option. +//! go back to the Selection tool. The Control bar edits the box through the `rect` option, the +//! point its X and Y name through `reference`, whether its W and H keep their proportions through +//! `linked`, and the cropped image's resolution through `ppi`. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; +use vectorcraft_doc::{Document, ImageObject, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle}; @@ -18,6 +20,103 @@ pub const ID: &str = "cropImage"; /// The smallest the box gets, in points. const MIN: f64 = 1.0; +/// The resolutions the Control bar's PPI list offers; those above the image's own are disabled. +pub const PPI_CHOICES: [f64; 5] = [72.0, 96.0, 150.0, 200.0, 300.0]; + +/// The highest resolution a linked image can be cropped to. +pub const LINKED_MAX_PPI: f64 = 300.0; + +/// The reference point the box's X and Y name by default: its center (of the nine points of +/// [`vectorcraft_geom::reference_point`], left to right and top to bottom). +pub const CENTER: usize = 4; + +/// An image's own resolution in pixels per inch (along its denser side, measured on its pixel +/// grid, so turning it changes nothing), and the highest resolution it can be cropped to: its own, +/// or [`LINKED_MAX_PPI`] for a linked image. +pub fn image_ppi(im: &ImageObject) -> (f64, f64) { + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + // The document lengths of one pixel's sides. + let (sx, sy) = (a.hypot(b), c.hypot(d)); + let own = 72.0 / sx.min(sy).max(1e-9); + (own, if im.link.is_some() { LINKED_MAX_PPI } else { own }) +} + +/// Whether cropping `im` at `ppi` keeps its pixels as they are: its pixels are square (the same +/// resolution across and down) and at that resolution, within `tolerance` ppi. +pub fn keeps_resolution(im: &ImageObject, ppi: f64, tolerance: f64) -> bool { + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + let (x, y) = (72.0 / a.hypot(b).max(1e-9), 72.0 / c.hypot(d).max(1e-9)); + (x - ppi).abs() <= tolerance && (y - ppi).abs() <= tolerance +} + +/// Checks the values `tool.setOption` gives the tool before any is set: `ppi` a number from 1 to +/// 2400, and no more than `max` (the selected image's limit, from [`image_ppi`]), or null; +/// `reference` a whole number from 0 to 8; `linked` true or false. +pub fn check_options(values: &serde_json::Map, max: Option) -> Result<(), String> { + for (key, v) in values { + let error = match key.as_str() { + "ppi" if v.is_null() => None, + "ppi" => match v.as_f64().filter(|n| (1.0..=2400.0).contains(n)) { + None => Some(format!("`ppi` must be a number from 1 to 2400 or null, not {v}")), + Some(n) => { + max.filter(|m| n > m + 1e-6).map(|m| format!("`ppi` can't be more than {} for this image", (m * 100.0 + 1e-6).floor() / 100.0)) + } + }, + "reference" => (!v.as_u64().is_some_and(|n| n <= 8)).then(|| format!("`reference` must be a whole number from 0 to 8, not {v}")), + "linked" => (!v.is_boolean()).then(|| format!("`linked` must be true or false, not {v}")), + _ => None, + }; + if let Some(e) = error { + return Err(e); + } + } + Ok(()) +} + +/// The box `r` over an image with bounds `image`, with one Control bar field set: `x` or `y` moves +/// the box so its `reference` point is there; `width` or `height` resizes it about that point, the +/// other side following in proportion when `linked`. Sizes below [`MIN`] are raised to it. A +/// linked size is held to the image with both sides scaled together, and a box that fits is slid +/// back within the image, so its proportions survive being kept within it. `None` for another key +/// or a value that isn't finite. +pub fn edited_box(r: Rect, image: Rect, reference: usize, linked: bool, key: &str, v: f64) -> Option { + if !v.is_finite() { + return None; + } + let p = vectorcraft_geom::reference_point(r, reference); + let (mut w, mut h) = (r.width(), r.height()); + let fit = |b: Rect| if b.width() <= image.width() + 1e-9 && b.height() <= image.height() + 1e-9 { slid_within(b, image) } else { b }; + match key { + "x" => return Some(fit(r + Vec2::new(v - p.x, 0.0))), + "y" => return Some(fit(r + Vec2::new(0.0, v - p.y))), + "width" => { + let nw = v.max(MIN); + if linked && w > 0.0 { + h = (h * nw / w).max(MIN); + } + w = nw; + } + "height" => { + let nh = v.max(MIN); + if linked && h > 0.0 { + w = (w * nh / h).max(MIN); + } + h = nh; + } + _ => return None, + } + if linked { + let k = (image.width() / w).min(image.height() / h).min(1.0); + if k.is_finite() && k > 0.0 { + (w, h) = (w * k, h * k); + } + } + // The reference point keeps its place: it sits at the same fraction of the new box. + let (fx, fy) = ((reference % 3) as f64 / 2.0, (reference / 3).min(2) as f64 / 2.0); + let (x0, y0) = (p.x - w * fx, p.y - h * fy); + Some(fit(Rect::new(x0, y0, x0 + w, y0 + h))) +} + /// Create the Crop Image tool by id (None = not ours). pub fn create(id: &str) -> Option> { (id == ID).then(|| Box::new(CropImageTool::default()) as Box) @@ -75,7 +174,6 @@ enum Drag { Move(Point, Rect), } -#[derive(Default)] pub struct CropImageTool { /// The box, for the image it was made for (None: set from outside, for the selected image); /// None until it's dragged or set. @@ -83,6 +181,18 @@ pub struct CropImageTool { drag: Option, /// Where the pointer last was on the canvas (measurement label during a drag). last: Point, + /// The cropped image's resolution in pixels per inch (None: the image's own). + ppi: Option, + /// The point of the box the Control bar's X and Y name (0..=8, [`CENTER`] by default). + reference: usize, + /// Whether the Control bar's W and H keep the box's proportions. + linked: bool, +} + +impl Default for CropImageTool { + fn default() -> Self { + Self { rect: None, drag: None, last: Point::ZERO, ppi: None, reference: CENTER, linked: false } + } } impl CropImageTool { @@ -93,24 +203,39 @@ impl CropImageTool { crop_box(cx.doc, cx.selection, set) } - /// Crop to the box and go back to the Selection tool (only back when it covers the image). + /// Crop to the box at the chosen resolution and go back to the Selection tool (only back when + /// the box covers the image and the resolution is the image's own). fn apply(&mut self, cx: &ToolContext) -> Vec { let current = self.current(cx); + let ppi = self.ppi; self.reset(); let mut out = vec![]; - if let Some((_, image, r)) = current - && !same(r, image) - { - out.push(Action::Exec("object.cropImage".into(), json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }))); + if let Some((id, image, r)) = current { + let im = match cx.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Image(im)) => Some(&**im), + _ => None, + }; + let max = im.map_or(f64::INFINITY, |im| image_ppi(im).1); + // A resolution set before this image was selected is held to this image's limit. + let resample = ppi.map(|v| v.min(max)).filter(|v| im.is_none_or(|im| !keeps_resolution(im, *v, 1e-3))); + if !same(r, image) || resample.is_some() { + let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }); + if let Some(v) = resample { + p["ppi"] = json!(v); + } + out.push(Action::Exec("object.cropImage".into(), p)); + } } out.push(Action::SwitchTool("selection".into())); out } + /// Forget the box and the resolution; the reference point and the link stay as they were set. fn reset(&mut self) { self.rect = None; self.drag = None; self.last = Point::ZERO; + self.ppi = None; } } @@ -242,19 +367,40 @@ impl Tool for CropImageTool { } /// `rect`: the box as `[x, y, width, height]` once it's been dragged or set (until then it's - /// [`initial_box`]). + /// [`initial_box`]); `ppi` once it's been set (until then the image's own); `reference` (0..=8) + /// and `linked`. fn options(&self) -> Value { - match self.rect { - Some((_, r)) => json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }), - None => json!({}), + let mut o = json!({ "reference": self.reference, "linked": self.linked }); + if let Some((_, r)) = self.rect { + o["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); } + if let Some(v) = self.ppi { + o["ppi"] = json!(v); + } + o } /// `rect` `[x, y, width, height]` sets the box (kept within the selected image when used); - /// anything else puts it back where it starts. + /// anything else puts it back where it starts. `ppi` a positive number sets the cropped + /// image's resolution (null: the image's own). `reference` a whole number 0..=8 sets the point X and Y name, and `linked` + /// true or false the link of W and H. `tool.setOption` refuses other values of those three + /// ([`check_options`]); one that reaches the tool anyway puts that setting back to its default. fn set_option(&mut self, key: &str, value: &Value) { - if key != "rect" { - return; + match key { + "ppi" => { + self.ppi = value.as_f64().filter(|v| v.is_finite() && *v > 0.0); + return; + } + "reference" => { + self.reference = value.as_u64().filter(|v| *v <= 8).map_or(CENTER, |v| v as usize); + return; + } + "linked" => { + self.linked = value.as_bool().unwrap_or(false); + return; + } + "rect" => {} + _ => return, } // Invalid components must discard the whole box, not silently shift the // coordinates by dropping a non-numeric entry. @@ -411,6 +557,124 @@ mod tests { assert_eq!(tool.options()["rect"], json!([10.0, 20.0, 30.0, 40.0])); } + /// The Control bar's fields: X and Y place the reference point, W and H resize about it, and + /// the link keeps the proportions. + #[test] + fn fields_move_and_resize_the_box_about_its_reference_point() { + let r = Rect::new(10.0, 20.0, 110.0, 70.0); + let big = Rect::new(0.0, 0.0, 1000.0, 1000.0); + // The center (the default): today's behavior. + assert_eq!(edited_box(r, big, CENTER, false, "x", 100.0), Some(Rect::new(50.0, 20.0, 150.0, 70.0))); + assert_eq!(edited_box(r, big, CENTER, false, "width", 50.0), Some(Rect::new(35.0, 20.0, 85.0, 70.0))); + // The top-left corner: X and Y name it, and a new size keeps it where it is. + assert_eq!(edited_box(r, big, 0, false, "x", 0.0), Some(Rect::new(0.0, 20.0, 100.0, 70.0))); + assert_eq!(edited_box(r, big, 0, false, "y", 5.0), Some(Rect::new(10.0, 5.0, 110.0, 55.0))); + assert_eq!(edited_box(r, big, 0, false, "height", 10.0), Some(Rect::new(10.0, 20.0, 110.0, 30.0))); + // The bottom-right corner keeps its place too. + assert_eq!(edited_box(r, big, 8, false, "width", 40.0), Some(Rect::new(70.0, 20.0, 110.0, 70.0))); + // Linked: the other side follows in proportion (100 × 50 → 40 × 20, then 60 × 30). + assert_eq!(edited_box(r, big, 0, true, "width", 40.0), Some(Rect::new(10.0, 20.0, 50.0, 40.0))); + assert_eq!(edited_box(r, big, 8, true, "height", 30.0), Some(Rect::new(50.0, 40.0, 110.0, 70.0))); + // A size below a point is raised to one; other keys and values that aren't finite change nothing. + assert_eq!(edited_box(r, big, 0, false, "width", -5.0), Some(Rect::new(10.0, 20.0, 11.0, 70.0))); + assert_eq!(edited_box(r, big, 0, false, "angle", 5.0), None); + assert_eq!(edited_box(r, big, 0, false, "x", f64::NAN), None); + // Within a 120 × 80 image: a linked size is held to the image with both sides scaled + // (200 × 100 → 120 × 60), and the box slides back within it, keeping its 2:1 proportions. + let image = Rect::new(0.0, 0.0, 120.0, 80.0); + assert_eq!(edited_box(r, image, 0, true, "width", 200.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0))); + assert_eq!(edited_box(r, image, 0, true, "height", 70.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0))); + // A move past the edge slides the box back without changing its size. + assert_eq!(edited_box(r, image, 0, false, "x", 50.0), Some(Rect::new(20.0, 20.0, 120.0, 70.0))); + // Unlinked, a side larger than the image is left for the box's own limit to cut. + assert_eq!(edited_box(r, image, 0, false, "width", 200.0), Some(Rect::new(10.0, 20.0, 210.0, 70.0))); + } + + #[test] + fn reference_link_and_resolution_are_tool_options() { + let mut t = CropImageTool::default(); + assert_eq!(t.options(), json!({ "reference": 4, "linked": false })); + t.set_option("reference", &json!(0)); + t.set_option("linked", &json!(true)); + t.set_option("ppi", &json!(150)); + assert_eq!(t.options(), json!({ "reference": 0, "linked": true, "ppi": 150.0 })); + // Values that don't read put each back to its default. + for (k, v) in [("reference", json!(9)), ("linked", json!("yes")), ("ppi", json!(0)), ("ppi", json!(-72)), ("ppi", json!("high"))] { + t.set_option(k, &v); + } + assert_eq!(t.options(), json!({ "reference": 4, "linked": false })); + } + + #[test] + fn option_values_are_checked_before_they_are_set() { + let values = |v: Value| v.as_object().cloned().unwrap(); + assert_eq!(check_options(&values(json!({ "ppi": 150.5, "reference": 8, "linked": true, "rect": [0, 0, 1, 1] })), None), Ok(())); + assert_eq!(check_options(&values(json!({ "ppi": null })), Some(36.0)), Ok(())); + assert_eq!(check_options(&values(json!({ "ppi": 36 })), Some(36.0)), Ok(())); + for (v, want) in [ + (json!({ "ppi": 0.5 }), "`ppi` must be a number from 1 to 2400 or null, not 0.5"), + (json!({ "ppi": 2401 }), "`ppi` must be a number from 1 to 2400 or null, not 2401"), + (json!({ "ppi": "high" }), "`ppi` must be a number from 1 to 2400 or null, not \"high\""), + (json!({ "ppi": 72 }), "`ppi` can't be more than 36 for this image"), + (json!({ "reference": 9 }), "`reference` must be a whole number from 0 to 8, not 9"), + (json!({ "reference": 1.5 }), "`reference` must be a whole number from 0 to 8, not 1.5"), + (json!({ "linked": "yes" }), "`linked` must be true or false, not \"yes\""), + ] { + assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); + } + } + + /// An image's own resolution, and the most it can be cropped to. + #[test] + fn image_resolution_and_its_limit() { + let (d, s) = doc_with_image((50.0, 60.0)); + let (id, _) = selected_image(&d, &s).unwrap(); + let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") }; + // 100 px over 200 pt: half a pixel per point, 36 ppi. + assert_eq!(image_ppi(&im), (36.0, 36.0)); + // Turned, it is the same image: 36 ppi, not the density across its bounding box. + let turned = ImageObject { xf: Affine::rotate(0.5) * im.xf, ..(*im).clone() }; + assert!((image_ppi(&turned).0 - 36.0).abs() < 1e-9); + // Stretched to 3 pt a pixel across, its denser side counts. + let stretched = ImageObject { xf: Affine::scale_non_uniform(3.0, 2.0), ..(*im).clone() }; + assert_eq!(image_ppi(&stretched).0, 36.0); + // Its own resolution keeps its pixels; pixels that are not square are resampled at any resolution. + assert!(keeps_resolution(&im, 36.0, 1e-6) && !keeps_resolution(&im, 18.0, 1e-6)); + assert!(!keeps_resolution(&stretched, 36.0, 1e-6) && !keeps_resolution(&stretched, 24.0, 1e-6)); + let linked = ImageObject { link: Some("photo.png".into()), ..*im }; + assert_eq!(image_ppi(&linked), (36.0, LINKED_MAX_PPI)); + } + + /// Apply sends the chosen resolution with the box, even for a box over the whole image; the + /// image's own resolution sends nothing new, and one above the image's limit is held to it. + #[test] + fn apply_sends_the_chosen_resolution() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let cx = cx(&d, &s, &p); + let exec = |acts: &[Action]| { + acts.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "object.cropImage" => Some(v.clone()), + _ => None, + }) + }; + let mut t = CropImageTool::default(); + t.set_option("ppi", &json!(20)); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [50.0, 60.0, 200.0, 100.0], "ppi": 20.0 }))); + assert!(t.options().get("ppi").is_none(), "the next crop starts at the image's own"); + t.set_option("ppi", &json!(36)); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), None, "the image's own over the whole image: nothing to do"); + t.set_option("ppi", &json!(36)); + t.set_option("rect", &json!([60, 70, 100, 50])); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + // A resolution set before this image was selected is held to its limit: 300 → its own 36. + t.set_option("ppi", &json!(300)); + t.set_option("rect", &json!([60, 70, 100, 50])); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + t.set_option("ppi", &json!(300)); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), None, "held to its own over the whole image: nothing to do"); + } + #[test] fn the_tool_is_made_by_its_id() { assert_eq!(crate::create(ID).id(), ID); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7eae56c39f..5daa997a5e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8899,7 +8899,9 @@ breakText Glyphs Glyfy @msg position must be normal, superscript or subscript position musí být normal, superscript nebo subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position musí být topLeft, topRight, bottomLeft nebo bottomRight @msg positions must be between 0 and 100000 pt positions musí být mezi 0 a 100000 pt +@msg ppi can't be more than {max} for this image ppi nemůže být pro tento obrázek víc než {max} @msg ppi must be a positive number, not {ppi} ppi musí být kladné číslo, ne {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim ponechává pixely obrázku beze změny: vynechte ppi @msg ppi must be between 1 and 2400 ppi musí být mezi 1 a 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` není transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape musí být clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 741cba9b6f..410a5f6e24 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8483,7 +8483,9 @@ breakText Glyphs Glyphen @msg position must be normal, superscript or subscript position muss normal, superscript oder subscript sein @msg position must be topLeft, topRight, bottomLeft or bottomRight position muss topLeft, topRight, bottomLeft oder bottomRight sein @msg positions must be between 0 and 100000 pt positions müssen zwischen 0 und 100000 pt liegen +@msg ppi can't be more than {max} for this image ppi darf für dieses Bild nicht mehr als {max} sein @msg ppi must be a positive number, not {ppi} ppi muss eine positive Zahl sein, nicht {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim lässt die Pixel des Bildes unverändert: Lassen Sie ppi weg @msg ppi must be between 1 and 2400 ppi muss zwischen 1 und 2400 liegen @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` ist nicht transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape muss clippingMask|transparency sein diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4a1e376475..9da0e3c7b3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8760,7 +8760,9 @@ breakText Glyphs Glyphes @msg position must be normal, superscript or subscript position doit valoir normal, superscript ou subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position doit valoir topLeft, topRight, bottomLeft ou bottomRight @msg positions must be between 0 and 100000 pt les positions doivent être comprises entre 0 et 100000 pt +@msg ppi can't be more than {max} for this image ppi ne peut pas dépasser {max} pour cette image @msg ppi must be a positive number, not {ppi} ppi doit être un nombre positif, pas {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim conserve les pixels de l’image tels quels : omettez ppi @msg ppi must be between 1 and 2400 ppi doit être compris entre 1 et 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` n’est pas transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape doit valoir clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 658f534db9..7da4fe412b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7744,7 +7744,9 @@ antiAlias Sharp शार्प @msg position must be normal, superscript or subscript position normal, superscript या subscript होना चाहिए @msg position must be topLeft, topRight, bottomLeft or bottomRight position को topLeft, topRight, bottomLeft या bottomRight होना चाहिए @msg positions must be between 0 and 100000 pt positions 0 और 100000 pt के बीच होनी चाहिए +@msg ppi can't be more than {max} for this image इस छवि के लिए ppi {max} से अधिक नहीं हो सकता @msg ppi must be a positive number, not {ppi} ppi एक धनात्मक संख्या होनी चाहिए, {ppi} नहीं +@msg trim keeps the image's pixels as they are: leave out ppi trim छवि के पिक्सेल जैसे हैं वैसे ही रखता है: ppi न दें @msg ppi must be between 1 and 2400 ppi 1 और 2400 के बीच होना चाहिए @msg precision must be from 0.001 to 10 pt precision 0.001 से 10 pt तक होनी चाहिए @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill में से नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eb7a229c66..09ec92ad47 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8769,7 +8769,9 @@ breakText Glyphs Glifák @msg position must be normal, superscript or subscript position: normal, superscript vagy subscript kell @msg position must be topLeft, topRight, bottomLeft or bottomRight position: topLeft, topRight, bottomLeft vagy bottomRight kell @msg positions must be between 0 and 100000 pt positions: 0 és 100000 pt közötti értékek kellenek +@msg ppi can't be more than {max} for this image ppi: ennél a képnél legfeljebb {max} lehet @msg ppi must be a positive number, not {ppi} ppi: pozitív szám kell, ez nem az: {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi a trim változatlanul hagyja a kép képpontjait: hagyja el a ppi értéket @msg ppi must be between 1 and 2400 ppi: 1 és 2400 közötti érték kell @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`: nem transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape: clippingMask|transparency kell diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 19c2fd35a0..04da7049ba 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8531,7 +8531,9 @@ breakText Glyphs Glifi @msg position must be normal, superscript or subscript position deve essere normal, superscript o subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position deve essere topLeft, topRight, bottomLeft o bottomRight @msg positions must be between 0 and 100000 pt le posizioni devono essere comprese tra 0 e 100000 pt +@msg ppi can't be more than {max} for this image ppi non può superare {max} per questa immagine @msg ppi must be a positive number, not {ppi} ppi deve essere un numero positivo, non {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim mantiene i pixel dell'immagine così come sono: ometti ppi @msg ppi must be between 1 and 2400 ppi deve essere compreso tra 1 e 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` non è transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape deve essere clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6a24933f11..9d0047041b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7732,7 +7732,9 @@ axis Y Axis Y 軸 @msg position must be normal, superscript or subscript position には normal、superscript、subscript のいずれかを指定してください @msg position must be topLeft, topRight, bottomLeft or bottomRight position には topLeft、topRight、bottomLeft、bottomRight のいずれかを指定してください @msg positions must be between 0 and 100000 pt positions には 0 から 100000 pt までの値を指定してください +@msg ppi can't be more than {max} for this image この画像の ppi には {max} 以下の値を指定してください @msg ppi must be a positive number, not {ppi} ppi には正の数値を指定してください ({ppi} は指定できません) +@msg trim keeps the image's pixels as they are: leave out ppi trim は画像のピクセルをそのまま残します: ppi は指定しないでください @msg ppi must be between 1 and 2400 ppi には 1 から 2400 までの値を指定してください @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` は transforms|bounds|fileDimensions|fit|fill のいずれでもありません @msg preserveShape must be clippingMask|transparency preserveShape には clippingMask|transparency のいずれかを指定してください diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 77a0172143..917c66ad3e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8495,7 +8495,9 @@ breakText Glyphs 글리프 @msg position must be normal, superscript or subscript position은 normal, superscript 또는 subscript여야 합니다 @msg position must be topLeft, topRight, bottomLeft or bottomRight position은 topLeft, topRight, bottomLeft 또는 bottomRight여야 합니다 @msg positions must be between 0 and 100000 pt positions는 0에서 100000 pt 사이여야 합니다 +@msg ppi can't be more than {max} for this image 이 이미지의 ppi는 {max}보다 클 수 없습니다 @msg ppi must be a positive number, not {ppi} ppi는 양수여야 합니다: {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim은 이미지의 픽셀을 그대로 유지합니다: ppi를 지정하지 마세요 @msg ppi must be between 1 and 2400 ppi는 1에서 2400 사이여야 합니다 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`은(는) transforms|bounds|fileDimensions|fit|fill이 아닙니다 @msg preserveShape must be clippingMask|transparency preserveShape는 clippingMask|transparency여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a6ca78f597..b410962eb7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6834,7 +6834,9 @@ imageTrace Outline Contour @msg position must be normal, superscript or subscript position moet normal, superscript of subscript zijn @msg position must be topLeft, topRight, bottomLeft or bottomRight position moet topLeft, topRight, bottomLeft of bottomRight zijn @msg positions must be between 0 and 100000 pt positions moeten tussen 0 en 100000 pt liggen +@msg ppi can't be more than {max} for this image ppi kan voor deze afbeelding niet hoger zijn dan {max} @msg ppi must be a positive number, not {ppi} ppi moet een positief getal zijn, niet {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim laat de pixels van de afbeelding zoals ze zijn: laat ppi weg @msg ppi must be between 1 and 2400 ppi moet tussen 1 en 2400 liggen @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` is niet transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape moet clippingMask|transparency zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ba909ca1a3..a5951e8c37 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8769,7 +8769,9 @@ breakText Glyphs Glify @msg position must be normal, superscript or subscript position musi mieć wartość normal, superscript lub subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position musi mieć wartość topLeft, topRight, bottomLeft lub bottomRight @msg positions must be between 0 and 100000 pt positions musi mieścić się w zakresie od 0 do 100000 pt +@msg ppi can't be more than {max} for this image ppi nie może przekraczać {max} dla tego obrazu @msg ppi must be a positive number, not {ppi} ppi musi być liczbą dodatnią, a nie {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim zachowuje piksele obrazu bez zmian: pomiń ppi @msg ppi must be between 1 and 2400 ppi musi mieścić się w zakresie od 1 do 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` nie jest jedną z wartości transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape musi mieć wartość clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d891622c53..3a752fba4a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8962,7 +8962,9 @@ swatch Yellow Green Verde-amarelado @msg position must be normal, superscript or subscript position deve ser normal, superscript ou subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position deve ser topLeft, topRight, bottomLeft ou bottomRight @msg positions must be between 0 and 100000 pt positions deve estar entre 0 e 100000 pt +@msg ppi can't be more than {max} for this image ppi não pode ser maior que {max} para esta imagem @msg ppi must be a positive number, not {ppi} ppi deve ser um número positivo, não {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim mantém os pixels da imagem como estão: omita ppi @msg ppi must be between 1 and 2400 ppi deve estar entre 1 e 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` não é transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape deve ser clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6f72fd5a38..fdce0cc732 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8465,7 +8465,9 @@ digits Hindi Hindi @msg position must be normal, superscript or subscript position måste vara normal, superscript eller subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position måste vara topLeft, topRight, bottomLeft eller bottomRight @msg positions must be between 0 and 100000 pt positionerna måste vara mellan 0 och 100 000 pt +@msg ppi can't be more than {max} for this image ppi kan inte vara mer än {max} för den här bilden @msg ppi must be a positive number, not {ppi} ppi måste vara ett positivt tal, inte {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim behåller bildens pixlar som de är: utelämna ppi @msg ppi must be between 1 and 2400 ppi måste vara mellan 1 och 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` är inte transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape måste vara clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 62e389747f..0cbd41f929 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8115,7 +8115,9 @@ axis Y Axis Y ekseni @msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır @msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır @msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır +@msg ppi can't be more than {max} for this image bu görüntü için ppi {max} değerinden büyük olamaz @msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil +@msg trim keeps the image's pixels as they are: leave out ppi trim görüntünün piksellerini olduğu gibi korur: ppi belirtmeyin @msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil @msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7991931baf..6d0012567e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8496,7 +8496,9 @@ breakText Glyphs Гліфи @msg position must be normal, superscript or subscript position має бути normal, superscript або subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position має бути topLeft, topRight, bottomLeft або bottomRight @msg positions must be between 0 and 100000 pt positions мають бути від 0 до 100000 pt +@msg ppi can't be more than {max} for this image ppi для цього зображення не може перевищувати {max} @msg ppi must be a positive number, not {ppi} ppi має бути додатним числом, а не {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim залишає пікселі зображення без змін: не вказуйте ppi @msg ppi must be between 1 and 2400 ppi має бути від 1 до 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` не є transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape має бути clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 85f3986759..d004cceb16 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8755,7 +8755,9 @@ breakText Glyphs 字形 @msg position must be normal, superscript or subscript position 必须是 normal、superscript 或 subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position 必须是 topLeft、topRight、bottomLeft 或 bottomRight @msg positions must be between 0 and 100000 pt positions 必须介于 0 到 100000 pt 之间 +@msg ppi can't be more than {max} for this image 此图像的 ppi 不能超过 {max} @msg ppi must be a positive number, not {ppi} ppi 必须是正数,不能是 {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim 会保持图像像素不变:请省略 ppi @msg ppi must be between 1 and 2400 ppi 必须介于 1 到 2400 之间 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape 必须是 clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3bf87d3eb2..f0747e0b80 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8683,7 +8683,9 @@ breakText Glyphs 字符 @msg position must be normal, superscript or subscript position 必須是 normal、superscript 或 subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position 必須是 topLeft、topRight、bottomLeft 或 bottomRight @msg positions must be between 0 and 100000 pt positions 必須介於 0 到 100000 pt 之間 +@msg ppi can't be more than {max} for this image 此影像的 ppi 不能超過 {max} @msg ppi must be a positive number, not {ppi} ppi 必須是正數,而非 {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim 會保持影像像素不變:請勿指定 ppi @msg ppi must be between 1 and 2400 ppi 必須介於 1 和 2400 之間 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape 必須是 clippingMask|transparency diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 29d89ebf6d..77d1b537f9 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -533,29 +533,66 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) { crate::chrome::group_separator(ui); } -/// Crop Image's box: its centre (X, Y) and size (W, H) in the general unit, set through the tool's -/// `rect` option, then Apply (Enter) and Cancel (Escape). +/// Crop Image's cropping options: the cropped image's resolution (PPI: a list, with the +/// resolutions above what the image allows disabled, or a typed value), the reference point, the +/// box's X and Y (that point) and size (W, H) in the general unit with the link that keeps their +/// proportions, all set through the tool's options; then Apply (Enter) and Cancel (Escape). fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui) { - let set = app.session.tool_options()["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::>()[..] { + use vectorcraft_tools::cropimage::{self as crop, PPI_CHOICES}; + let opts = app.session.tool_options(); + let set = opts["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::>()[..] { [x, y, w, h] => Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h)), _ => None, }); - let Some((_, _, r)) = app.session.active().and_then(|st| vectorcraft_tools::cropimage::crop_box(&st.doc, &st.selection, set)) else { return }; + let Some((r, image, own, max)) = app.session.active().and_then(|st| { + let (id, image, r) = crop::crop_box(&st.doc, &st.selection, set)?; + let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id)?.kind else { return None }; + let (own, max) = crop::image_ppi(im); + Some((r, image, own, max.min(2400.0))) + }) else { + return; + }; + let reference = opts["reference"].as_u64().filter(|v| *v <= 8).map_or(crop::CENTER, |v| v as usize); + let linked = opts["linked"].as_bool().unwrap_or(false); let t = Tokens::get(ui.ctx()); + let set_option = |app: &mut VectorcraftApp, key: &str, value: Value| { + app.run("tool.setOption", json!({ "key": key, "value": value })).ok(); + }; + // Resolution: the list's choices above the image's limit are disabled; a typed value is held to it. + let ppi = opts["ppi"].as_f64().unwrap_or(own); + let label = |v: f64| crate::i18n::fill_once(tl!("{n} ppi"), &[("n", &format!("{}", (v * 100.0).round() / 100.0))]); + let labels: Vec = PPI_CHOICES.iter().map(|v| label(*v)).collect(); + let names: Vec<&str> = labels.iter().map(String::as_str).collect(); + widgets::field_label(ui, egui::RichText::new(tl!("PPI")).size(12.0).color(t.text_dim)); + let current = label(ppi); + if let Some(v) = + widgets::dropdown_with(ui, ("cb-crop", "ppi-list"), ¤t, &names, 80.0, |i| PPI_CHOICES.get(i).is_some_and(|v| *v <= max + 1e-6)) + .and_then(|i| PPI_CHOICES.get(i)) + { + set_option(app, "ppi", json!(v)); + } + // An image's own resolution above the limit (a linked image's, or one past 2400 ppi) still shows + // as it is; an edit there sets at most the limit. + if let Some(v) = widgets::range_field(ui, ("cb-crop", "ppi"), ppi, 1.0..=max.max(ppi).max(1.0), "", 2, 56.0) { + set_option(app, "ppi", json!(v.min(max.max(1.0)))); + } + ui.separator(); + if let Some(i) = widgets::reference_point(ui, reference) { + set_option(app, "reference", json!(i)); + } let units = app.session.general_unit(); - let c = r.center(); - for (k, lbl, v) in [("x", "X:", c.x), ("y", "Y:", c.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { + let p = vectorcraft_geom::reference_point(r, reference); + for (k, lbl, v) in [("x", "X:", p.x), ("y", "Y:", p.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { + if k == "height" + && widgets::icon_button(ui, if linked { "link" } else { "unlink" }, tl!("Constrain Width and Height Proportions"), linked, 22.0).clicked() + { + set_option(app, "linked", json!(!linked)); + } widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); - if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) { - let (mut c, mut w, mut h) = (c, r.width(), r.height()); - match k { - "x" => c.x = nv, - "y" => c.y = nv, - "width" => w = nv.max(0.0), - _ => h = nv.max(0.0), - } - let rect = [c.x - w / 2.0, c.y - h / 2.0, w, h]; - app.run("tool.setOption", json!({ "key": "rect", "value": rect })).ok(); + if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) + && let Some(b) = crop::edited_box(r, image, reference, linked, k, nv) + { + set_option(app, "rect", json!([b.x0, b.y0, b.width(), b.height()])); } } ui.separator(); diff --git a/docs/mcp.md b/docs/mcp.md index 6484c32fea..7330def4ea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1882,6 +1882,21 @@ and `rotate` in `object.transformEach`; `ppi` in `object.rasterize`; `width`, `h four numbers, such as a string, with `rect must be [x, y, width, height]`; a null `rect` crops to the artboard, as a missing one does. +`object.cropImage {ppi}` sets the cropped image's resolution in pixels per inch: the cut pixels are resampled to it, +and the image keeps the size of the crop box. A `rect` over the whole image with a new `ppi` only resamples the image. +An image scaled differently across and down is resampled on both sides, so its pixels come out square at `ppi`. +The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or +300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value +outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with +`ppi must be a positive number, not {ppi}`. A null `ppi` keeps the image's own, as a missing one does, and `ppi` with +`trim` is refused. While the Crop Image tool is chosen, `tool.setOption` sets `ppi` (the resolution Apply sends), +`reference` (0 to 8, left to right and top to bottom: the point of the box that the Control bar's X and Y name and +that its W and H resize about; 4, the center, by default) and `linked` (W and H keep the box's proportions; false by +default). It refuses another value of those three, such as a `ppi` of `"high"`, a `ppi` above what the selected +image allows or a `reference` of 9, and changes nothing; a null `ppi` goes back to the image's own. `tool.options` reads them back with `rect`. +Apply holds a `ppi` set before the image was selected to that image's limit. With `linked` on, a new W or H that would +not fit the image is reduced with the other side in proportion, and the box slides back within the image. + `object.createObjectMosaic` (`columns`, `rows`), `object.transformEach` (`reference`, `seed`) and `artboard.rearrange` (`columns`) take whole numbers, written `4` or `4.0`. A fraction or a negative number is refused with `` `columns` must be a whole number ``. A string or another value that is not a number is refused with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c27883d11..2ce2603750 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1523,6 +1523,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). + While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own. From 8263e36a8f6bcfba8da55642712ed7925d1b1b7e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:18:57 -0800 Subject: [PATCH 10/50] Expand Appearance: shadow and glow images keep their blend mode The image made of an object's shadows and outer glows took the default blend mode, so a Multiply shadow (Drop Shadow's default) over colored art became a plain shadow painted over it. When the shadows and glows all use one blend mode, the image now paints with it, for the object's own effects and for nested symbol instances alike. --- crates/engine/src/cmd/effectcmd.rs | 17 ++++++-- crates/engine/src/tests/expand.rs | 62 ++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cafe5daa23..2c4fad2e81 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -957,9 +957,9 @@ fn is_container(n: &Node) -> bool { /// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at /// the document's raster effects resolution or a Rasterize effect's finer one, with whether they -/// all paint below it (shadows and outer glows: the image then holds just them). A group's or -/// layer's image leaves out its members' raster effects, which are expanded with them. `None` -/// when it has none. +/// all paint below it (shadows and outer glows: the image then holds just them, and paints with +/// their blend mode when they all use one). A group's or layer's image leaves out its members' +/// raster effects, which are expanded with them. `None` when it has none. /// `Err` when that image would take `budget` past its limits: the object then stays as it is. fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result, OverBudget> { let fx = rasterfx::raster_fx(n); @@ -968,12 +968,21 @@ fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::r } let below = fx.iter().all(effects::RasterFx::is_below); let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?; - let image = rasterfx::raster_image(d, n, below, true); + let mut image = rasterfx::raster_image(d, n, below, true); if image.is_none() { // No image was made: it takes nothing from the budget. budget.images += 1; budget.pixels += pixels; } + // Rendered alone, over nothing, the shadows and glows can't blend with the art below the + // object, so the image does, as the canvas draws them. + let mut modes = fx.iter().filter_map(effects::RasterFx::mode); + if below + && let (Some(mode), Some(image)) = (modes.next(), image.as_mut()) + && modes.all(|m| m == mode) + { + image.blend = mode; + } Ok(image.map(|image| (image, below))) } diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 1039dab493..287cbc11da 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -612,6 +612,68 @@ fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() { assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); } +/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it. +fn blue_backdrop(s: &mut Session) { + run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200})); + run(s, "paint.setFill", json!({"color": "#0000ff"})); +} + +/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`. +fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) { + let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"}); + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params})); +} + +/// The blend modes of the images in `n`, in the order the walk visits them. +fn image_modes(n: &Node) -> Vec { + let mut modes = vec![]; + n.walk(&mut |part| { + if matches!(part.kind, NodeKind::Image(_)) { + modes.push(part.blend); + } + }); + modes +} + +/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below +/// as the shadow did, rather than painting red over it. +#[test] +fn a_nested_instance_multiply_shadow_image_keeps_its_mode() { + let mut s = session(); + blue_backdrop(&mut s); + let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply")); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art"); + assert_eq!(image_modes(&n), [BlendMode::Multiply]); + no_effects_left(&n); + let after = render(&s); + assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100)); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply. +#[test] +fn an_instance_multiply_shadow_image_keeps_its_mode() { + let mut s = session(); + blue_backdrop(&mut s); + let (id, row) = instance_with_row(&mut s, "Square", true); + red_shadow_row(&mut s, id, row, "multiply"); + let before = render(&s); + assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(image_modes(&n), [BlendMode::Multiply]); + let after = render(&s); + assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100)); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + /// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it. #[test] fn a_hidden_nested_instance_fill_shadow_makes_no_image() { From bef5bc01e13ba50a5411527b6a91997253c27950 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:32:31 -0800 Subject: [PATCH 11/50] i18n: drop the Georgian justification order row that main now carries main's ka.tsv gained the same `@msg` row, so the catalog held it twice and bundled_catalogs_are_consistent failed. --- crates/ui-egui/src/i18n/ka.tsv | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 629455e5c3..2864881e87 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8418,7 +8418,6 @@ imageTrace Outline კონტური Letter Spacing: ასოებს შორის დაშორება: Word Spacing: სიტყვებს შორის დაშორება: Minimum must not exceed Desired, nor Desired Maximum. მინიმალური არ უნდა აღემატებოდეს სასურველს, ხოლო სასურველი — მაქსიმალურს. -@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: მინიმალური არ უნდა აღემატებოდეს სასურველს, ხოლო სასურველი — მაქსიმალურს Single Word Justification: ერთი სიტყვის სწორება: Apply {name} სტილის „{name}“ გამოყენება Redefine {name} სტილის „{name}“ ხელახლა განსაზღვრა From aca33169543628a947ecb0bec98c6e46fac72fa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:38:04 -0800 Subject: [PATCH 12/50] Expand Appearance: note the image limits in the progress line The progress line said nested symbol instances leave nothing live after Expand Appearance. It now names the 1,024-image and 256-megapixel limits, the objects they leave with their raster effects and the `rasterLeft` warning, and the test that covers them. --- 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 e5ceccb00b..7106292918 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1693,7 +1693,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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`). 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. - Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. No live instance or raster effect is left from those effects, so the result no longer changes with the symbols. The help page describes Expand Appearance turning appearance attributes into objects, and the help page describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. + Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own limits); an object or instance whose image would go past them stays as it is, with its raster effects, and the result reports how many with `rasterLeft` and a warning. Within those limits no live instance or raster effect is left from those effects, so the result no longer changes with the symbols; an instance left by the image limits still follows its symbol. The help page describes Expand Appearance turning appearance attributes into objects, and the help page describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`, `nested_instance_raster_effects_stop_at_the_image_limit`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. 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). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. From 0633645f2401e4b15345a1c863e5a2d6aaeac72f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:13:18 -0800 Subject: [PATCH 13/50] Revolve: a cut side whose holes cannot be found within the limit is refused When the search for holes in a partial sweep's cut sides passes its work limit, Revolve now reports the profile as too complex instead of closing the cut sides with every hole filled. --- crates/three-d/src/lib.rs | 22 ++++++++++------------ crates/three-d/src/tests/cut_sides.rs | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 2790458cc8..e1cd292f1f 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -1089,6 +1089,7 @@ fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec> { return vec![]; } let crossed = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ring, true)]); + // A loop thinner than 0.000001 pt is left out, as the solids' rings leave out such debris. match vectorcraft_pathops::try_unite_all_with(&[(&crossed, FillRule::NonZero)], 1e-6) { Ok(loops) => loops .subpaths @@ -1096,7 +1097,8 @@ fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec> { .map(|s| s.anchors.iter().map(|a| a.p).collect::>()) .filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10) .collect(), - // Past the boolean's limits, the region is kept as the profile draws it. + // Past the boolean's limits the region is kept as the profile draws it, as the solids' + // rings keep theirs. Err(_) if ring_area(&ring).abs() > 1e-10 => vec![ring], Err(_) => vec![], } @@ -1204,13 +1206,12 @@ fn oriented(regions: impl IntoIterator>, bool)>) -> Vec Vec { - let none = vec![false; contours.len()]; +/// when there is only one, walls none. An error when the search passes its limits. +fn holes_of(path: &PathData, rule: FillRule, contours: &[usize]) -> Result, String> { if contours.len() < 2 { - return none; + return Ok(vec![false; contours.len()]); } - let Ok(mut search) = HoleSearch::new(path, rule) else { return none }; + let mut search = HoleSearch::new(path, rule)?; let mut out = Vec::with_capacity(contours.len()); for &k in contours { let Some(sp) = path.subpaths.get(k).filter(|sp| sp.closed) else { @@ -1219,14 +1220,11 @@ fn holes_of(path: &PathData, rule: FillRule, contours: &[usize]) -> Vec { }; let mut walls = 0; for segment in 0..sp.anchors.len() { - match search.is_hole(k, sp.segment(segment).eval(0.5)) { - Ok(hole) => walls += usize::from(hole), - Err(_) => return none, - } + walls += usize::from(search.is_hole(k, sp.segment(segment).eval(0.5))?); } out.push(walls * 2 > sp.anchors.len()); } - out + Ok(out) } impl CutRegions { @@ -1279,7 +1277,7 @@ impl CutRegions { lose_mesh(draw, mesh, lost, e)?; } let contours: Vec = self.drawn.iter().map(|(_, k)| *k).collect(); - let holes = holes_of(path, rule, &contours); + let holes = holes_of(path, rule, &contours)?; cut_faces(at, &oriented(self.drawn.iter().map(|(r, _)| r.clone()).zip(holes)), eye, light) } } diff --git a/crates/three-d/src/tests/cut_sides.rs b/crates/three-d/src/tests/cut_sides.rs index 9d78da3e9d..70b73a4860 100644 --- a/crates/three-d/src/tests/cut_sides.rs +++ b/crates/three-d/src/tests/cut_sides.rs @@ -126,6 +126,29 @@ fn the_mesh_closes_a_cut_side_that_crosses_itself_with_both_of_its_loops() { assert!((start - 1000.0).abs() < 1e-6, "{start}"); } +#[test] +fn a_region_thinner_than_a_millionth_of_a_point_is_debris_and_closes_no_cut_side() { + // 0.0000005 pt wide and 80 pt tall, beside a square 40 pt across. + let path = profile("M40 10 L40.0000005 10 L40.0000005 90 L40 90 Z M50 10 L90 10 L90 50 L50 50 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 90.0, offset: 10.0, ..options() }; + let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, o).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - 40.0 * 40.0).abs() < 1e-6, "{start}"); +} + +#[test] +fn cut_sides_whose_holes_cannot_be_found_within_the_limit_are_refused() { + // 2,100 squares on top of each other: each test of a point meets every square. + let square = "M20 10 L60 10 L60 50 L20 50 Z "; + let path = profile(&square.repeat(2100)); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 90.0, offset: 10.0, ..options() }; + assert_eq!(revolve(&path, bounds, o).err().as_deref(), Some(TOO_COMPLEX_PROFILE)); + // Hollow, the sweep has no cut sides to close. + assert!(revolve(&path, bounds, Revolve { cap_ends: false, ..o }).is_ok()); +} + #[test] fn visibility_keeps_both_of_two_separate_regions_wound_opposite_ways() { let path = profile("M20 10 L30 10 L30 50 L20 50 Z M40 10 L40 50 L50 50 L50 10 Z"); From 3efe88de388f7abc656fff860a137a2f4d46c8fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:08:08 -0800 Subject: [PATCH 14/50] Expand Appearance: an object left by the image limit keeps its color adjustment An object whose raster effects' image would go past the image limits now stays exactly as it was, color adjustment included. Before, the adjustment was still applied, so a color-adjusted symbol instance became a group with a live blur that no longer followed its symbol, and recolored copies of embedded images stayed in the document unused. --- crates/engine/src/cmd/effectcmd.rs | 16 +++++++- crates/engine/src/tests/expand.rs | 66 ++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 2c4fad2e81..b416b202b1 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1193,6 +1193,8 @@ fn expanded_node( if !expandable(&n) { return None; } + // What `out` held before `n`: an object left by the raster budget lists nothing. + let listed_before = out.len(); // Colour adjustments: the colours inside become the adjusted ones (an embedded image a // recoloured copy), then the rest of the appearance expands. let mut changed = false; @@ -1205,6 +1207,10 @@ fn expanded_node( } _ => None, }; + // The embedded images before the adjustment, when the raster budget may yet leave `n` as it + // is: the recolored copies the adjustment adds then go again. + let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) + .then(|| d.images.keys().cloned().collect::>()); if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1251,8 +1257,14 @@ fn expanded_node( return Some(m); } // Raster effects whose image would go past the budget stay: so does the object, with what is - // inside it (a color adjustment already made stays made). - let Ok(image) = raster_image(d, &n, raster) else { return changed.then_some(n) }; + // inside it and its color adjustments (a symbol instance stays an instance of its symbol). + let Ok(image) = raster_image(d, &n, raster) else { + out.truncate(listed_before); + if let Some(keys) = images_before { + d.images.retain(|k, _| keys.contains(k)); + } + return None; + }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 287cbc11da..0cc0106351 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -748,6 +748,72 @@ fn nested_instance_raster_effects_stop_at_the_image_limit() { }); } +/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which +/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was +/// before expanding. +fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node { + // Images of a pixel or two each. + run(s, "document.rasterEffectsSettings", json!({"resolution": 1})); + run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}})); + run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}})); + let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}})); + let before = node(s, id); + let group = { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let blurred = d.node(sq).unwrap().clone(); + d.remove(sq).unwrap(); + let mut members: Vec<_> = (0..1_024) + .map(|_| { + let mut copy = blurred.clone(); + copy.id = d.alloc_id(); + std::sync::Arc::new(copy) + }) + .collect(); + members.push(std::sync::Arc::new(before.clone())); + let group = d.alloc_id(); + *d.node_mut(id).unwrap() = Node::group(group, members); + group + }; + + let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]})); + assert_eq!(r["rasterLeft"], 1, "{r}"); + before +} + +/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance +/// of its symbol, with both effects. +#[test] +fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap()); + let before = adjusted_and_left_by_the_image_limit(&mut s, id); + assert!(matches!(before.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur"); +} + +/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is, +/// and the document keeps no recolored copy of its pixels. +#[test] +fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() { + let mut s = session(); + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let images: Vec = s.doc().unwrap().doc.images.keys().cloned().collect(); + let before = adjusted_and_left_by_the_image_limit(&mut s, id); + assert!(matches!(before.kind, NodeKind::Image(_))); + assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur"); + // Besides the squares' images, the document holds the image's pixels alone. + let after: Vec = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect(); + assert_eq!(after, images, "no recolored copy stays in the document"); +} + /// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the /// shadow on the art's fill, not its stroke, and PDF export makes an image of it. #[test] From a191b0dae58d4c2fda1d435e7f98bae4bd147f8f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:20:09 -0800 Subject: [PATCH 15/50] Revolve: closed subpaths close the cut sides with what the fill rule fills The closed subpaths of a profile now close a partial sweep's cut sides together, with the area the object's fill rule fills, instead of one region per subpath marked as a hole by most of its edges. Two closed subpaths that overlap with only a corner inside each other no longer fill their overlap under the even-odd rule, and under the nonzero rule the overlap is filled once. The cut-side regions are taken after the profile gets the anchor where a mapped side is cut, so the cut sides kept for a mesh have a corner at every corner of the edge they share with the side. --- crates/three-d/src/lib.rs | 174 ++++++++++++++------------ crates/three-d/src/tests/cut_sides.rs | 51 +++++++- docs/mcp.md | 6 +- docs/revolve.md | 10 +- 4 files changed, 146 insertions(+), 95 deletions(-) diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index e1cd292f1f..d01a8b9840 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -1076,15 +1076,7 @@ fn ring_area(ring: &[Point]) -> f64 { /// crosses itself, such as a bow tie, gives a loop for each part it encloses. None when the contour /// encloses no area. fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec> { - let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return vec![] }; - let mut ring = points.to_vec(); - if !closed && first.distance(last) > 1e-10 { - ring.extend([Point::new(axis, last.y), Point::new(axis, first.y)]); - } - ring.dedup_by(|a, b| a.distance(*b) <= 1e-10); - while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-10) { - ring.pop(); - } + let ring = cut_ring(points, closed, axis); if ring.len() < 3 { return vec![]; } @@ -1104,6 +1096,21 @@ fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec> { } } +/// The ring around the region of one contour's profile `points` ([`cut_region`]), without repeated +/// points or a last point that repeats the first. +fn cut_ring(points: &[Point], closed: bool, axis: f64) -> Vec { + let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return vec![] }; + let mut ring = points.to_vec(); + if !closed && first.distance(last) > 1e-10 { + ring.extend([Point::new(axis, last.y), Point::new(axis, first.y)]); + } + ring.dedup_by(|a, b| a.distance(*b) <= 1e-10); + while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-10) { + ring.pop(); + } + ring +} + /// The steps at whose ends the two cut sides of a partial sweep lie, each with its outward normal /// before the view's rotation: the start faces back against the sweep, the end on along it. fn cut_sides(at: &Sweeping) -> [(usize, V3); 2] { @@ -1178,51 +1185,63 @@ fn cut_faces(at: &Sweeping, regions: &[Vec], eye: Option, light: V3) Ok(out) } -/// The regions the cut sides of a partial sweep close ([`cut_region`]), contour by contour: those -/// of the profile drawn, each with its contour's index, and those of the profile kept for a mesh, -/// each with whether it walls a hole. +/// The profiles whose regions the cut sides of a partial sweep close, contour by contour, each with +/// whether its contour is closed: those of the profile drawn, and those of the profile kept for a +/// mesh. Each profile is added as its faces are swept, with any anchor [`ring_cut`] adds, so the +/// cut sides have a corner at every corner of the edges they share with the side. struct CutRegions { /// A partial sweep with caps: there are cut sides to close. on: bool, - drawn: Vec<(Vec>, usize)>, - kept: Vec<(Vec>, bool)>, + drawn: Vec<(Vec, bool)>, + kept: Vec<(Vec, bool)>, } -/// The loops of each contour's region in `regions` turned so a region runs counterclockwise in the -/// profile's plane, or clockwise when it is marked as a hole: filled with the nonzero rule, the -/// holes stay open and every outline fills. A region's largest loop decides, and loops inside it -/// that run the other way stay holes of it. -fn oriented(regions: impl IntoIterator>, bool)>) -> Vec> { +/// The loops of one contour's region turned so the region runs counterclockwise in the profile's +/// plane: filled with the nonzero rule, it fills. Its largest loop decides, and loops inside it that +/// run the other way stay holes of it. +fn outlined(mut loops: Vec>) -> Vec> { + let largest = loops.iter().map(|l| ring_area(l)).max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or_default(); + if largest < 0.0 { + loops.iter_mut().for_each(|l| l.reverse()); + } + loops +} + +/// The regions the cut sides of a partial sweep close for the profiles `contours`, as loops that +/// the nonzero rule fills: outlines run counterclockwise in the profile's plane and holes clockwise. +/// Each open contour closes its own region ([`cut_region`]). The closed contours together close +/// what `rule` fills of them, so a contour that walls a hole leaves it open, and the parts where +/// contours overlap are filled or left open as `rule` fills them; a closed contour alone closes its +/// own region. Every corner of the closed contours' profiles on the region's edge stays a corner +/// of it. An error when the closed contours pass the limits of combining them. +fn cut_loops(contours: &[(Vec, bool)], rule: FillRule, axis: f64) -> Result>, String> { let mut out = vec![]; - for (mut loops, hole) in regions { - let largest = loops.iter().map(|l| ring_area(l)).max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or_default(); - if (largest < 0.0) != hole { - loops.iter_mut().for_each(|l| l.reverse()); + let mut rings = vec![]; + for (points, closed) in contours { + if *closed { + rings.push(points); + } else { + out.extend(outlined(cut_region(points, false, axis))); } - out.extend(loops); } - out -} - -/// Whether each of the closed contours `contours` of `path` walls a hole under `rule`: the fill is -/// outside it and not inside at most of its segments' middles. An open contour, or every contour -/// when there is only one, walls none. An error when the search passes its limits. -fn holes_of(path: &PathData, rule: FillRule, contours: &[usize]) -> Result, String> { - if contours.len() < 2 { - return Ok(vec![false; contours.len()]); - } - let mut search = HoleSearch::new(path, rule)?; - let mut out = Vec::with_capacity(contours.len()); - for &k in contours { - let Some(sp) = path.subpaths.get(k).filter(|sp| sp.closed) else { - out.push(false); - continue; - }; - let mut walls = 0; - for segment in 0..sp.anchors.len() { - walls += usize::from(search.is_hole(k, sp.segment(segment).eval(0.5))?); + match rings.as_slice() { + [] => {} + [one] => out.extend(outlined(cut_region(one, true, axis))), + _ => { + let subpaths = + rings.iter().map(|r| cut_ring(r, true, axis)).filter(|r| r.len() >= 3).map(|r| vectorcraft_geom::SubPath::polyline(&r, true)); + let path = PathData::new(subpaths.collect()); + let filled = vectorcraft_pathops::try_unite_all_with(&[(&path, rule)], 1e-6).map_err(|_| TOO_COMPLEX_PROFILE.to_string())?; + // The union gives outlines counterclockwise and holes clockwise. A loop thinner than + // 0.000001 pt is left out, as in [`cut_region`]. + out.extend( + filled + .subpaths + .iter() + .map(|s| s.anchors.iter().map(|a| a.p).collect::>()) + .filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10), + ); } - out.push(walls * 2 > sp.anchors.len()); } Ok(out) } @@ -1233,33 +1252,22 @@ impl CutRegions { Self { on: o.cap_ends && o.angle > 0.0 && o.angle < 360.0, drawn: vec![], kept: vec![] } } - /// Add the regions of contour `contour`'s profiles: `drawn`, when faces are drawn, and `kept`, - /// when a mesh keeps them. - fn add(&mut self, contour: usize, drawn: Option<&Swept>, kept: Option<&Swept>, closed: bool, axis: f64) { - if !self.on { - return; - } - if let Some(region) = drawn.map(|s| cut_region(&s.points, closed, axis)).filter(|r| !r.is_empty()) { - self.drawn.push((region, contour)); - } - if let Some(s) = kept { - let region = cut_region(&s.points, closed, axis); - // A contour walls a hole when most of its parts do. - let walls = s.holes.iter().filter(|h| **h).count(); - if !region.is_empty() { - self.kept.push((region, walls * 2 > s.holes.len())); - } + /// Add a contour's profile `s`, drawn or kept for a mesh as `kept` says. + fn add(&mut self, s: &Swept, closed: bool, kept: bool) { + if self.on { + let to = if kept { &mut self.kept } else { &mut self.drawn }; + to.push((s.points.clone(), closed)); } } - /// Close the cut sides of sweep `at` of `path`: keep them for the mesh, if any, of `kept` - /// (whether faces are drawn, the mesh, and the error that stopped it, as [`lose_mesh`] takes - /// them) within `face_limit` faces, and give them drawn ([`cut_faces`]), the holes `rule` - /// leaves in `path` left open. + /// Close the cut sides of sweep `at` about `axis`, the holes `rule` leaves left open: keep them + /// for the mesh, if any, of `kept` (whether faces are drawn, the mesh, and the error that + /// stopped it, as [`lose_mesh`] takes them) within `face_limit` faces, and give them drawn + /// ([`cut_faces`]). fn close( &self, at: &Sweeping, - (path, rule): (&PathData, FillRule), + (rule, axis): (FillRule, f64), kept: (bool, &mut Option<&mut Vec>, &mut Option), face_limit: usize, eye: Option, @@ -1267,32 +1275,33 @@ impl CutRegions { ) -> Result, String> { let (draw, mesh, lost) = kept; let result = match mesh.as_deref_mut() { - Some(m) => keep_cuts(at, &self.kept, |contours, normal| { - m.push((contours, normal)); - if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } + Some(m) => cut_loops(&self.kept, rule, axis).and_then(|loops| { + keep_cuts(at, &loops, |contours, normal| { + m.push((contours, normal)); + if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } + }) }), None => Ok(()), }; if let Err(e) = result { lose_mesh(draw, mesh, lost, e)?; } - let contours: Vec = self.drawn.iter().map(|(_, k)| *k).collect(); - let holes = holes_of(path, rule, &contours)?; - cut_faces(at, &oriented(self.drawn.iter().map(|(r, _)| r.clone()).zip(holes)), eye, light) + if !draw { + return Ok(vec![]); + } + cut_faces(at, &cut_loops(&self.drawn, rule, axis)?, eye, light) } } -/// Keep for a mesh the two cut sides of a partial sweep: the regions `regions` of every contour -/// ([`cut_region`]), each marked when it walls a hole, turned to each side. Outlines run one way -/// round and holes the other, so the mesh leaves the holes open. `keep` keeps one face with its -/// outward normal. -fn keep_cuts(at: &Sweeping, regions: &[(Vec>, bool)], mut keep: impl FnMut(Vec>, V3) -> Result<(), String>) -> Result<(), String> { - if regions.is_empty() { +/// Keep for a mesh the two cut sides of a partial sweep: the loops `loops` of their regions +/// ([`cut_loops`]) turned to each side. Outlines run one way round and holes the other, so the mesh +/// leaves the holes open. `keep` keeps one face with its outward normal. +fn keep_cuts(at: &Sweeping, loops: &[Vec], mut keep: impl FnMut(Vec>, V3) -> Result<(), String>) -> Result<(), String> { + if loops.is_empty() { return Ok(()); } - let oriented = oriented(regions.iter().cloned()); for (step, normal) in cut_sides(at) { - let contours = oriented.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); + let contours = loops.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); keep(contours, at.o.rotate(normal))?; } Ok(()) @@ -1490,7 +1499,6 @@ fn revolve_sweep( } } } - cuts.add(contour, draw.then_some(&drawn), mesh.is_some().then_some(&kept), sp.closed, axis); // Which way a profile runs round the region it sweeps (closed against the axis at its ends // when it is open), so the faces' normals point out of the solid. A closed contour that does // not touch the axis has its side cut opposite the middle of its outer side; an anchor goes @@ -1521,6 +1529,7 @@ fn revolve_sweep( }; if let Some(m) = mesh.as_deref_mut() { let turn = prepare(&mut kept); + cuts.add(&kept, sp.closed, true); let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); if let Err(e) = kept { @@ -1531,6 +1540,7 @@ fn revolve_sweep( continue; } let turn = prepare(&mut drawn); + cuts.add(&drawn, sp.closed, false); let profile = &drawn.points; let along = along_profile(profile, axis, sp.closed); for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() { @@ -1591,7 +1601,7 @@ fn revolve_sweep( } } } - cuts.close(&at, (path, rule), (draw, &mut mesh, &mut lost), face_limit, eye, light)?.into_iter().try_for_each(|face| emit(Some(face), 1))?; + cuts.close(&at, (rule, axis), (draw, &mut mesh, &mut lost), face_limit, eye, light)?.into_iter().try_for_each(|face| emit(Some(face), 1))?; faces.sort_by(|a, b| a.depth.total_cmp(&b.depth)); Ok((faces, lost)) } diff --git a/crates/three-d/src/tests/cut_sides.rs b/crates/three-d/src/tests/cut_sides.rs index 70b73a4860..184ce53085 100644 --- a/crates/three-d/src/tests/cut_sides.rs +++ b/crates/three-d/src/tests/cut_sides.rs @@ -87,13 +87,11 @@ fn an_even_odd_hole_wound_with_its_outline_stays_open_in_the_drawn_cut_sides() { assert!(!filled.contains(filled.bounding_box().center())); assert!((area(cut) - (40.0 * 40.0 - 20.0 * 20.0)).abs() < 1e-6, "{}", area(cut)); } - // Under the nonzero rule the inner contour fills too: each side is the outer square and the - // inner one drawn over it. + // Under the nonzero rule the inner contour fills too: each side is the whole outer square. let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::NonZero, ..o }).unwrap(); - let mut areas: Vec = cut_sides(&faces).iter().map(|f| area(f)).collect(); - areas.sort_by(f64::total_cmp); - assert_eq!(areas.len(), 4); - assert!(areas.iter().zip([400.0, 400.0, 1600.0, 1600.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{areas:?}"); + let areas: Vec = cut_sides(&faces).iter().map(|f| area(f)).collect(); + assert_eq!(areas.len(), 2); + assert!(areas.iter().all(|a| (a - 1600.0).abs() < 1e-6), "{areas:?}"); } #[test] @@ -247,6 +245,47 @@ fn the_mesh_closes_both_cut_sides_and_leaves_holes_open_under_either_fill_rule() assert_eq!(area_facing(&hollow, [0.0, 0.0, -1.0]), 0.0); } +#[test] +fn overlapping_contours_close_the_cut_sides_with_what_the_fill_rule_fills() { + // Two squares of 1,600 pt² that overlap in 300 pt², and only one corner of each lies inside + // the other. The even-odd rule leaves the overlap open; the nonzero rule fills it once. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z M50 20 L90 20 L90 60 L50 60 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, ..options() }; + for (rule, expected) in [(FillRule::EvenOdd, 2.0 * (1600.0 - 300.0)), (FillRule::NonZero, 2.0 * 1600.0 - 300.0)] { + let faces = revolve(&path, bounds, Revolve { fill_rule: rule, ..o }).unwrap(); + let cuts = cut_sides(&faces); + let total: f64 = cuts.iter().map(|f| area(f)).sum(); + assert!((total - 2.0 * expected).abs() < 1e-6, "{rule:?}: both sides cover {total}, not twice {expected}"); + let mesh = revolve_mesh(&path, rule, bounds, Revolve { angle: 90.0, ..o }).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}"); + } +} + +#[test] +fn the_cut_sides_kept_for_a_mesh_have_a_corner_at_every_corner_of_the_side() { + // With graphics mapped, the square's side is cut half way round from its outer side, at + // (20, 30), which is not an anchor: the cut side takes that corner too. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 90.0, offset: 10.0, map_surface: true, ..options() }; + let mut faces = vec![]; + revolve_faces(&path, FillRule::NonZero, bounds, o, Some(&mut faces)).unwrap(); + // The corners in the plane where the sweep starts, of every face kept for the mesh and of the + // cut side's alone, which faces back against the sweep. + let in_plane = |all: bool| { + let start = |n: &V3| (n.0.abs() + n.1.abs() + (n.2 + 1.0).abs()) < 1e-9; + let kept = faces.iter().filter(|(_, n)| all || start(n)); + kept.flat_map(|(contours, _)| contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::>() + }; + let cut = in_plane(false); + assert!(!cut.is_empty()); + for p in in_plane(true) { + assert!(cut.iter().any(|q| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9), "{p:?} is not a corner of the cut side"); + } +} + #[test] fn the_mesh_cut_sides_face_out_of_a_sweep_on_the_left_of_its_axis() { // The axis is 40 pt to the right of the line, which sweeps from the left of the axis to its back. diff --git a/docs/mcp.md b/docs/mcp.md index 9eb8c4099a..20d1a2352c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4164,9 +4164,9 @@ default 0), `ambient` (Ambient Light, 0..200%, default 25; an earlier `lightAzim as the same light), `cap` (boolean, default true), and `expandVisibleOnly` (boolean, default true). A vertical-line profile needs a positive offset to have a radius. `cap` closes each circular endpoint of an open profile with one curved, uniformly shaded vector path. Body faces share that curved rim. Partial sweeps use sectors, and `cap` also closes their two -angular cut sides with flat faces: the region between each open subpath and the axis and the area of each closed -subpath, one face for each region. A closed subpath that walls a hole under the object's fill rule leaves that -hole open. +angular cut sides with flat faces: the region between each open subpath and the axis and the area the closed +subpaths fill together under the object's fill rule, one face for each region. A closed subpath that walls a hole +leaves that hole open, and an overlap of closed subpaths is filled or left open as the fill rule fills it. Exported 3D meshes include the cut sides. Missing `cap` enables caps; set it to false for open endpoints and open cut sides (hollow). Shaded Revolve surfaces automatically interpolate curved-surface lighting with vector gradients while preserving profile corners and flat caps. There is no separate smoothing parameter. `shade: false` disables all lighting. Visibility of intersecting surfaces is approximate. `lights` is null by default, retaining the earlier single-light controls. Set an array of one to ten objects to replace that light: `{color: "#rrggbb", intensity: 0..100, rotation: -180..180, height: 0..90, softness: 0..100, behind: bool}`. Defaults per light are white, 80%, 125.26 degrees, 30 degrees, 0%, false. Omitted fields use defaults; unknown nested keys and malformed lists are refused before mutation. `ambient` is shared and counted once. Set `lights: null` to restore the earlier controls. The list is saved in the native file and survives preview, undo and expansion. diff --git a/docs/revolve.md b/docs/revolve.md index 99165377d9..922a1218e2 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -80,10 +80,12 @@ An endpoint on the axis needs no cap. Each open subpath of a compound profile is With an Angle below 360°, Cap also closes the two angular cut sides, so the object appears solid; with Cap off it is hollow ([Revolve options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). Each cut side is flat and uniformly shaded, and is drawn in depth order with the rest of the surface. It covers the -region between each open subpath and the axis, and the area each closed subpath encloses, with one face for each -region. A closed subpath that walls a hole under the object's fill rule leaves that hole open in the face of the -region around it, and the other regions are filled. A self-intersecting subpath fills what the nonzero rule fills, -with one face for each loop it encloses; this is VectorCraft's own rule. A cut side seen edge on is not drawn. +region between each open subpath and the axis, and the area the closed subpaths fill together under the object's +fill rule, with one face for each region. A closed subpath that walls a hole leaves that hole open in the face of +the region around it, and where closed subpaths overlap, the overlap is filled or left open as the fill rule fills +it. A self-intersecting open subpath, or a self-intersecting closed subpath that is the only closed one, fills what +the nonzero rule fills, with one face for each loop it encloses; this is VectorCraft's own rule. A cut side seen edge +on is not drawn. The cut sides appear in preview, SVG/PDF export, Expand Appearance, Expand as Wireframes, Revolve (Classic) and exported 3D meshes. Cap does not make intersecting profiles into a watertight solid. From a91a3c0fd5b37913920b9ea0a19c87ca3b09fd82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:37:42 -0800 Subject: [PATCH 16/50] SVG: a confined Preserve Editing attachment leaves out an Export for Screens folder outside the read roots Under automation read roots, the native document that an SVG or SVGZ carries with Preserve Editing now leaves out the Export for Screens folder (`export_settings.folder`) when that folder is outside the read roots, as `document.exportSettings` already does in its reply. The other export settings and the art are kept, a folder inside the roots is kept, and the open document is not changed. --- crates/engine/src/cmd/fileio/screens.rs | 2 +- crates/engine/src/cmd/fileio/svg.rs | 14 +++++- crates/engine/src/tests/links.rs | 58 +++++++++++++++++++++++++ docs/mcp.md | 3 ++ docs/target-app-parity.md | 1 + 5 files changed, 76 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 61e5fede2a..c4ab3d4ab0 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -764,7 +764,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) { /// Export settings kept in the document or a preset, as the request being served may see them: a /// `folder` outside the read roots ([`super::access::shown`]) is left out. -fn leave_out_unreadable_settings_folder(mut settings: Map) -> Map { +pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map) -> Map { if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) { settings.remove("folder"); } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 44928bf176..bcc01e37a4 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> }) } +/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` +/// outside the read roots of the request being served (the open document keeps it). +fn native_attachment(doc: &Document) -> Vec { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return vectorcraft_format::save(doc, false); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + vectorcraft_format::save(&kept, false) +} + /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they /// link to and the writer's warnings. pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result { let (opts, boards, chosen) = plan(doc, p)?; // Preserve editing embeds the native document (once, shared by every file). - let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false)); + let native = opts.preserve_editing.then(|| native_attachment(doc)); // Draw linked files as vectors when available, or their previews with a warning. Keep // that preparation out of the native attachment so missing links remain relinkable. let (full, warnings) = crate::cmd::place::document::full_documents(doc); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 57bb9e278e..ff933c0fd0 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2138,3 +2138,61 @@ 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 and SVGZ with Preserve Editing Capabilities carry a native document +/// without the Export for Screens folder when it is outside the read roots, with the other export +/// settings and the art; the open document keeps the folder. A folder inside the roots, and any +/// folder without roots, stays in the attachment. +#[test] +fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-export-folder-away"); + let home = Folder::new("svg-export-folder-home"); + let outside = away.0.to_string_lossy().into_owned(); + let inside = home.file("screens"); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + let set_folder = |s: &mut Session, folder: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap(); + }; + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + // The native document an SVG's text carries. + let attached = |text: &str| { + let data = vectorcraft_svg::editing_data(text).expect("editing data"); + vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap() + }; + let check = |d: &Document, folder: Option<&str>, what: &str| { + assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}"); + assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}"); + assert!(d.node(rect).is_some(), "{what}: no art"); + }; + // Every way an SVG is asked for with Preserve Editing, its text and its native document. + let every = |s: &mut Session, confined: bool, folder: Option<&str>| { + let run = |s: &mut Session, cmd: &str, p: Value| { + let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) }; + r.unwrap() + }; + for format in ["svg", "svgz"] { + let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true})); + check(&attached(&svg_text(&r)), folder, &format!("{format} serialize")); + let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}})); + check(&attached(&svg_text(&r)), folder, &format!("{format} options object")); + let path = home.file(&format!("export.{format}")); + run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true})); + let bytes = std::fs::read(&path).unwrap(); + check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export")); + } + }; + set_folder(&mut s, &outside); + every(&mut s, true, None); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str())); + every(&mut s, false, Some(&outside)); + // Without Preserve Editing the SVG carries no native document. + let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap(); + assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}"); + set_folder(&mut s, &inside); + every(&mut s, true, Some(&inside)); +} diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..d3780a52f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -261,6 +261,9 @@ the suite) keep the agent to the folders you give it: selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked. +- With `preserveEditing`, the document an SVG or SVGZ of these outputs carries leaves out the Export for Screens + folder (`export_settings.folder`) when it is outside the read roots, as `document.exportSettings` does; the + other export settings and the art are kept, and the open document keeps the folder. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..2216b04ded 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -878,6 +878,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). + - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). - 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 5412c911cf8c0ef4cf9a5aedfb82fa2b5837c260 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:39:45 -0800 Subject: [PATCH 17/50] Graph Type: Draw Filled Lines takes a Line Width Graph Type has a Line Width field next to Draw Filled Lines, and `graph.setType` takes `lineWidth` in points (0.01 to 1000; 3 when the graph sets none). Filled lines are drawn at that width, and the width is kept through save and open. A graph stores a width only when it is not 3 pt, and a graph with a width of its own is written to .ai as its art. `graph.setType` with options that leave the graph as it is records no undo step. --- crates/doc/src/graph.rs | 20 ++++++++++ crates/doc/src/lib.rs | 4 +- crates/engine/src/cmd/graph/commands.rs | 2 +- crates/engine/src/cmd/graph/edit.rs | 17 ++++++++ crates/engine/src/cmd/graph/labels.rs | 8 ++-- crates/engine/src/cmd/graph/tests.rs | 49 ++++++++++++++++++++++++ crates/eps/src/ai_graph.rs | 5 ++- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/graph_type.rs | 41 ++++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 11 +++++- docs/target-app-parity.md | 2 +- 40 files changed, 174 insertions(+), 17 deletions(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 58b52dd651..820e0ddc8d 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -483,6 +483,10 @@ pub struct GraphSpec { pub first_column_in_front: bool, #[serde(skip_serializing_if = "std::ops::Not::not")] pub filled_lines: bool, + /// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws + /// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub line_width: Option, /// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the /// legend in rows above the plot instead of a column on its right). #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -557,6 +561,21 @@ fn is_zero(n: &usize) -> bool { *n == 0 } +/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and +/// greatest widths a graph takes, in points. +pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0; +pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01; +pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0; + +impl GraphSpec { + /// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A + /// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the + /// default. + pub fn filled_line_width(&self) -> f64 { + self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH) + } +} + /// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then. fn edge_to_edge_before_the_option() -> bool { true @@ -696,6 +715,7 @@ impl Default for GraphSpec { first_row_in_front: false, first_column_in_front: false, filled_lines: false, + line_width: None, drop_shadow: false, legend_across_top: false, pie_legend_in_wedges: false, diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7b7ef4fee7..788abd2d78 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -94,8 +94,8 @@ pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ - ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, - PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, + ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH, + MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, }; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 7084fe19f6..27da7936a8 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Type…", ["Object", "Graph"], None, - "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", + "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as bands `lineWidth` wide filled with the series colour), lineWidth?: pt (Line Width of Draw Filled Lines: 0.01–1000; 3), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; options that leave the graph as it is record no step of history; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", has_selection, set_type ), diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 378a8e3745..728eff6427 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -230,6 +230,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value "prefix": one_line(&spec.prefix), "suffix": one_line(&spec.suffix), "rightPrefix": one_line(&spec.right_prefix), "rightSuffix": one_line(&spec.right_suffix), "dropShadow": spec.drop_shadow, "legendAcrossTop": spec.legend_across_top, "firstRowInFront": spec.first_row_in_front, "firstColumnInFront": spec.first_column_in_front, "filledLines": spec.filled_lines, + "lineWidth": spec.filled_line_width(), }); // Only the options this graph's types use: overlap order for columns and bars, filled lines for lines. let kinds: Vec = (0..count.max(1)).map(|i| spec.series_kind(i)).collect(); @@ -241,6 +242,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value } if !has(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]) { o.remove("filledLines"); + o.remove("lineWidth"); } } // Pie graphs: Legend, Position and Sort (their Legend stands for the legend checkbox). @@ -266,6 +268,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { const C: &str = "graph.setType"; let id = target(s, p, C)?; let mut spec = spec_of(s, id)?; + let stored = spec.clone(); // The series to retype: `seriesIndexes`, else, with no `id`, a selection made only of this graph's series (Group // Selection). Anything else selected, the graph itself for one, is the whole graph. let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); @@ -311,6 +314,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { "firstRowInFront", "firstColumnInFront", "filledLines", + "lineWidth", "pieLegend", "piePosition", "pieSort", @@ -404,6 +408,15 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?; spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?; spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?; + if let Some(w) = p.get("lineWidth").filter(|v| !v.is_null()) { + let w = w.as_f64().ok_or_else(|| bad(C, format!("`lineWidth` must be a number, not {w}")))?; + let (min, max) = (vectorcraft_doc::MIN_FILLED_LINE_WIDTH, vectorcraft_doc::MAX_FILLED_LINE_WIDTH); + if !(min..=max).contains(&w) { + return Err(bad(C, format!("`lineWidth` must be from {min} to {max} pt, not {w}"))); + } + // The default width is stored as no width. + spec.line_width = (w != vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH).then_some(w); + } spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?; // After `legend`, which the Graph Type dialog sends too. if let Some(v) = text_param(p, "pieLegend", C)? { @@ -418,6 +431,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?; spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?; spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks); + // Options that leave the graph as it is record no step of history. + if spec == stored { + return Ok(json!({ "id": id.0 })); + } let label = format!("{} Graph", spec.kind.label()); s.edit("Graph Type", |d, sel| { regenerate(d, id, spec)?; diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 8e56ad8ae6..27ae422b32 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -177,10 +177,11 @@ impl Gen<'_> { Arc::new(g) } /// A series' line joining its data points (Connect Data Points): a 1 pt stroke in the series colour, or with Draw - /// Filled Lines a band FILLED_LINE_WIDTH wide filled with it and outlined in black. + /// Filled Lines a band as wide as the graph's Line Width ([`GraphSpec::filled_line_width`]) filled with it and outlined + /// in black. pub(super) fn data_line(&mut self, g: &GraphSpec, s: usize, pd: PathData, filled: bool) -> Arc { let band = if filled { - vectorcraft_pathops::outline_stroke(&pd, FILLED_LINE_WIDTH, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0) + vectorcraft_pathops::outline_stroke(&pd, g.filled_line_width(), vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0) } else { PathData::default() }; @@ -234,9 +235,6 @@ const SHADOW_OFFSET: f64 = 2.0; pub(super) const SHADOW_OPACITY: f32 = 0.35; -/// Draw Filled Lines: how wide a filled line is. -const FILLED_LINE_WIDTH: f64 = 3.0; - const FILLED_LINE_BUDGET: usize = 20_000; /// Does graph `g`, with `series` series, draw Filled Lines (up to FILLED_LINE_BUDGET data points)? diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c533cb5e4e..43af02f226 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6443,6 +6443,54 @@ fn filled_lines_keep_the_line_colour_and_fall_back_to_thin_lines() { assert!(series_parts(&s, big, 0)[0].appearance.fill_paint().is_none()); } +/// Line Width sets how wide Draw Filled Lines draws the bands and is kept through save and open. A width outside 0.01 +/// to 1000 pt is refused, the same width again records no undo step, and the default 3 pt is stored as no width. +#[test] +fn filled_lines_take_a_line_width() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "line", ",a\nQ1,2\nQ2,2\nQ3,2"); + s.execute("graph.setType", &json!({"id": id.0, "filledLines": true})).unwrap(); + let height = |s: &Session| series_parts(s, id, 0)[0].geometric_bounds().unwrap().height(); + assert!((height(&s) - 3.0).abs() < 1e-6, "3 pt by default: {}", height(&s)); + assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(3.0)); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 8})).unwrap(); + assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s)); + assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(8.0)); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + for p in [json!({"id": id.0, "lineWidth": 8}), json!({"id": id.0, "lineWidth": 8.0, "filledLines": true}), json!({"id": id.0, "lineWidth": null})] + { + s.execute("graph.setType", &p).unwrap(); + assert_eq!(steps(&s), before, "nothing changed: {p}"); + } + for w in [json!(0), json!(-2), json!(0.005), json!(1000.5)] { + let e = s.execute("graph.setType", &json!({"id": id.0, "lineWidth": w})).unwrap_err().to_string(); + assert!(e.contains(&format!("`lineWidth` must be from 0.01 to 1000 pt, not {}", w.as_f64().unwrap())), "{e}"); + assert_eq!((steps(&s), spec(&s, id).line_width), (before, Some(8.0)), "{w}"); + } + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 0.01})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(0.01)); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 1000})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(1000.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(8.0)); + // Kept through save and open. + let dir = vectorcraft_testkit::TempDir::new("graph-line-width"); + let path = dir.join("width.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(8.0)); + assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s)); + // The default width is stored as no width, so the file keeps no `lineWidth`. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 3})).unwrap(); + assert_eq!(spec(&s, id).line_width, None); + assert!(serde_json::to_value(spec(&s, id)).unwrap().get("lineWidth").is_none()); + assert!((height(&s) - 3.0).abs() < 1e-6, "{}", height(&s)); +} + #[test] fn overlapping_columns_keep_clear_of_the_legend_and_options_follow_the_graph_type() { let mut s = Session::new(); @@ -8029,6 +8077,7 @@ fn graph_commands_refuse_params_of_the_wrong_type() { ("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"), ("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"), ("filledLines", json!("on"), "`filledLines` must be true or false"), + ("lineWidth", json!("4"), "`lineWidth` must be a number, not \"4\""), ("dropShadow", json!(1), "`dropShadow` must be true or false"), ("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"), ("type", json!(5), "`type` must be a string"), diff --git a/crates/eps/src/ai_graph.rs b/crates/eps/src/ai_graph.rs index 3e1cebd9f9..d2db08229f 100644 --- a/crates/eps/src/ai_graph.rs +++ b/crates/eps/src/ai_graph.rs @@ -233,7 +233,8 @@ fn tick(t: TickLength) -> u8 { } /// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across -/// the top, every series of the graph's type, one value axis on the left, lines not filled, no graph +/// the top, every series of the graph's type, one value axis on the left, lines not filled and no +/// Line Width of their own, no graph /// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most /// [`MAX_TICK_MARKS`] tick marks a division. fn settings_kept(g: &GraphSpec) -> bool { @@ -244,6 +245,7 @@ fn settings_kept(g: &GraphSpec) -> bool { && !g.separate_scales && g.right_series.is_empty() && !g.filled_lines + && g.line_width.is_none() && g.series_markers.iter().all(Option::is_none) && g.series_columns.iter().all(Option::is_none) && g.label_styles == LabelStyles::default() @@ -514,6 +516,7 @@ pub(crate) mod sample { cases.extend([ ("no legend", with(&|g| g.legend = false)), ("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))), + ("a filled line width", with(&|g| (g.kind, g.line_width) = (GraphKind::Line, Some(8.0)))), ("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])), ("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])), ("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8e651622af..06901c1181 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -973,7 +973,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 083adfacb6..170dad3552 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -10,8 +10,8 @@ //! without a step of history. //! //! Fields: the options `graph.setType {}` returns under the command's names for them, with -//! `legend`, `pieLegend`, `piePosition`, `pieSort`, `firstRowInFront`, `firstColumnInFront` and -//! `filledLines` held for every type, and `type` or `valueAxis` null while the picked series +//! `legend`, `pieLegend`, `piePosition`, `pieSort`, `firstRowInFront`, `firstColumnInFront`, +//! `filledLines` and `lineWidth` held for every type, and `type` or `valueAxis` null while the picked series //! differ in it (OK then leaves each series as it is); `overrideValues` and `rightOverrideValues` (Override //! Calculated Values of the left or only value axis and of the right one: while one is on, OK //! sends `axisMin`, `axisMax` and `ticks`, or `rightAxisMin`, `rightAxisMax` and `rightTicks`); and @@ -60,6 +60,8 @@ const WIDTHS: RangeInclusive = 1.0..=1000.0; /// The divisions it takes for a value axis, and the tick marks it takes per division. const DIVISIONS: RangeInclusive = 1.0..=100.0; const TICK_MARKS: RangeInclusive = 1.0..=20.0; +/// The Line Width it takes for Draw Filled Lines, in points. +const LINE_WIDTHS: RangeInclusive = vectorcraft_doc::MIN_FILLED_LINE_WIDTH..=vectorcraft_doc::MAX_FILLED_LINE_WIDTH; /// The characters it keeps of a prefix or suffix. const AFFIX_CHARS: usize = 64; /// The divisions it draws an overridden value axis in while the axis has no count of its own. @@ -86,7 +88,7 @@ const PIE_SORTS: [(&str, &str); 3] = [("all", "All"), ("first", "First"), ("none /// The options OK always sends. `valueAxis` is left out while the picked series are on both axes, /// and the legend and the tick values follow the type and Override Calculated Values. -const SENT: [&str; 24] = [ +const SENT: [&str; 25] = [ "type", "valueAxis", "separateScales", @@ -100,6 +102,7 @@ const SENT: [&str; 24] = [ "connectPoints", "edgeToEdge", "filledLines", + "lineWidth", "tickLength", "tickMarks", "rightTickLength", @@ -183,6 +186,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ("firstRowInFront", json!(spec.first_row_in_front)), ("firstColumnInFront", json!(spec.first_column_in_front)), ("filledLines", json!(spec.filled_lines)), + ("lineWidth", json!(spec.filled_line_width())), ("legend", json!(spec.legend)), ("pieLegend", json!(pie_legend)), ("piePosition", json!(spec.pie_position.id())), @@ -672,6 +676,11 @@ fn type_options(ui: &mut egui::Ui, d: &mut Dialog, kind: GraphKind) { check(ui, d, "filledLines", tl!("Draw Filled Lines"), connected); ui.end_row(); }); + // Line Width sets how wide Draw Filled Lines draws the lines. + let shown = number(d, "lineWidth").unwrap_or(vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH); + ui.add_enabled_ui(connected && d.bool("filledLines"), |ui| { + ranged(ui, d, "lineWidth", &colon(tl!("Line Width")), shown, (LINE_WIDTHS, " pt", 2)); + }); } if pie { choice(ui, d, "pieLegend", &colon(tl!("Legend")), &PIE_LEGENDS); @@ -1062,6 +1071,32 @@ mod tests { assert!(!field(&h, "Column Width:") && !checkbox(&h, "Mark Data Points") && !menu(&h, "Legend:") && h.query_by_label("Options").is_none()); } + /// Line Width next to Draw Filled Lines shows the graph's width, is available only while Draw + /// Filled Lines is on, and OK gives the graph the width typed. + #[test] + fn line_width_goes_with_draw_filled_lines() { + let mut app = app_with_graph("line"); + open(&mut app).unwrap(); + assert_eq!(number(app.ui.dialog.as_ref().unwrap(), "lineWidth"), Some(vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH)); + let mut h = harness(app); + let dimmed = |h: &Harness| h.get_by_role_and_label(Role::TextInput, "Line Width:").accesskit_node().is_disabled(); + assert!(dimmed(&h), "Draw Filled Lines is off"); + h.get_by_role_and_label(Role::CheckBox, "Draw Filled Lines").click(); + h.run_steps(3); + assert!(!dimmed(&h)); + h.check_accessibility(); + set(h.state_mut(), "connectPoints", json!(false)); + h.run_steps(3); + assert!(dimmed(&h), "no lines to fill"); + set(h.state_mut(), "connectPoints", json!(true)); + set(h.state_mut(), "lineWidth", json!(6.5)); + let app = h.state_mut(); + let before = steps(app); + crate::dialogs::confirm(app).unwrap(); + assert_eq!((query(app)["filledLines"].clone(), query(app)["lineWidth"].clone()), (json!(true), json!(6.5))); + assert_eq!(steps(app), before + 1, "one step of history"); + } + /// The menu at the top lists a page per axis of the type picked, and a second value axis page /// while the value axis is on both sides. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a6a69d9100..edb2a7dafe 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1395,6 +1395,7 @@ font-technology Variable Променливи Connect Data Points Свързване на точките от данни Edge-to-Edge Lines Линии от край до край Draw Filled Lines Чертане на запълнени линии + Line Width Ширина на линията Tick Values Стойности на отметките Override Calculated Values Замяна на изчислените стойности Divisions Деления diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5da48b6cff..6dbf66beda 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3616,6 +3616,7 @@ theme Appearance Izgled Connect Data Points Poveži tačke podataka Edge-to-Edge Lines Linije od ivice do ivice Draw Filled Lines Crtaj ispunjene linije + Line Width Širina linije Tick Values Vrijednosti crtica Override Calculated Values Zamijeni izračunate vrijednosti Divisions Podioci diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e861e61fec..2d716f2a6a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1927,6 +1927,7 @@ digits Malayalam Malaiàlam Connect Data Points Connecta els punts de dades Edge-to-Edge Lines Línies de vora a vora Draw Filled Lines Dibuixa línies emplenades + Line Width Amplada de línia Tick Values Valors de les marques Override Calculated Values Substitueix els valors calculats Divisions Divisions diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..92a55de7a5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3712,6 +3712,7 @@ theme Appearance Motiv Connect Data Points Spojit datové body Edge-to-Edge Lines Čáry od okraje k okraji Draw Filled Lines Kreslit vyplněné čáry + Line Width Šířka čáry Tick Values Hodnoty značek Override Calculated Values Přepsat vypočítané hodnoty Divisions Dílky diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..1d956f8874 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4059,6 +4059,7 @@ theme Appearance Udseende Connect Data Points Forbind datapunkter Edge-to-Edge Lines Linjer fra kant til kant Draw Filled Lines Tegn udfyldte linjer + Line Width Linjebredde Tick Values Afmærkningsværdier Override Calculated Values Tilsidesæt beregnede værdier Divisions Inddelinger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..65718ce4c6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1438,6 +1438,7 @@ file-filter Templates Vorlagen Connect Data Points Datenpunkte verbinden Edge-to-Edge Lines Linien von Kante zu Kante Draw Filled Lines Gefüllte Linien zeichnen + Line Width Linienbreite Tick Values Teilstrichwerte Override Calculated Values Berechnete Werte überschreiben Divisions Teilungen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..7343bcf773 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1370,6 +1370,7 @@ font-technology Variable Μεταβλητές Connect Data Points Σύνδεση σημείων δεδομένων Edge-to-Edge Lines Γραμμές από άκρη σε άκρη Draw Filled Lines Σχεδίαση γεμισμένων γραμμών + Line Width Πλάτος γραμμής Tick Values Τιμές υποδιαιρέσεων Override Calculated Values Αντικατάσταση υπολογισμένων τιμών Divisions Διαιρέσεις diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..6e1191465f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1449,6 +1449,7 @@ font-technology Variable Variables Connect Data Points Conectar puntos de datos Edge-to-Edge Lines Líneas de borde a borde Draw Filled Lines Dibujar líneas rellenas + Line Width Ancho de línea Tick Values Valores de marcas Override Calculated Values Sustituir valores calculados Divisions Divisiones diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..75581f9e71 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3650,6 +3650,7 @@ theme Appearance Ulkoasu Connect Data Points Yhdistä arvopisteet Edge-to-Edge Lines Viivat reunasta reunaan Draw Filled Lines Piirrä täytetyt viivat + Line Width Viivan leveys Tick Values Asteikon arvot Override Calculated Values Ohita lasketut arvot Divisions Jaot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..594e7e2f13 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1443,6 +1443,7 @@ font-technology Variable Variables Connect Data Points Relier les points de données Edge-to-Edge Lines Lignes bord à bord Draw Filled Lines Tracer des lignes pleines + Line Width Épaisseur de ligne Tick Values Valeurs des graduations Override Calculated Values Remplacer les valeurs calculées Divisions Divisions diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ff59a464c5..44448f7a29 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1565,6 +1565,7 @@ Connect Data Points ડેટા પોઇન્ટ જોડો Edge-to-Edge Lines કિનારીથી કિનારી સુધી રેખાઓ Draw Filled Lines ભરેલી રેખાઓ દોરો + Line Width રેખાની પહોળાઈ Tick Values ટિક મૂલ્યો Override Calculated Values ગણતરી કરેલાં મૂલ્યો બદલો Divisions વિભાગો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..9594829cd6 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2142,6 +2142,7 @@ antiAlias Sharp शार्प Connect Data Points डेटा पॉइंट जोड़ें Edge-to-Edge Lines किनारे से किनारे तक रेखाएँ Draw Filled Lines भरी हुई रेखाएँ बनाएँ + Line Width रेखा की चौड़ाई Tick Values टिक मान Override Calculated Values परिकलित मानों को बदलें Divisions विभाजन diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..559f700287 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1801,6 +1801,7 @@ file-filter Templates Sablonok Connect Data Points Adatpontok összekötése Edge-to-Edge Lines Széltől szélig érő vonalak Draw Filled Lines Kitöltött vonalak rajzolása + Line Width Vonalvastagság Tick Values Osztásértékek Override Calculated Values Számított értékek felülírása Divisions Osztások diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf029526f7..ff7e718bed 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3393,6 +3393,7 @@ theme Appearance Tampilan Connect Data Points Hubungkan titik data Edge-to-Edge Lines Garis dari tepi ke tepi Draw Filled Lines Gambar garis terisi + Line Width Lebar garis Tick Values Nilai tanda skala Override Calculated Values Timpa nilai terhitung Divisions Pembagian diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..2f04c0c406 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1468,6 +1468,7 @@ file-filter Templates Modelli Connect Data Points Collega punti dati Edge-to-Edge Lines Linee da bordo a bordo Draw Filled Lines Disegna linee piene + Line Width Spessore linea Tick Values Valori delle tacche Override Calculated Values Sostituisci valori calcolati Divisions Divisioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..fe1cbb0736 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3891,6 +3891,7 @@ file-filter Templates テンプレート Connect Data Points データポイントを線でつなぐ Edge-to-Edge Lines 端から端までの線 Draw Filled Lines 線を塗りつぶして描く + Line Width 線幅 Tick Values 目盛りの値 Override Calculated Values 計算値を上書き Divisions 分割数 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..1b297e9904 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5366,6 +5366,7 @@ theme Appearance იერსახე Connect Data Points მონაცემთა წერტილების შეერთება Edge-to-Edge Lines ხაზები კიდიდან კიდემდე Draw Filled Lines შევსებული ხაზების დახატვა + Line Width ხაზის სიგანე Tick Values დანაყოფების მნიშვნელობები Override Calculated Values გამოთვლილი მნიშვნელობების შეცვლა Divisions დანაყოფები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..4a55cae141 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3879,6 +3879,7 @@ file-filter Templates 템플릿 Connect Data Points 데이터 요소 연결 Edge-to-Edge Lines 가장자리 간 선 Draw Filled Lines 채워진 선 그리기 + Line Width 선 너비 Tick Values 눈금 값 Override Calculated Values 계산된 값 재정의 Divisions 구간 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..4b9080af1f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3955,6 +3955,7 @@ theme Appearance Vormgeving Connect Data Points Gegevenspunten verbinden Edge-to-Edge Lines Lijnen van rand tot rand Draw Filled Lines Gevulde lijnen tekenen + Line Width Lijndikte Tick Values Maatstreepwaarden Override Calculated Values Berekende waarden negeren Divisions Verdelingen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..e7187c5026 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3591,6 +3591,7 @@ theme Appearance Wygląd Connect Data Points Połącz punkty danych Edge-to-Edge Lines Linie od krawędzi do krawędzi Draw Filled Lines Rysuj wypełnione linie + Line Width Szerokość linii Tick Values Wartości podziałki Override Calculated Values Zastąp obliczone wartości Divisions Podziały diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..eb1999e823 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5010,6 +5010,7 @@ axis Both Ambos Connect Data Points Conectar Pontos de Dados Edge-to-Edge Lines Linhas de Borda a Borda Draw Filled Lines Desenhar Linhas Preenchidas + Line Width Largura da Linha Tick Values Valores das Marcas Override Calculated Values Substituir Valores Calculados Divisions Divisões diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..0aaba78287 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1459,6 +1459,7 @@ file-filter Templates Шаблоны Connect Data Points Соединять точки данных Edge-to-Edge Lines Линии от края до края Draw Filled Lines Рисовать заполненные линии + Line Width Ширина линии Tick Values Значения делений Override Calculated Values Заменить вычисленные значения Divisions Деления diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..b65e9135b6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1406,6 +1406,7 @@ font-technology Variable Variabla Connect Data Points Förbind datapunkter Edge-to-Edge Lines Linjer från kant till kant Draw Filled Lines Rita fyllda linjer + Line Width Linjebredd Tick Values Skalstrecksvärden Override Calculated Values Åsidosätt beräknade värden Divisions Indelningar diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..e261eeaab8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1374,6 +1374,7 @@ font-technology Variable Değişken Connect Data Points Veri Noktalarını Bağla Edge-to-Edge Lines Kenardan Kenara Çizgiler Draw Filled Lines Dolgulu Çizgiler Çiz + Line Width Çizgi Genişliği Tick Values Onay İşareti Değerleri Override Calculated Values Hesaplanan Değerleri Geçersiz Kıl Divisions Bölümler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..152f75a94b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1462,6 +1462,7 @@ file-filter Templates Шаблони Connect Data Points З'єднувати точки даних Edge-to-Edge Lines Лінії від краю до краю Draw Filled Lines Малювати заповнені лінії + Line Width Ширина лінії Tick Values Значення поділок Override Calculated Values Замінити обчислені значення Divisions Поділки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..1e39d1ae0f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1721,6 +1721,7 @@ file-filter Templates Mẫu Connect Data Points Nối các điểm dữ liệu Edge-to-Edge Lines Đường từ mép đến mép Draw Filled Lines Vẽ đường tô đầy + Line Width Độ rộng đường Tick Values Giá trị vạch chia Override Calculated Values Ghi đè giá trị đã tính Divisions Số khoảng chia diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..75c709f1bd 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1397,6 +1397,7 @@ file-filter Templates 模板 Connect Data Points 连接数据点 Edge-to-Edge Lines 边到边线条 Draw Filled Lines 绘制填充线 + Line Width 线宽 Tick Values 刻度值 Override Calculated Values 覆盖计算值 Divisions 刻度数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..4d394abc5e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1432,6 +1432,7 @@ file-filter Templates 範本 Connect Data Points 連接資料點 Edge-to-Edge Lines 邊到邊線條 Draw Filled Lines 繪製填色線條 + Line Width 線寬 Tick Values 刻度值 Override Calculated Values 覆寫計算值 Divisions 刻度數 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4c286f1da9..3c721937bf 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -974,7 +974,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..2bbfb07418 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1964,6 +1964,12 @@ were. `graph.setType` refuses `` `columnWidth` must be a number, not "50" `` for `` `type` must be a string `` for `type`, `valueAxis`, the three tick lengths, `prefix`, `suffix`, `rightPrefix`, `rightSuffix`, `pieLegend`, `piePosition` and `pieSort`; and `` `ticks` must be a number, not "5" `` (or `` `ticks` must be 0 or more `` for a negative number) for `ticks`, `rightTicks` and the three tick mark counts. +`lineWidth`, the Line Width of Draw Filled Lines in points (3 when the graph sets none), takes a number from 0.01 to +1000 (VectorCraft's own range); `"4"` is refused with `` `lineWidth` must be a number, not "4" ``, and a width below +0.01 or past 1000 with `` `lineWidth` must be from 0.01 to 1000 pt, not 0 ``. The graph stores a width only when it is +not 3, so a graph without one is saved and drawn as before. A graph with a width of its own is written to `.ai` as its +art, without the editable graph records. `graph.setType` with options that leave the graph as it is +records no undo step. `axisMin`, `axisMax`, `rightAxisMin` and `rightAxisMax` take a number, or null to go back to the value calculated from the data; any other value is refused with `` `axisMin` must be a number or null, not "10" ``. `graph.setData` and `graph.create` refuse a `csv` that is not a string, `series` or `categories` that are not lists, and `rows` that are not @@ -10901,8 +10907,9 @@ A canvas-click dialog also has `preview` (initially on): tentative settings draw Object › Graph › Type… (`graph.setType` without params) and a double-click on a graph tool open Graph Type (dialog `graphType`) for the selected graph, or for the series picked in it with Group Selection. Its fields are the options `graph.setType {}` returns, under the command's names for them. `legend`, `pieLegend`, `piePosition`, `pieSort`, -`firstRowInFront`, `firstColumnInFront` and `filledLines` are held for every type, so a type picked in the dialog shows -the options it uses. `overrideValues` and `rightOverrideValues` are Override Calculated Values of the left (or only) +`firstRowInFront`, `firstColumnInFront`, `filledLines` and `lineWidth` are held for every type, so a type picked in the +dialog shows the options it uses. The Line Width field next to Draw Filled Lines is available only while Draw Filled +Lines is on. `overrideValues` and `rightOverrideValues` are Override Calculated Values of the left (or only) value axis and of the right one. While one is on, OK sends `axisMin`, `axisMax` and `ticks` (or `rightAxisMin`, `rightAxisMax` and `rightTicks`), and the dialog fills the ones the graph lacks with the values the axis would be calculated with for the type, value axis and Separate Scales the dialog shows. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 65cbf9e216..77348b08dc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1209,7 +1209,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines at its Line Width (3 pt when none is set, 0.01 to 1000 pt), adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are. What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. From 49d53b8aaf15429bbf5f071ac9fee0904fab420f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:48:39 -0800 Subject: [PATCH 18/50] Crop Image: keep faint colors, the box's content and the settings of a failed crop - Resampling at a resolution asked for weights colors by alpha in 16 bits a channel, so a pixel with alpha 1 keeps its color instead of turning black. - A box between pixels is drawn with the image stretched so the box fills the whole pixels drawn; nothing past the box is squeezed into it. - A linked W or H below a point raises both sides together, keeping the box's proportions. - Apply no longer clears the box and the resolution; leaving the tool does, so a crop that fails keeps them for another try. --- crates/engine/src/cmd/menucmds.rs | 44 ++++++++++----- crates/engine/src/tests/menucmds.rs | 52 +++++++++++++++++- crates/tools/src/cropimage.rs | 85 ++++++++++++++++++++--------- 3 files changed, 142 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index e7163c13d7..7930c3bc90 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1030,23 +1030,29 @@ fn check_crop_size(w: f64, h: f64) -> Result<()> { } /// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully -/// transparent pixel does not show at the edges of what is opaque. +/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in +/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> image::RgbaImage { - let mut pre = img.clone(); - for p in pre.pixels_mut() { - let a = u32::from(p[3]); - for c in &mut p.0[..3] { - *c = ((u32::from(*c) * a + 127) / 255) as u8; + let mut pre = image::ImageBuffer::, Vec>::new(img.width(), img.height()); + for (d, s) in pre.pixels_mut().zip(img.pixels()) { + let a = u32::from(s[3]); + for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) { + // c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted. + *dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16; } + d.0[3] = (a * 257) as u16; } - let mut out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3); - for p in out.pixels_mut() { - let a = u32::from(p[3]); - for c in &mut p.0[..3] { - *c = (u32::from(*c) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; + let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3); + let mut res = image::RgbaImage::new(out.width(), out.height()); + for (d, s) in res.pixels_mut().zip(out.pixels()) { + let a = u64::from(s[3]); + for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) { + // c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a. + *dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; } + d.0[3] = ((a + 128) / 257).min(255) as u8; } - out + res } /// `img` as PNG bytes. @@ -1141,8 +1147,20 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { if let Some(e) = bare.extras_if_any() { e.color_mask = None; } + let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0)); + let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale); + // At a resolution asked for, the drawing is fitted to the box below: the image is stretched + // about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn. + if target.is_some() + && let NodeKind::Image(bi) = &mut bare.kind + { + let o = r.origin().to_vec2(); + bi.xf = Affine::translate(o) + * Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height()) + * Affine::translate(-o) + * bi.xf; + } let tmp = isolated_doc(&st.doc, vec![bare]); - let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale); let (png, w, h, warning) = render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?; // At a resolution asked for, the drawing is resampled to the box's size at that resolution and diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 57dc6b6510..ec35fd36bc 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1600,7 +1600,10 @@ fn crop_image_resamples_the_cut_to_the_resolution_asked_for() { let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image(); - assert_eq!(out, image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3)); + // Resampled in 16 bits a channel: within a level of the 8-bit resampling. + let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3); + assert_eq!(out.dimensions(), want.dimensions()); + assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1)); } /// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not @@ -1626,6 +1629,53 @@ fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() { } } +/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest +/// alpha comes out as that color, not black. +#[test] +fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() { + let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1])); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap(); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + for p in out.pixels() { + let near = |a: u8, b: u8| a.abs_diff(b) <= 1; + assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}"); + } +} + +/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its +/// place: the edge of the image's content lands where it was in the box. +#[test] +fn crop_image_between_pixels_keeps_the_content_at_its_place() { + // White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt. + let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) }); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + // 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into + // the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white. + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::() / f64::from(out.height()); + let want = 49.0 * 79.0 / 101.0; + assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}"); +} + /// A box between pixels is drawn at the resolution asked for, and lands on the box. #[test] fn crop_image_between_pixels_draws_at_the_resolution_asked_for() { diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index abc2b55b53..53b5bd86f9 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -75,7 +75,8 @@ pub fn check_options(values: &serde_json::Map, max: Option) /// The box `r` over an image with bounds `image`, with one Control bar field set: `x` or `y` moves /// the box so its `reference` point is there; `width` or `height` resizes it about that point, the -/// other side following in proportion when `linked`. Sizes below [`MIN`] are raised to it. A +/// other side following in proportion when `linked`. Sizes below [`MIN`] are raised to it, a +/// linked size with both sides together so it keeps its proportions. A /// linked size is held to the image with both sides scaled together, and a box that fits is slid /// back within the image, so its proportions survive being kept within it. `None` for another key /// or a value that isn't finite. @@ -89,20 +90,13 @@ pub fn edited_box(r: Rect, image: Rect, reference: usize, linked: bool, key: &st match key { "x" => return Some(fit(r + Vec2::new(v - p.x, 0.0))), "y" => return Some(fit(r + Vec2::new(0.0, v - p.y))), - "width" => { - let nw = v.max(MIN); - if linked && w > 0.0 { - h = (h * nw / w).max(MIN); - } - w = nw; - } - "height" => { - let nh = v.max(MIN); - if linked && h > 0.0 { - w = (w * nh / h).max(MIN); - } - h = nh; + // Linked, both sides take one scale, raised so neither side falls below MIN. + "width" | "height" if linked && w > 0.0 && h > 0.0 => { + let k = (v / if key == "width" { w } else { h }).max(MIN / w).max(MIN / h); + (w, h) = (w * k, h * k); } + "width" => w = v.max(MIN), + "height" => h = v.max(MIN), _ => return None, } if linked { @@ -204,11 +198,12 @@ impl CropImageTool { } /// Crop to the box at the chosen resolution and go back to the Selection tool (only back when - /// the box covers the image and the resolution is the image's own). + /// the box covers the image and the resolution is the image's own). The box and the resolution + /// are forgotten when the tool is left, so a crop that fails keeps them for another try. fn apply(&mut self, cx: &ToolContext) -> Vec { let current = self.current(cx); let ppi = self.ppi; - self.reset(); + self.drag = None; let mut out = vec![]; if let Some((id, image, r)) = current { let im = match cx.doc.node(id).map(|n| &n.kind) { @@ -456,6 +451,15 @@ mod tests { } } + /// Enter, then the switch to the Selection tool that a crop that ran is followed by. + fn enter(t: &mut CropImageTool, cx: &ToolContext) -> Vec { + let acts = t.key(cx, ToolKey::Enter, Mods::default()); + if acts.contains(&Action::SwitchTool("selection".into())) { + assert!(t.deactivate(cx).is_empty()); + } + acts + } + fn crop_rect(acts: &[Action]) -> Option> { acts.iter().find_map(|a| match a { Action::Exec(c, v) if c == "object.cropImage" => Some(v["rect"].as_array()?.iter().filter_map(Value::as_f64).collect()), @@ -487,11 +491,11 @@ mod tests { assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Highlight { .. })).count(), 2, "above and right of the box"); assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Handle { .. })).count(), 8); // Enter crops to it and goes back to the Selection tool. - let acts = t.key(&cx, ToolKey::Enter, Mods::default()); + let acts = enter(&mut t, &cx); assert_eq!(crop_rect(&acts), Some(vec![50.0, 70.0, 130.0, 90.0])); assert_eq!(acts.last(), Some(&Action::SwitchTool("selection".into()))); assert!(t.options().get("rect").is_none(), "the next crop starts afresh"); - assert!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())).is_none(), "the whole image: nothing to cut"); + assert!(crop_rect(&enter(&mut t, &cx)).is_none(), "the whole image: nothing to cut"); } /// In a view turned 90° the handles' cursors turn with the view. @@ -515,10 +519,10 @@ mod tests { let mut t = CropImageTool::default(); drag(&mut t, &cx, (100.0, 150.0), (110.0, 150.0)); assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]); - assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![0.0, 100.0, 150.0, 100.0])); + assert_eq!(crop_rect(&enter(&mut t, &cx)), Some(vec![0.0, 100.0, 150.0, 100.0])); // The Control bar sets the box; it stays within the image. t.set_option("rect", &json!([100, 120, 500, 20])); - assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![100.0, 120.0, 50.0, 20.0])); + assert_eq!(crop_rect(&enter(&mut t, &cx)), Some(vec![100.0, 120.0, 50.0, 20.0])); // Nothing selected: no box, and the keys go elsewhere. let none = Selection::default(); let cx = crate::testutil::cx(&d, &none, &p); @@ -660,19 +664,50 @@ mod tests { }; let mut t = CropImageTool::default(); t.set_option("ppi", &json!(20)); - assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [50.0, 60.0, 200.0, 100.0], "ppi": 20.0 }))); + assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [50.0, 60.0, 200.0, 100.0], "ppi": 20.0 }))); assert!(t.options().get("ppi").is_none(), "the next crop starts at the image's own"); t.set_option("ppi", &json!(36)); - assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), None, "the image's own over the whole image: nothing to do"); + assert_eq!(exec(&enter(&mut t, &cx)), None, "the image's own over the whole image: nothing to do"); t.set_option("ppi", &json!(36)); t.set_option("rect", &json!([60, 70, 100, 50])); - assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); // A resolution set before this image was selected is held to its limit: 300 → its own 36. t.set_option("ppi", &json!(300)); t.set_option("rect", &json!([60, 70, 100, 50])); - assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); t.set_option("ppi", &json!(300)); - assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), None, "held to its own over the whole image: nothing to do"); + assert_eq!(exec(&enter(&mut t, &cx)), None, "held to its own over the whole image: nothing to do"); + } + + /// A crop that fails leaves the tool chosen (the switch to the Selection tool is not made), so + /// the box and the resolution stay for another try; leaving the tool forgets them. + #[test] + fn the_box_and_resolution_stay_until_the_tool_is_left() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = CropImageTool::default(); + t.set_option("ppi", &json!(20)); + t.set_option("rect", &json!([60, 70, 100, 50])); + let acts = t.key(&cx, ToolKey::Enter, Mods::default()); + assert_eq!(crop_rect(&acts), Some(vec![60.0, 70.0, 100.0, 50.0])); + assert_eq!(t.options()["rect"], json!([60.0, 70.0, 100.0, 50.0])); + assert_eq!(t.options()["ppi"], json!(20.0)); + assert!(t.deactivate(&cx).is_empty()); + assert!(t.options().get("rect").is_none() && t.options().get("ppi").is_none()); + } + + /// A linked size raised to the smallest box keeps the box's proportions: both sides grow + /// together until the shorter one is a point. + #[test] + fn a_linked_size_at_the_smallest_keeps_its_proportions() { + let big = Rect::new(0.0, 0.0, 1000.0, 1000.0); + let wide = Rect::new(10.0, 20.0, 110.0, 70.0); + assert_eq!(edited_box(wide, big, 0, true, "width", 1.0), Some(Rect::new(10.0, 20.0, 12.0, 21.0))); + assert_eq!(edited_box(wide, big, 0, true, "height", 0.25), Some(Rect::new(10.0, 20.0, 12.0, 21.0))); + let tall = Rect::new(10.0, 20.0, 60.0, 120.0); + assert_eq!(edited_box(tall, big, 0, true, "height", 1.0), Some(Rect::new(10.0, 20.0, 11.0, 22.0))); + assert_eq!(edited_box(tall, big, 0, true, "width", -3.0), Some(Rect::new(10.0, 20.0, 11.0, 22.0))); } #[test] From 18b85e8fd9cf457c47c2188bb2f17413b185d9db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:09:30 -0800 Subject: [PATCH 19/50] Docs: Graph Type's Line Width also needs Connect Data Points The MCP guide and the dialog test's doc comment said Line Width is available while Draw Filled Lines is on. The dialog also needs Connect Data Points on, as its code and test already check. --- crates/ui-egui/src/dialogs/graph_type.rs | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 170dad3552..838ba066d9 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -1072,7 +1072,7 @@ mod tests { } /// Line Width next to Draw Filled Lines shows the graph's width, is available only while Draw - /// Filled Lines is on, and OK gives the graph the width typed. + /// Filled Lines and Connect Data Points are on, and OK gives the graph the width typed. #[test] fn line_width_goes_with_draw_filled_lines() { let mut app = app_with_graph("line"); diff --git a/docs/mcp.md b/docs/mcp.md index 2bbfb07418..b03f221602 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10909,7 +10909,7 @@ Object › Graph › Type… (`graph.setType` without params) and a double-click `graph.setType {}` returns, under the command's names for them. `legend`, `pieLegend`, `piePosition`, `pieSort`, `firstRowInFront`, `firstColumnInFront`, `filledLines` and `lineWidth` are held for every type, so a type picked in the dialog shows the options it uses. The Line Width field next to Draw Filled Lines is available only while Draw Filled -Lines is on. `overrideValues` and `rightOverrideValues` are Override Calculated Values of the left (or only) +Lines and Connect Data Points are on. `overrideValues` and `rightOverrideValues` are Override Calculated Values of the left (or only) value axis and of the right one. While one is on, OK sends `axisMin`, `axisMax` and `ticks` (or `rightAxisMin`, `rightAxisMax` and `rightTicks`), and the dialog fills the ones the graph lacks with the values the axis would be calculated with for the type, value axis and Separate Scales the dialog shows. From 6f853810bf146b8747a5e11ac7ceba17fe650972 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:47:40 -0800 Subject: [PATCH 20/50] Type: Composite Fonts' Show Sample draws the font picked with its metric lines Show Sample (Hide Sample when it shows) in Type > Composite Fonts... draws the font picked in a line of sample text, with the first character of each custom set added, through the renderer, so color and bitmap glyphs keep their colors. Buttons beside it show or hide lines for the ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, and Zoom draws it at 25% to 800% of 36 pt. The em box and ICF box are the Kanji part's font's; the other lines measure the faces the glyphs are drawn in, fallback faces included. Each line takes its part's size, baseline and vertical scale, and Kana scaled at center, as layout sets them. ui.dialog.set takes sample, zoom and the seven line fields, and refuses a zoom outside the menu or a line that is not true or false. FontFace gains cap_height(), the estimate a face without an OS/2 cap height uses, beside x_height(). Docs: docs/mcp.md, docs/type-parity.md, docs/target-app-parity.md. --- crates/text/src/fontdb/face.rs | 5 + crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/dialogs/composite_fonts.rs | 34 +- .../src/dialogs/composite_fonts/sample.rs | 382 ++++++++++++++++++ .../src/dialogs/composite_fonts/tests.rs | 190 +++++++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + docs/mcp.md | 16 +- docs/target-app-parity.md | 1 + docs/type-parity.md | 2 +- 36 files changed, 739 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/composite_fonts/sample.rs diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index ff9ad8d58f..5d90bf6976 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -356,6 +356,11 @@ impl FontFace { pub fn x_height(&self) -> f64 { self.x_height } + /// The height of the capital letters in font units, positive (estimated from the ascent when + /// the font has no OS/2 value). + pub fn cap_height(&self) -> f64 { + self.cap_height + } /// The line gap the font asks for between lines, in font units (from the same table as /// [`vertical_metrics`](Self::vertical_metrics); 0 when it has none). pub fn line_gap(&self) -> f64 { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index fe48f28952..551854023a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -645,12 +645,16 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields /// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. +/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value +/// Composite Fonts' Show Sample can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); return Ok(()); } + if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { + return composite_fonts::field_set(d, field); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 6e3b6f84e1..41bef1f45b 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -5,14 +5,17 @@ //! out, Import… adds the fonts of a file and Export… writes the one picked to a file. Custom shows //! the custom character sets of the font picked: New adds a set based on the one picked, Delete Set //! takes it out, and Add puts the characters typed (Direct Entry) or the character of a Unicode code -//! into it; Delete takes the character picked out. Nothing changes in the document until OK, which +//! into it; Delete takes the character picked out. Show Sample draws a sample of the font picked +//! with lines that mark its metrics ([`sample`]). Nothing changes in the document until OK, which //! runs `type.compositeFonts.set` with every font as one undo step; Cancel leaves them as they were. //! //! Fields: `fonts` (the composite fonts as `type.compositeFonts.set` takes them), `selected` (the //! index of the one picked) and `name` (its name as typed); `custom` (whether the custom character //! sets show), `set` (the index of the set picked), `setName` (its name as typed), `entryMode` //! (`direct` or `unicode`), `entry` (the characters or code typed) and `char` (the index of the -//! character picked in the set). +//! character picked in the set); `sample` (whether the sample shows), `zoom` (its magnification in +//! percent) and `lineIcfBox`, `lineEmBox`, `lineBaseline`, `lineCapHeight`, `lineAscentDescent`, +//! `lineAscender` and `lineXHeight` (whether each of its lines shows). //! //! Behavior reference (public documentation): //! , @@ -29,6 +32,8 @@ use crate::picks::PickRequest; use crate::state::Dialog; use crate::{FilePick, VectorcraftApp, widgets}; +mod sample; + /// The dialog kind of Composite Fonts. pub const KIND: &str = "compositeFonts"; @@ -53,15 +58,22 @@ pub(super) const SPEC: DialogSpec = DialogSpec { }; /// Open Composite Fonts on the active document's composite fonts, the first one picked, with the -/// custom character sets hidden and nothing typed. +/// custom character sets and the sample hidden and nothing typed. pub fn open(app: &mut VectorcraftApp) -> Result { let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec(); let mut d = Dialog::new(KIND, json!({ "fonts": fonts, "selected": 0, "custom": false, "entryMode": "direct", "entry": "" })); + sample::defaults(&mut d.fields); show_selected(&mut d); app.ui.dialog = Some(d); Ok(Value::Null) } +/// Why `ui.dialog.set` can't set `field` of Composite Fonts `d` to the value it now holds (Show +/// Sample's fields, [`sample::check_field`]). +pub(super) fn field_set(d: &Dialog, field: &str) -> Result<(), String> { + sample::check_field(d, field) +} + /// The fonts the dialog holds. fn fonts(d: &Dialog) -> Vec { d.fields.get("fonts").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default() @@ -138,6 +150,8 @@ enum Action { Export, /// Custom: show or hide the custom character sets. Custom, + /// Show Sample or Hide Sample. + Sample, NewSet, DeleteSet, /// Add the characters typed, or the character of the code typed, to the set picked. @@ -178,6 +192,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Custom"), 64.0)).inner.clicked() { act = Some(Action::Custom); } + let label = if d.bool("sample") { tl!("Hide Sample") } else { tl!("Show Sample") }; + if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, label, 96.0)).inner.clicked() { + act = Some(Action::Sample); + } }); if let Some(k) = picked { select(d, k); @@ -192,6 +210,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { f.name = d.str("name"); ui.add_space(8.0); parts_table(app, ui, f); + if d.bool("sample") { + ui.add_space(8.0); + sample::show(ui, d, f); + } if d.bool("custom") { ui.add_space(8.0); ui.separator(); @@ -319,6 +341,10 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), Stri let open = !d.bool("custom"); d.fields.insert("custom".into(), json!(open)); } + Action::Sample => { + let open = !d.bool("sample"); + d.fields.insert("sample".into(), json!(open)); + } Action::NewSet | Action::DeleteSet | Action::AddChars | Action::DeleteChar => { let f = list.get_mut(i).ok_or("no composite font")?; let at = edit_sets(d, f, act)?; @@ -389,7 +415,7 @@ fn edit_sets(d: &mut Dialog, f: &mut CompositeFont, act: Action) -> Result Ok(None), + Action::New | Action::Delete | Action::Import | Action::Export | Action::Custom | Action::Sample => Ok(None), } } diff --git a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs new file mode 100644 index 0000000000..952e88be1c --- /dev/null +++ b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs @@ -0,0 +1,382 @@ +//! Show Sample in Composite Fonts: the font picked set in a line of sample text, with lines that +//! mark its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest +//! ascender and x-height, each shown or hidden by its button, at the size Zoom picks. +//! +//! The sample text, the zoom steps, the size at 100% and what each line measures are VectorCraft's +//! own: the em box and ICF box are those of the Kanji part's face +//! ([`vectorcraft_text::FontFace::ideographic_centre`], [`vectorcraft_text::FontFace::icf_margins`]), +//! the cap height and x-height those of the face the Roman letters are drawn in, Max Ascent/Descent +//! the highest ascent and lowest descent among the faces the sample is drawn in (fallback faces +//! included), and Max Ascender the top of the sample's tallest glyph. Each takes its part's size, +//! baseline and vertical scale. +//! +//! Behavior reference (public documentation): +//! , +//! . + +use std::hash::{DefaultHasher, Hash, Hasher}; + +use egui::{Color32, Rect, Sense, Stroke, Ui, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{CharClass, CharStyle, CompositeClass, CompositeFont, FontHeightReference, TextObject}; +use vectorcraft_geom::kurbo::BezPath; +use vectorcraft_geom::{Affine, Point}; +use vectorcraft_text::FontDb; + +use crate::state::Dialog; +use crate::widgets; + +/// The text the sample sets: two Kanji, two kana, two punctuation marks, a symbol, Roman letters +/// with an ascender and a descender, and two numerals, then the first character of each custom set. +pub(super) const TEXT: &str = "永国あア、。※Agh12"; + +/// The Zoom menu's magnifications, in percent. +pub(super) const ZOOMS: [u64; 7] = [25, 50, 75, 100, 200, 400, 800]; + +/// The size the sample is set at with Zoom at 100%, in points. +const SIZE: f64 = 36.0; + +/// How tall the sample is drawn, in points. +const HEIGHT: f32 = 150.0; + +/// How far the sample text starts from the left edge, in points. +const INSET: f64 = 12.0; + +/// The width of the column of line buttons and Zoom beside the sample, in points. +const BUTTONS: f32 = 190.0; + +/// The narrowest and widest the sample is drawn, in points. +const WIDTH: std::ops::RangeInclusive = 240.0..=720.0; + +/// The name the sample lends the font under, so a name that is empty, being typed or shared with +/// another font still draws. +const NAME: &str = "VectorCraft Composite Sample"; + +/// A line Show Sample can mark. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Mark { + IcfBox, + EmBox, + Baseline, + CapHeight, + AscentDescent, + Ascender, + XHeight, +} + +impl Mark { + /// The marks, in the order their buttons show. + pub(super) const ALL: [Self; 7] = + [Self::IcfBox, Self::EmBox, Self::Baseline, Self::CapHeight, Self::AscentDescent, Self::Ascender, Self::XHeight]; + + /// The dialog field that holds whether the mark shows. + pub(super) fn field(self) -> &'static str { + match self { + Self::IcfBox => "lineIcfBox", + Self::EmBox => "lineEmBox", + Self::Baseline => "lineBaseline", + Self::CapHeight => "lineCapHeight", + Self::AscentDescent => "lineAscentDescent", + Self::Ascender => "lineAscender", + Self::XHeight => "lineXHeight", + } + } + + fn label(self) -> &'static str { + match self { + Self::IcfBox => tl!("ICF Box"), + Self::EmBox => tl!("Em Box"), + Self::Baseline => tl!("Baseline"), + Self::CapHeight => tl!("Cap Height"), + Self::AscentDescent => tl!("Max Ascent/Descent"), + Self::Ascender => tl!("Max Ascender"), + Self::XHeight => tl!("x-height"), + } + } + + /// Shown when the dialog opens: the em box, the ICF box and the baseline. + pub(super) fn shown_at_first(self) -> bool { + matches!(self, Self::IcfBox | Self::EmBox | Self::Baseline) + } + + fn color(self) -> Color32 { + match self { + Self::IcfBox => Color32::from_rgb(0, 150, 170), + Self::EmBox => Color32::from_rgb(220, 60, 60), + Self::Baseline => Color32::from_rgb(40, 110, 230), + Self::CapHeight => Color32::from_rgb(40, 160, 70), + Self::AscentDescent => Color32::from_rgb(230, 140, 30), + Self::Ascender => Color32::from_rgb(150, 80, 200), + Self::XHeight => Color32::from_rgb(200, 60, 160), + } + } +} + +/// The fields Show Sample adds to the dialog when it opens: hidden, at 100%, with the marks of +/// [`Mark::shown_at_first`]. +pub(super) fn defaults(fields: &mut serde_json::Map) { + fields.insert("sample".into(), json!(false)); + fields.insert("zoom".into(), json!(100)); + for m in Mark::ALL { + fields.insert(m.field().into(), json!(m.shown_at_first())); + } +} + +/// Why `ui.dialog.set` can't set Show Sample's `field` to the value `d` now holds: `sample` and the +/// marks take true or false, and `zoom` one of [`ZOOMS`]. +pub(super) fn check_field(d: &Dialog, field: &str) -> Result<(), String> { + let v = d.fields.get(field); + let key = field; + if field == "sample" || Mark::ALL.iter().any(|m| m.field() == field) { + if !v.is_some_and(Value::is_boolean) { + return Err(format!("`{key}` must be true or false")); + } + } else if field == "zoom" && !v.and_then(Value::as_u64).is_some_and(|z| ZOOMS.contains(&z)) { + return Err(format!("`{key}` must be one of {}", ZOOMS.map(|z| z.to_string()).join(", "))); + } + Ok(()) +} + +/// The Zoom `d` holds, 100 when it holds none of [`ZOOMS`]. +fn zoom(d: &Dialog) -> u64 { + d.fields.get("zoom").and_then(Value::as_u64).filter(|z| ZOOMS.contains(z)).unwrap_or(100) +} + +/// The heights the marks are drawn at, in points above the baseline (a mark's line is not drawn +/// when its height is `None`). The baseline is at 0. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Heights { + /// The em box's bottom and top. + pub em_box: Option<(f64, f64)>, + /// The ICF box's bottom and top. + pub icf_box: Option<(f64, f64)>, + pub cap_height: Option, + pub x_height: Option, + /// The lowest descent and the highest ascent. + pub ascent_descent: Option<(f64, f64)>, + /// The top of the tallest glyph. + pub ascender: Option, +} + +impl Heights { + /// The heights of mark `m`. + fn of(&self, m: Mark) -> Vec { + let pair = |p: Option<(f64, f64)>| p.map_or_else(Vec::new, |(a, b)| vec![a, b]); + match m { + Mark::IcfBox => pair(self.icf_box), + Mark::EmBox => pair(self.em_box), + Mark::Baseline => vec![0.0], + Mark::CapHeight => self.cap_height.into_iter().collect(), + Mark::AscentDescent => pair(self.ascent_descent), + Mark::Ascender => self.ascender.into_iter().collect(), + Mark::XHeight => self.x_height.into_iter().collect(), + } + } +} + +/// `f` as the sample sets it: named [`NAME`], without its custom sets when one of them can't be +/// used (a set whose name is empty or shared while it is typed). +fn sample_font(f: &CompositeFont) -> CompositeFont { + let mut s = f.clone(); + s.name = NAME.to_string(); + if s.check().is_err() { + s.custom.clear(); + } + s +} + +/// [`TEXT`], then the first character of each of `f`'s custom sets that it does not hold yet. +pub(super) fn text(f: &CompositeFont) -> String { + let mut t = TEXT.to_string(); + for c in f.custom.iter().filter_map(|s| s.characters.chars().next()) { + if !t.contains(c) { + t.push(c); + } + } + t +} + +/// The outlines of the sample of `f` set at `size` points with its baseline at y 0 (y down), and +/// the heights of its marks. +pub(super) fn measure(f: &CompositeFont, size: f64) -> (BezPath, Heights) { + let db = FontDb::global(); + let font = sample_font(f); + let _lent = db.lend_composite_fonts(std::slice::from_ref(&font)); + let text = text(&font); + let style = CharStyle { font_family: NAME.to_string(), size, ..Default::default() }; + let layout = vectorcraft_text::layout(db, &TextObject::point(Point::ZERO, &text, style)); + let path = layout.to_bezpath(); + let classes = font.classes(); + // The face of character `c`'s part, the face layout draws it in (a fallback face when the part's + // font lacks it), the size of its em and the shift of its baseline (points), and its part's + // vertical scale, as layout sets them: Kana scaled at center keep the middle of their part's em + // box where it is. + let placed = |c: char| { + let (part_face, _) = db.composite_resolve(NAME, c)?; + let drawn = text.find(c).and_then(|at| layout.glyphs.iter().find(|g| g.byte == at)).and_then(|g| db.face_by_id(g.font_id)); + let class = classes.of(c); + let p = font.part(class).unwrap_or(&font.parts.kanji); + let em = size * p.size / 100.0; + let mut shift = size * p.baseline / 100.0; + if class == CompositeClass::Fixed(CharClass::Kana) && p.scale_at_center && p.v_scale != 100.0 { + shift += em * part_face.ideographic_centre() * (1.0 - p.v_scale / 100.0); + } + let drawn = drawn.unwrap_or_else(|| part_face.clone()); + Some((part_face, drawn, em, shift, p.v_scale / 100.0)) + }; + let mut h = Heights::default(); + // The em box and ICF box are the Kanji part's, the base of the composite font, as layout + // measures that part's face for Scale at Center. + if let Some((face, _, em, shift, v)) = TEXT.chars().next().and_then(placed) { + let tall = em * v; + let mid = shift + face.ideographic_centre() * tall; + let (bottom, top) = (mid - tall * 0.5, mid + tall * 0.5); + let m = face.icf_margins(); + h.em_box = Some((bottom, top)); + h.icf_box = Some((bottom + m.bottom * tall, top - m.top * tall)); + } + if let Some((_, face, em, shift, v)) = placed('A') { + let height = |r| face.font_height(r, false); + let cap = height(FontHeightReference::CapHeight).unwrap_or_else(|| face.cap_height() / face.units_per_em()); + h.cap_height = Some(shift + cap * em * v); + let x = height(FontHeightReference::XHeight).unwrap_or_else(|| face.x_height() / face.units_per_em()); + h.x_height = Some(shift + x * em * v); + } + let mut seen = Vec::new(); + for c in text.chars().filter(|c| !c.is_whitespace()) { + let Some((_, face, em, shift, v)) = placed(c) else { continue }; + if seen.contains(&(face.id(), em.to_bits(), shift.to_bits(), v.to_bits())) { + continue; + } + seen.push((face.id(), em.to_bits(), shift.to_bits(), v.to_bits())); + let (ascent, descent) = face.vertical_metrics(); + let scale = em * v / face.units_per_em(); + let (low, high) = (shift - descent * scale, shift + ascent * scale); + h.ascent_descent = Some(h.ascent_descent.map_or((low, high), |(l, t)| (l.min(low), t.max(high)))); + } + // Outlines, color glyphs and bitmap glyphs alike. + h.ascender = layout.ink_bounds().filter(|ink| ink.height() > 0.0).map(|ink| -ink.y0); + (path, h) +} + +/// The sample drawn for a key, kept until the font, zoom, size, display scale, text color or the +/// fonts installed change. +struct Drawn { + key: u64, + texture: Option, + heights: Heights, +} + +thread_local! { + static DRAWN: crate::graphics::TexCache> = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// Show Sample's area under the table: the sample of `f` with its marks, then the mark buttons and +/// Zoom beside it. +pub(super) fn show(ui: &mut Ui, d: &mut Dialog, f: &CompositeFont) { + let zoom = zoom(d); + ui.horizontal(|ui| { + let width = (ui.available_width() - BUTTONS).clamp(*WIDTH.start(), *WIDTH.end()); + let (rect, _) = ui.allocate_exact_size(vec2(width, HEIGHT), Sense::hover()); + paint(ui, rect, d, f, zoom); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for m in Mark::ALL { + let on = d.bool(m.field()); + ui.horizontal(|ui| { + let (swatch, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover()); + ui.painter().rect_filled(swatch, 1.0, m.color()); + if ui.add(egui::Button::selectable(on, m.label())).clicked() { + d.fields.insert(m.field().into(), json!(!on)); + } + }); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Zoom")); + let names: Vec = ZOOMS.iter().map(|z| format!("{z}%")).collect(); + let options: Vec<&str> = names.iter().map(String::as_str).collect(); + let current = format!("{zoom}%"); + if let Some(k) = widgets::dropdown(ui, "composite-fonts-zoom", ¤t, &options, 80.0) + && let Some(z) = ZOOMS.get(k) + { + d.fields.insert("zoom".into(), json!(z)); + } + }); + }); + }); +} + +/// Draw the sample of `f` at `zoom` percent into `rect`, its em box centered in it, with the marks +/// `d` shows. +fn paint(ui: &Ui, rect: Rect, d: &Dialog, f: &CompositeFont, zoom: u64) { + let painter = ui.painter_at(rect); + let visuals = ui.visuals(); + painter.rect_filled(rect, 2.0, visuals.extreme_bg_color); + let ppp = ui.ctx().pixels_per_point(); + let ink = visuals.text_color(); + let mut h = DefaultHasher::new(); + serde_json::to_string(f).unwrap_or_default().hash(&mut h); + (zoom, ppp.to_bits(), rect.width().to_bits(), rect.height().to_bits(), ink.to_array(), FontDb::global().generation()).hash(&mut h); + let key = h.finish(); + let size = SIZE * zoom as f64 / 100.0; + let (texture, heights) = DRAWN.with(|cache| { + let mut cache = cache.borrow_mut(); + if let Some(drawn) = cache.as_ref().filter(|c| c.key == key) { + return (drawn.texture.clone(), drawn.heights); + } + let (_, heights) = measure(f, size); + let texture = render(ui.ctx(), f, size, baseline(&heights, size, rect), rect, ppp, ink); + *cache = Some(Drawn { key, texture: texture.clone(), heights }); + (texture, heights) + }); + if let Some(t) = &texture { + painter.image(t.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + } + let base = rect.top() + baseline(&heights, size, rect) as f32; + for m in Mark::ALL.into_iter().filter(|m| d.bool(m.field())) { + for y in heights.of(m) { + painter.hline(rect.x_range(), base - y as f32, Stroke::new(1.0, m.color())); + } + } + painter.rect_stroke(rect, 2.0, visuals.widgets.noninteractive.bg_stroke, egui::StrokeKind::Inside); +} + +/// Where the baseline goes, in points down from the top of `rect`: the em box's middle (else +/// 0.38 em above the baseline) at the middle of `rect`. +fn baseline(h: &Heights, size: f64, rect: Rect) -> f64 { + let mid = h.em_box.map_or(size * 0.38, |(bottom, top)| (bottom + top) * 0.5); + f64::from(rect.height()) * 0.5 + mid +} + +/// The sample of `f` drawn into a texture the size of `rect` in pixels ([`draw`]). `None` when +/// `rect` is empty or larger than the largest texture. +fn render(ctx: &egui::Context, f: &CompositeFont, size: f64, baseline: f64, rect: Rect, ppp: f32, ink: Color32) -> Option { + let (w, h) = ((rect.width() * ppp).round(), (rect.height() * ppp).round()); + let max = ctx.input(|i| i.max_texture_side) as f32; + if w < 1.0 || h < 1.0 || w > max || h > max || w > f32::from(u16::MAX) || h > f32::from(u16::MAX) { + return None; + } + let image = draw(f, size, baseline, (w as u16, h as u16), ppp, ink); + Some(ctx.load_texture("composite-font-sample", crate::canvas::color_image_owned(image), egui::TextureOptions::LINEAR)) +} + +/// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the +/// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own +/// colors) into `px` pixels at `ppp` pixels per point. +pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered { + let (w, h) = px; + let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp)); + let font = sample_font(f); + let sample = text(&font); + *doc.composite_fonts = vec![font]; + let [r, g, b, _] = ink.to_normalized_gamma_f32(); + let fill = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(r, g, b)); + let style = CharStyle { font_family: NAME.to_string(), size, fill, ..Default::default() }; + let t = TextObject::point(Point::new(INSET, baseline), &sample, style); + let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t)))); + let view = Affine::scale(f64::from(ppp)); + let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] }; + RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty) +} diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index e50ce1b566..fa909973b1 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -280,3 +280,193 @@ fn custom_sets_sharing_a_name_keep_the_dialog_open() { assert!(app.ui.dialog.is_some()); assert!(names(&app).is_empty()); } + +/// A composite font set in Inter, with its Roman part as `roman` changes it. +fn inter_font(roman: impl FnOnce(&mut vectorcraft_doc::CompositePart)) -> CompositeFont { + let mut parts = vectorcraft_doc::CompositeParts::all(vectorcraft_doc::CompositePart::new("Inter", "Regular")); + roman(&mut parts.roman); + CompositeFont { name: "UI Composite Sample".into(), parts, custom: Vec::new() } +} + +/// Show Sample opens hidden at 100% with the ICF box, em box and baseline shown; its button shows +/// and hides the sample, which draws with every line shown and at every zoom; nothing changes in +/// the document. +#[test] +fn show_sample_shows_and_hides_the_sample() { + let mut app = app(); + open(&mut app).unwrap(); + let d = dialog(&mut app); + assert!(!d.bool("sample")); + assert_eq!(d.fields.get("zoom"), Some(&json!(100))); + let shown: Vec = sample::Mark::ALL.iter().map(|m| d.bool(m.field())).collect(); + assert_eq!(shown, [true, true, true, false, false, false, false]); + press(&mut app, Action::New); + press(&mut app, Action::Sample); + assert!(dialog(&mut app).bool("sample")); + frame(&mut app); + for m in sample::Mark::ALL { + dialog(&mut app).fields.insert(m.field().into(), json!(true)); + } + for z in sample::ZOOMS { + dialog(&mut app).fields.insert("zoom".into(), json!(z)); + frame(&mut app); + } + press(&mut app, Action::Sample); + assert!(!dialog(&mut app).bool("sample")); + super::super::cancel(&mut app); + assert!(names(&app).is_empty()); +} + +/// `ui.dialog.set` takes `sample`, `zoom` and the line fields; a zoom outside the Zoom menu or a +/// line that is not true or false is refused and leaves the dialog as it was. +#[test] +fn sample_fields_are_set_and_checked() { + let mut app = app(); + let ctx = egui::Context::default(); + open(&mut app).unwrap(); + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("not done") }; + r + }; + for (field, value) in [("sample", json!(true)), ("zoom", json!(400)), ("lineCapHeight", json!(true)), ("lineBaseline", json!(false))] { + let r = set(&mut app, field, value.clone()); + assert!(r.get("error").is_none(), "{field}: {r}"); + assert_eq!(dialog(&mut app).fields.get(field), Some(&value), "{field}"); + } + for (field, value) in [("zoom", json!(30)), ("zoom", json!("200")), ("sample", json!(1)), ("lineXHeight", json!("yes"))] { + let r = set(&mut app, field, value.clone()); + assert!(r.get("error").is_some(), "{field} {value}: {r}"); + } + let d = dialog(&mut app); + assert_eq!((d.fields.get("zoom"), d.bool("sample"), d.bool("lineXHeight")), (Some(&json!(400)), true, false)); +} + +/// The sample's lines: the em box and ICF box of the face the Kanji are set in (a face without +/// ideographs centers its em box 0.38 em above the baseline), the cap height and x-height of the +/// Roman part's face raised by its baseline and scaled by its vertical scale, the lowest descent +/// and highest ascent, and the top of the tallest glyph; all of them grow with the size. +#[test] +fn sample_lines_follow_the_parts() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let (path, h) = sample::measure(&inter_font(|_| {}), 36.0); + assert!(!path.elements().is_empty()); + let (bottom, top) = h.em_box.unwrap(); + assert!(close(bottom, -0.12 * 36.0) && close(top, 0.88 * 36.0), "{h:?}"); + let (ib, it) = h.icf_box.unwrap(); + assert!(ib >= bottom && it <= top && ib < it, "{h:?}"); + let (cap, x) = (h.cap_height.unwrap(), h.x_height.unwrap()); + assert!(0.0 < x && x < cap && cap < top, "{h:?}"); + let (low, high) = h.ascent_descent.unwrap(); + assert!(low < 0.0 && high > cap, "{h:?}"); + assert!(h.ascender.unwrap() > x, "{h:?}"); + // The Roman part raised by 10% and squeezed to half height moves its lines; the Kanji's stay. + let (_, raised) = sample::measure( + &inter_font(|p| { + p.baseline = 10.0; + p.v_scale = 50.0; + }), + 36.0, + ); + assert!(close(raised.cap_height.unwrap(), 3.6 + cap * 0.5), "{raised:?}"); + assert!(close(raised.x_height.unwrap(), 3.6 + x * 0.5), "{raised:?}"); + assert_eq!(raised.em_box, h.em_box); + // At 200% every line is twice as far from the baseline. + let (_, double) = sample::measure(&inter_font(|_| {}), 72.0); + assert!(close(double.cap_height.unwrap(), cap * 2.0) && close(double.em_box.unwrap().1, top * 2.0), "{double:?}"); +} + +/// The ICF box is the Kanji face's ideographic character face inside its em box, and a Roman face +/// without an OS/2 cap height still gets a Cap Height line, estimated from its ascent. +#[test] +fn sample_lines_read_the_icf_box_and_estimate_a_missing_cap_height() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, HEIGHTLESS_FAMILY, height_font}; + let db = vectorcraft_text::FontDb::global(); + db.add_font(height_font(true).expect("the test font builds")); + db.add_font(height_font(false).expect("the test font builds")); + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let mut f = inter_font(|p| p.font = HEIGHTLESS_FAMILY.into()); + f.parts.kanji.font = HEIGHT_FAMILY.into(); + let (_, h) = sample::measure(&f, 36.0); + let (bottom, top) = h.icf_box.unwrap(); + assert!(close(bottom, -0.07 * 36.0) && close(top, 0.83 * 36.0), "{h:?}"); + let cap = h.cap_height.expect("an estimated cap height"); + assert!(cap > h.x_height.unwrap() && cap < h.ascent_descent.unwrap().1, "{h:?}"); +} + +/// A character its part's font lacks is drawn in a fallback face, and the lines measure that face: +/// in a font whose box runs to 0.9 em and which maps no `A`, `g`, `h`, `1` or `2`, the highest +/// ascent is the fallback face's. +#[test] +fn sample_lines_measure_the_faces_that_draw_the_glyphs() { + use vectorcraft_text::test_fonts::{PATH_ALIGN_HHEA_FAMILY, path_align_font}; + vectorcraft_text::FontDb::global().add_font(path_align_font(PATH_ALIGN_HHEA_FAMILY).expect("the test font builds")); + let mut f = inter_font(|_| {}); + f.parts = vectorcraft_doc::CompositeParts::all(vectorcraft_doc::CompositePart::new(PATH_ALIGN_HHEA_FAMILY, "Regular")); + let (_, h) = sample::measure(&f, 36.0); + let (_, high) = h.ascent_descent.unwrap(); + assert!(high > 0.9 * 36.0 + 0.5, "{h:?}"); +} + +/// The lines follow a vertical scale as the glyphs do: a custom set that holds the first Kanji at +/// half height halves the em box about its baseline, and Kana scaled at center keep the middle of +/// their em box, so their ascent moves up by the half they lose below it. +#[test] +fn sample_lines_follow_vertical_scale() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let mut f = inter_font(|_| {}); + let mut half = vectorcraft_doc::CompositePart::new("Inter", "Regular"); + half.v_scale = 50.0; + f.custom = vec![CustomCharSet { name: "Half".into(), characters: "永".into(), part: half }]; + let (_, h) = sample::measure(&f, 36.0); + let (bottom, top) = h.em_box.unwrap(); + assert!(close(bottom, (0.38 - 0.5) * 18.0) && close(top, (0.38 + 0.5) * 18.0), "{h:?}"); + let kana = |at_center: bool| { + let mut f = inter_font(|_| {}); + f.parts.kana.size = 300.0; + f.parts.kana.v_scale = 50.0; + f.parts.kana.scale_at_center = at_center; + sample::measure(&f, 36.0).1.ascent_descent.unwrap() + }; + // The Kana, at three times the size, give the highest ascent either way. + let ((_, high), (_, raised)) = (kana(false), kana(true)); + assert!(close(raised, high + 0.38 * 108.0 * 0.5), "{high} {raised}"); +} + +/// The sample adds the first character of each custom set it does not hold yet, and a font whose +/// sets can't be used yet (two sharing a name while it is typed) still draws, without them. +#[test] +fn the_sample_takes_the_custom_sets() { + let mut f = inter_font(|_| {}); + let set = |name: &str, characters: &str| CustomCharSet { + name: name.into(), + characters: characters.into(), + part: vectorcraft_doc::CompositePart::new("Inter", "Regular"), + }; + f.custom = vec![set("Marks", "〒※"), set("Letters", "A")]; + assert_eq!(sample::text(&f), format!("{}〒", sample::TEXT)); + f.custom = vec![set("Marks", "〒"), set("marks", "〒")]; + let (path, h) = sample::measure(&f, 36.0); + assert!(!path.elements().is_empty() && h.cap_height.is_some()); +} + +/// The sample draws a color font's glyphs in their own colors, not in the dialog's text color. +#[test] +fn the_sample_draws_color_glyphs_in_their_colors() { + use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font}; + vectorcraft_text::FontDb::global().add_font(colr_font(false).expect("the test font builds")); + let mut f = inter_font(|_| {}); + let mut colr = vectorcraft_doc::CompositePart::new(colr_family(false), "Regular"); + colr.size = 300.0; + f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }]; + let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK); + let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| { + let p = img.pixel(x, y); + p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200 + }); + assert!(red, "the glyph's red layer is drawn"); + // Max Ascender reaches the top of the color glyph, three times the size of the rest. + let (_, plain) = sample::measure(&inter_font(|_| {}), 36.0); + let (_, tall) = sample::measure(&f, 36.0); + assert!(tall.ascender.unwrap() > plain.ascender.unwrap() * 1.5, "{plain:?} {tall:?}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a6a69d9100..2354b6f3c8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5013,6 +5013,10 @@ axis Both И двете Em Box Квадратна касетка (Em Box) x-Height Височина на x ICF Box Касетка ICF + Show Sample Показване на образец + Hide Sample Скриване на образец + Max Ascent/Descent Макс. височина нагоре/надолу + Max Ascender Макс. възходящ елемент @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` е референцията за стъпка {r}, която се разрешава само от `run` и `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` трябва да бъде масив от идентификатори на обекти, а не {v} @msg `colors` must be an array of colors, not {v} `colors` трябва да бъде масив от цветове, а не {v} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5da48b6cff..a36b7521e2 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1676,6 +1676,10 @@ digits Malayalam Malajalam Em Box Em okvir x-Height Visina malih slova ICF Box ICF okvir + Show Sample Prikaži uzorak + Hide Sample Sakrij uzorak + Max Ascent/Descent Maks. visina gore/dolje + Max Ascender Maks. gornji produžetak Copy Color Value (Hex) Kopiraj vrijednost boje (hex) Create New Swatch… Kreiraj novi uzorak boje… Name 40% Naziv 40% diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e861e61fec..e98f0dd09b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6972,6 +6972,10 @@ theme Appearance Aparença Em Box Caixa em x-Height Alçada de la x ICF Box Caixa ICF + Show Sample Mostra l'exemple + Hide Sample Amaga l'exemple + Max Ascent/Descent Alçada/profunditat màx. + Max Ascender Ascendent màx. # Average & Join (Object › Path, Cmd+Alt+Shift+J). Average & Join… Mitjana i unió… Average & Join Mitjana i unió diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..dd07cb030a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1747,6 +1747,10 @@ digits Malayalam Malajálamské Em Box Čtverčík x-Height Výška x ICF Box Rámeček ICF + Show Sample Zobrazit ukázku + Hide Sample Skrýt ukázku + Max Ascent/Descent Max. výška/hloubka + Max Ascender Max. horní dotah Copy Color Value (Hex) Kopírovat hodnotu barvy (hex) Create New Swatch… Vytvořit novou položku vzorníku… Name 40% Název 40 % diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..96c485db68 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2269,6 +2269,10 @@ digits Malayalam Malayalam Em Box Em-felt x-Height x-højde ICF Box ICF-felt + Show Sample Vis eksempel + Hide Sample Skjul eksempel + Max Ascent/Descent Maks. højde/dybde + Max Ascender Maks. overhøjde Copy Color Value (Hex) Kopiér farveværdi (hex) Create New Swatch… Opret ny farveprøve… Name 40% Navn 40% diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..85a10b39bd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5282,6 +5282,10 @@ theme Appearance Erscheinungsbild Cap Height Versalhöhe x-Height x-Höhe ICF Box ICF-Rahmen + Show Sample Muster einblenden + Hide Sample Muster ausblenden + Max Ascent/Descent Max. Höhe/Tiefe + Max Ascender Max. Oberlänge @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` ist der Schrittverweis {r}, den nur `run` und `command_batch` auflösen @msg `ids` must be an array of object ids, not {v} `ids` muss ein Array von Objekt-IDs sein, nicht {v} @msg `colors` must be an array of colors, not {v} `colors` muss ein Array von Farben sein, nicht {v} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..3ce4a48110 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5314,6 +5314,10 @@ digits Malayalam Μαλαγιάλαμ Em Box Τετράγωνο em x-Height Ύψος x ICF Box Πλαίσιο ICF + Show Sample Εμφάνιση δείγματος + Hide Sample Απόκρυψη δείγματος + Max Ascent/Descent Μέγ. ύψος/βάθος + Max Ascender Μέγ. άνω επέκταση @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve το `id` είναι η αναφορά βήματος {r}, την οποία αναλύουν μόνο τα `run` και `command_batch` @msg `ids` must be an array of object ids, not {v} το `ids` πρέπει να είναι πίνακας αναγνωριστικών αντικειμένων, όχι {v} @msg `colors` must be an array of colors, not {v} το `colors` πρέπει να είναι πίνακας χρωμάτων, όχι {v} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..bcaf070409 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1024,6 +1024,10 @@ font-technology Variable Variables Em Box Cuadro eme x-Height Altura de la x ICF Box Cuadro ICF + Show Sample Mostrar muestra + Hide Sample Ocultar muestra + Max Ascent/Descent Altura/profundidad máx. + Max Ascender Ascendente máx. Em Dash Raya Em Space Espacio eme Embed Incrustar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..1a7bc7ba2e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1720,6 +1720,10 @@ digits Malayalam Malajalam Em Box Em-laatikko x-Height x-korkeus ICF Box ICF-laatikko + Show Sample Näytä näyte + Hide Sample Piilota näyte + Max Ascent/Descent Suurin korkeus/syvyys + Max Ascender Suurin yläpidennys Copy Color Value (Hex) Kopioi väriarvo (heksa) Create New Swatch… Luo uusi värimalli… Name 40% Nimi 40% diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..2a8cb022f6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5345,6 +5345,10 @@ axis Both Les deux Em Box Cadratin x-Height Hauteur d’x ICF Box Cadre ICF + Show Sample Afficher l'échantillon + Hide Sample Masquer l'échantillon + Max Ascent/Descent Hauteur/profondeur max. + Max Ascender Jambage ascendant max. ICF Top/Right ICF haut/droite ICF Bottom/Left ICF bas/gauche @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` est la référence d’étape {r}, que seuls `run` et `command_batch` résolvent diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ff59a464c5..6e02028235 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1729,6 +1729,10 @@ ICC Profile ICC પ્રોફાઇલ ICF Bottom/Left ICF નીચે/ડાબે ICF Box ICF બૉક્સ + Show Sample નમૂનો બતાવો + Hide Sample નમૂનો છુપાવો + Max Ascent/Descent મહત્તમ એસેન્ટ/ડિસેન્ટ + Max Ascender મહત્તમ એસેન્ડર ICF Top/Right ICF ઉપર/જમણે ID: {id} ID: {id} Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..61262b0e24 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2358,6 +2358,10 @@ antiAlias Sharp शार्प ICC Profile ICC प्रोफ़ाइल ICF Bottom/Left ICF बॉटम/लेफ्ट ICF Box ICF बॉक्स + Show Sample नमूना दिखाएँ + Hide Sample नमूना छिपाएँ + Max Ascent/Descent अधिकतम एसेंट/डिसेंट + Max Ascender अधिकतम एसेंडर ICF Top/Right ICF ऊपर/दाएँ Identify Objects By ऑब्जेक्ट्स की पहचान करके If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. अगर ड्रॉइंग टैबलेट के पेन से ड्रॉ नहीं हो रहा, तो X11 (XWayland) ऑप्शन चुनें। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..f544a2841c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2139,6 +2139,10 @@ file-filter Templates Sablonok Em Box Kvirtmező x-Height x-magasság ICF Box ICF-mező + Show Sample Minta megjelenítése + Hide Sample Minta elrejtése + Max Ascent/Descent Max. magasság/mélység + Max Ascender Max. felnyúló szár ICF Top/Right ICF teteje/jobb oldala Identify Objects By Objektumok azonosítása Ignore Kihagy diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf029526f7..3203386c2b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1603,6 +1603,10 @@ digits Malayalam Malayalam Em Box Em Box x-Height Tinggi x ICF Box Kotak ICF + Show Sample Tampilkan contoh + Hide Sample Sembunyikan contoh + Max Ascent/Descent Tinggi/kedalaman maks. + Max Ascender Ascender maks. Copy Color Value (Hex) Salin nilai warna (Hex) Create New Swatch… Buat swatch baru… Name 40% Nama 40% diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..21bb2b3f5c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1033,6 +1033,10 @@ font-technology Variable Variabili Cap Height Altezza maiuscole x-Height Altezza x ICF Box Riquadro ICF + Show Sample Mostra campione + Hide Sample Nascondi campione + Max Ascent/Descent Altezza/profondità max + Max Ascender Ascendente max Em Dash Lineetta Em Space Spazio em Embed Incorpora diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..1d45694030 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -49,6 +49,10 @@ font-technology Variable バリアブル Cap Height キャップハイト x-Height x ハイト ICF Box 平均字面 + Show Sample サンプルを表示 + Hide Sample サンプルを隠す + Max Ascent/Descent 最大アセント/ディセント + Max Ascender 最大アセンダ Proportional Metrics プロポーショナルメトリクス H or V Style 横組み・縦組み用かな Roman Italics 欧文イタリック diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..2973e0d974 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3668,6 +3668,10 @@ digits Malayalam მალაიალამური Em Box Em-ბლოკი x-Height x-სიმაღლე ICF Box ICF-ბლოკი + Show Sample ნიმუშის ჩვენება + Hide Sample ნიმუშის დამალვა + Max Ascent/Descent მაქს. სიმაღლე/სიღრმე + Max Ascender მაქს. ზედა გამონაშვერი Copy Color Value (Hex) ფერის მნიშვნელობის კოპირება (Hex) Create New Swatch… ახალი ფერის ნიმუშის შექმნა… Name 40% სახელი 40% diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..c83ba8fcac 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -43,6 +43,10 @@ font-technology Variable 가변 Cap Height 대문자 높이 x-Height x 높이 ICF Box ICF 박스 + Show Sample 샘플 표시 + Hide Sample 샘플 숨기기 + Max Ascent/Descent 최대 어센트/디센트 + Max Ascender 최대 어센더 Proportional Metrics 비례 메트릭 H or V Style 가로 또는 세로 스타일 Roman Italics 로마자 이탤릭 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..7a58d4268f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2165,6 +2165,10 @@ digits Malayalam Malayalam Em Box Em-vak x-Height x-hoogte ICF Box ICF-vak + Show Sample Voorbeeld tonen + Hide Sample Voorbeeld verbergen + Max Ascent/Descent Max. hoogte/diepte + Max Ascender Max. stijger Copy Color Value (Hex) Kleurwaarde kopiëren (Hex) Create New Swatch… Nieuw staal maken… Name 40% Naam 40% diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..c6565f9917 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1659,6 +1659,10 @@ digits Malayalam Malajalam Em Box Ramka firetowa x-Height Wysokość x ICF Box Ramka ICF + Show Sample Pokaż próbkę + Hide Sample Ukryj próbkę + Max Ascent/Descent Maks. wysokość/głębokość + Max Ascender Maks. wydłużenie górne Copy Color Value (Hex) Kopiuj wartość koloru (hex) Create New Swatch… Utwórz nową próbkę… Name 40% Nazwa 40% diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..1b0833c0b1 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -917,6 +917,10 @@ antiAlias Sharp Nítido Em Box Caixa Eme x-Height Altura do x ICF Box Caixa ICF + Show Sample Mostrar Amostra + Hide Sample Ocultar Amostra + Max Ascent/Descent Altura/Profundidade Máx. + Max Ascender Ascendente Máx. Em Dash Travessão Em Space Espaço Em Embed Incorporar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..8ffa9c8294 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1022,6 +1022,10 @@ font-technology Variable Вариативные Em Box Кегельная площадка x-Height Высота строчных ICF Box Рамка ICF + Show Sample Показать образец + Hide Sample Скрыть образец + Max Ascent/Descent Макс. высота/глубина + Max Ascender Макс. выносной элемент вверх Em Dash Длинное тире Em Space Круглая шпация Embed Внедрить diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..5fc69aee4f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5261,6 +5261,10 @@ axis Both Båda Em Box Em-ruta x-Height x-höjd ICF Box ICF-ruta + Show Sample Visa exempel + Hide Sample Dölj exempel + Max Ascent/Descent Max höjd/djup + Max Ascender Max uppstapel @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` är stegreferensen {r}, som bara `run` och `command_batch` löser upp @msg `ids` must be an array of object ids, not {v} `ids` måste vara en array med objekt-id:n, inte {v} @msg `colors` must be an array of colors, not {v} `colors` måste vara en array med färger, inte {v} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..fd7874ca0d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5102,6 +5102,10 @@ axis Both Her İkisi Em Box Em Kutusu x-Height x-Yüksekliği ICF Box ICF Kutusu + Show Sample Örneği Göster + Hide Sample Örneği Gizle + Max Ascent/Descent Maks. Yükseklik/Derinlik + Max Ascender Maks. Yükselen @msg `colors` must be an array of colors, not {v} `colors` {v} değil, bir renk dizisi olmalıdır @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id`, yalnızca `run` ve `command_batch` komutlarının çözümlediği {r} adım referansıdır @msg `ids` must be an array of object ids, not {v} `ids` bir nesne kimlikleri dizisi olmalıdır, {v} değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..23518b48a3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1027,6 +1027,10 @@ font-technology Variable Варіативні Cap Height Висота великих літер x-Height Висота малих літер ICF Box Рамка ICF + Show Sample Показати зразок + Hide Sample Приховати зразок + Max Ascent/Descent Макс. висота/глибина + Max Ascender Макс. виносний елемент вгору Em Dash Довге тире Em Space Кругла шпація Embed Вбудувати diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..c7f88b944d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1992,6 +1992,10 @@ digits Hindi Hindi Cap Height Chiều cao chữ hoa x-Height Chiều cao chữ x ICF Box Ô ICF + Show Sample Hiện mẫu + Hide Sample Ẩn mẫu + Max Ascent/Descent Độ cao/sâu tối đa + Max Ascender Nét chân chữ trên tối đa ICF Top/Right ICF Trên/Phải Identify Objects By Nhận diện đối tượng theo Ignore Bỏ qua diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..0c9f32b932 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -964,6 +964,10 @@ antiAlias Sharp 锐利 Cap Height 大写字母高度 x-Height x 字高 ICF Box ICF 框 + Show Sample 显示样本 + Hide Sample 隐藏样本 + Max Ascent/Descent 最大上升/下降 + Max Ascender 最大上伸部 Em Dash 长破折号 Em Space 全角空格 Embed 嵌入 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..6f031565c4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -995,6 +995,10 @@ font-technology Variable 可變 Cap Height 大寫字母高度 x-Height x 字高 ICF Box ICF 框 + Show Sample 顯示樣本 + Hide Sample 隱藏樣本 + Max Ascent/Descent 最大上升/下降 + Max Ascender 最大上伸部 Em Dash 長破折號 Em Space 全形空格 Embed 嵌入 diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..cce0bf108f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9705,9 +9705,19 @@ font based on the one picked, Delete Font takes it out, Import… adds the fonts picked. Custom shows the font's custom character sets: Character Set picks one, New adds a set based on the one picked, Delete Set takes it out, and Name renames it. Character › Direct Entry adds the characters typed, and Character › Unicode adds the characters of hexadecimal codes (`3042`, `U+3042`, several separated by spaces or commas); Add skips -characters the set already lists. Delete takes the character picked out of the set. OK runs `type.compositeFonts.set` -with every font as one undo step; a refused font keeps the dialog open. `ui.dialog.set` takes `custom`, `entry` and -`char` (the index of the character picked in the set) as soon as the dialog opens. +characters the set already lists. Delete takes the character picked out of the set. Show Sample (Hide Sample when it +shows) draws the font picked in a line of sample text, with the first character of each custom set added, and a button +beside it for each line it can mark: ICF Box, Em Box, Baseline, Cap Height, Max Ascent/Descent, Max Ascender and +x-height ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=300)). +The em box and ICF box are those of the Kanji part's font, the cap height and x-height those of the face the +Roman letters are drawn in (a fallback face when the part's font lacks the character), Max Ascent/Descent the highest +ascent and lowest descent of the faces the sample uses, and Max Ascender the top of its tallest glyph; each takes its +part's size, baseline and vertical scale. Zoom draws it at 25% to 800% of 36 pt. The +sample text, the zoom steps and the size are VectorCraft's own. OK runs `type.compositeFonts.set` with every font as one +undo step; a refused font keeps the dialog open. `ui.dialog.set` takes `custom`, `entry` and `char` (the index of the +character picked in the set) as soon as the dialog opens, and `sample` (true or false), `zoom` (25, 50, 75, 100, 200, +400 or 800) and `lineIcfBox`, `lineEmBox`, `lineBaseline`, `lineCapHeight`, `lineAscentDescent`, `lineAscender` and +`lineXHeight` (true or false; the first three start true); another value is refused. ```json {"name":"run_command","arguments":{"command":"type.compositeFonts.set","params":{"fonts":[{"name":"My Composite","parts":{"kanji":{"font":"Source Han Sans"},"roman":{"font":"Source Sans 3","size":95,"baseline":-2},"numerals":{"font":"Source Sans 3"}}}]}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 65cbf9e216..fce00c8fb2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -710,6 +710,7 @@ since 2026-10-01. - **Composite fonts that two documents define differently:** when two open documents each define a composite font (Type › Composite Fonts…) by the same name with different parts, each document draws and exports its type in its own definition: in a tiled or floating window drawn while the front document draws, when it is placed in a document that defines the name differently, and in an export made while another document is in front. Evidence: `tests::composite::nested_loans_of_one_name_use_each_documents_definition` and `threads_lending_one_name_at_once_use_their_own_definitions` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` (`crates/render`). Scores unchanged (estimated). - **Composite fonts only another document defines:** a document draws, measures and exports its type only in the composite fonts it defines itself. Type naming a composite font that only another open document, or the document a placed document sits in, defines is set as in a missing font, also when the document defines no composite font: in a window, a thumbnail or an export of a document in the back, in a file being opened and in a placed document. A temporary document drawn while a document draws keeps that document's composite fonts. Evidence: `tests::composite::a_lent_document_does_not_use_another_documents_composite_font` and `a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` and `a_document_draws_type_in_another_documents_composite_font_as_missing` (`crates/render`), `a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing` (`crates/engine`). Scores unchanged (estimated). - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). +- **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=300)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). diff --git a/docs/type-parity.md b/docs/type-parity.md index e6adf78d09..9576d55d72 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -74,7 +74,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | | CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for (in `GSUB`, or for the width forms `GSUB` or `GPOS`) is disabled, and Revert To Default Forms draws the default glyphs. A form other than the default takes away a character's glyph choice, and with a width form Proportional Metrics' `palt` is not applied and the font's pair kerning is off. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `typecmd::area_tests::a_glyph_form_takes_away_the_characters_glyph_choice`, `features::tests::width_forms_turn_off_proportional_metrics`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form`, `panels::glyphs::tests::glyph_form_items_at_a_caret_follow_all_the_text`, `panels::glyphs::tests::a_glyph_choice_lets_the_current_form_be_chosen_again` | | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | -| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Not yet: the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | +| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=300)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Serbian: Cyrillic, Serbian: Latin and Croatian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation by it in languages other than English and the eleven Indian languages above, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | From c26c1f3efdb98e2cbc89eafcc417520b7d4e9bf8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:31:22 -0800 Subject: [PATCH 21/50] Type: the font menu's Show Similar Fonts lists the families that look like a family first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A ≈ button on a family's row in the font menus orders the listed families by how alike they look to it: that family first, then the families that set the same script (Japanese, Thai or neither), then the others, each group nearest first. The Recent Fonts section is left out while the list is ordered this way. A ≈ chip under the filters names the family and clears the order, with that family still highlighted; closing the menu clears it too. The measure is VectorCraft's own. Each face records its OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, and its post italic angle; a named instance of a variable font takes its wght and slnt settings. The system font scan reads the head table and the post table's header besides the tables it read before, so installed families are compared by the same numbers without loading them. A family is compared by its face nearest an upright Regular, a number either face does not give is left out, and a family of another kind counts as further away. text.similarFonts {family, limit?} returns the same order, with errors for a missing or non-string family, a family that is not available or not listed in the font menus, and a limit that is not a whole number from 1 to 100000. --- crates/engine/src/cmd/fonts.rs | 39 ++++++++ crates/engine/src/tests/fontlist.rs | 33 +++++++ crates/text/src/fontdb.rs | 2 +- crates/text/src/fontdb/cache.rs | 5 +- crates/text/src/fontdb/db.rs | 5 +- crates/text/src/fontdb/lookup.rs | 65 ++++++++++-- crates/text/src/fontdb/scan.rs | 30 ++++-- crates/text/src/fontdb/traits.rs | 136 ++++++++++++++++++++++++-- crates/text/src/lib.rs | 8 +- crates/text/src/tests.rs | 1 + crates/text/src/tests/similar.rs | 119 ++++++++++++++++++++++ crates/text/src/tests/sysfonts.rs | 27 ++++- crates/ui-egui/src/font_menu.rs | 125 +++++++++++++++++++---- crates/ui-egui/src/font_menu/tests.rs | 84 +++++++++++++++- 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 + docs/mcp.md | 14 +++ docs/type-parity.md | 2 +- 44 files changed, 693 insertions(+), 58 deletions(-) create mode 100644 crates/text/src/tests/similar.rs diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 28662f013c..7419b915f0 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,15 @@ pub fn specs() -> Vec { always, font_list ), + cmd!( + query "text.similarFonts", + "Show Similar Fonts", + [], + None, + "{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000", + always, + similar_fonts + ), cmd!( "text.rescanFonts", "Refresh Font List", @@ -1137,6 +1146,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result { } } +/// The most families `text.similarFonts` takes as its `limit`. +const MAX_SIMILAR: u64 = 100_000; + +fn similar_fonts(_: &mut Session, p: &Value) -> Result { + const C: &str = "text.similarFonts"; + let db = vectorcraft_text::FontDb::global(); + let family = match p.get("family") { + Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(), + Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")), + Some(_) => return Err(bad(C, "`family` must be a string")), + }; + let limit = match p.get("limit") { + None => None, + Some(v) => Some( + v.as_u64() + .filter(|n| (1..=MAX_SIMILAR).contains(n)) + .ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?, + ), + }; + // Any of the family's names, spelled as the font menus list it; a family they don't list is not available. + let menu = db.menu_family_list(); + let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned()); + let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) }; + let mut families = db.similar_families(&family, &menu); + if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) { + families.truncate(n); + } + Ok(json!({ "family": family, "families": families })) +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 6202a8ce70..4a17bf734a 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -34,6 +34,39 @@ fn the_font_list_names_every_available_family_with_its_styles() { assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err()); } +/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the +/// order the font menus show; bad params are refused. +#[test] +fn similar_fonts_lists_every_family_by_likeness() { + let mut s = Session::new(); + let db = FontDb::global(); + let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap(); + assert_eq!(r["family"], "Source Sans 3"); + let order = names(&r["families"]); + assert_eq!(order.first().map(String::as_str), Some("Source Sans 3")); + let mut sorted = order.clone(); + sorted.sort(); + let mut listed = db.menu_family_list().to_vec(); + listed.sort(); + // Other tests running at the same time add and remove composite fonts; the installed families are compared. + let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); + assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); + let two = s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap(); + assert_eq!(names(&two["families"]), order[..2]); + for (params, error) in [ + (json!({}), "`family` is required"), + (json!({"family": " "}), "`family` is required"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "font family `No Such Font` is not available"), + (json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"), + ] { + let e = s.execute("text.similarFonts", ¶ms).unwrap_err().to_string(); + assert!(e.contains(error), "{params}: {e}"); + } +} + #[test] fn refreshing_the_font_list_redraws_type_without_editing_the_document() { let mut s = Session::new(); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index e96e1d0fae..0309084420 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -70,7 +70,7 @@ pub use stylistic_sets::StylisticSet; use traits::Alias; #[cfg(test)] use traits::{FaceKeys, face_names}; -pub use traits::{FontClass, FontMatch, FontTraits}; +pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits}; #[cfg(test)] pub(crate) use traits::{alias_lists, face_styles, on_faces_published}; pub use wanted::{WantedFont, WantedFonts}; diff --git a/crates/text/src/fontdb/cache.rs b/crates/text/src/fontdb/cache.rs index 09b03c410c..72bed5519b 100644 --- a/crates/text/src/fontdb/cache.rs +++ b/crates/text/src/fontdb/cache.rs @@ -8,7 +8,10 @@ pub(super) struct CatalogFamily { /// Non-English family name from the name table, when the scan found one. pub(super) native: Option, pub(super) faces: Vec, - /// The family's kind (from its first face found); variable when any face found is. + /// The family's kind (from its first face found); variable when any face found is. Its + /// likeness is the one of the face found nearest an upright Regular ([`regular_rank`]). + /// + /// [`regular_rank`]: super::traits::regular_rank pub(super) traits: Option, } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 738a158952..e890e0c833 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -16,7 +16,7 @@ use super::scan::{file_face_names, is_font_file}; #[cfg(test)] use super::traits::faces_published; #[cfg(not(target_arch = "wasm32"))] -use super::traits::{Alias, FaceStyle}; +use super::traits::{Alias, FaceStyle, regular_rank}; use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId}; #[cfg(not(target_arch = "wasm32"))] use super::{ScanStamp, modified}; @@ -430,6 +430,9 @@ impl FontDb { let entry = catalog.entry(family.to_ascii_lowercase()).or_default(); let kind = entry.traits.get_or_insert(traits); kind.variable |= traits.variable; + if regular_rank(&traits.likeness) < regular_rank(&kind.likeness) { + kind.likeness = traits.likeness; + } if entry.name.is_empty() { entry.name = family; } diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 23e00afa0c..f27c5fbc44 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -9,7 +9,7 @@ use super::names::SYSTEM_FALLBACKS; use super::names::{norm, norm_chars, script_families}; #[cfg(not(target_arch = "wasm32"))] use super::scan::{enumerate_faces, font_files}; -use super::traits::{Alias, FontMatch, FontTraits}; +use super::traits::{Alias, FontMatch, FontTraits, regular_rank}; use super::{ Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering, Size, @@ -86,26 +86,77 @@ impl FontDb { /// loaded face, else from the system font scan. Variable when any of its faces, loaded or /// scanned, is: a family may install static files beside a variable one. Cheap: no font file /// is read, and a loaded family doesn't start the scan. A composite font takes its base font's. + /// Its likeness is the one of its face nearest an upright Regular, loaded or scanned. pub fn family_traits(&self, family: &str) -> FontTraits { if let Some((base, _)) = self.composite_base(family) { return self.family_traits(&base); } let loaded = { let faces = self.read_faces(); - let mut of_family = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)); - of_family.next().map(|first| FontTraits { variable: first.traits.variable || of_family.any(|f| f.traits.variable), ..first.traits }) + let mut found: Option = None; + for f in faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)) { + match &mut found { + None => found = Some(f.traits), + Some(traits) => { + traits.variable |= f.traits.variable; + if regular_rank(&f.traits.likeness) < regular_rank(&traits.likeness) { + traits.likeness = f.traits.likeness; + } + } + } + } + found }; let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits); match loaded { None => scanned(&self.read_catalog()).unwrap_or_default(), - Some(traits) if traits.variable => traits, - Some(traits) => { - let variable = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)).is_some_and(|t| t.variable); - FontTraits { variable, ..traits } + Some(mut traits) => { + // What the scan found so far, without starting it. + if let Some(found) = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)) { + traits.variable |= found.variable; + if regular_rank(&found.likeness) < regular_rank(&traits.likeness) { + traits.likeness = found.likeness; + } + } + traits } } } + /// `families` ordered by how alike they look to `family` (Show Similar Fonts): `family` itself + /// first when listed, then the families that set the same script as it (Japanese, Thai or + /// neither, as [`FontTraits`] tells), then the others, each group nearest first by + /// [`FontLikeness::distance`](super::FontLikeness::distance) of their + /// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`]) + /// counting 2 further. Families equally far keep their order in `families`. Reads no font + /// file, as `family_traits` does not. + pub fn similar_families(&self, family: &str, families: &[String]) -> Vec { + let base = self.family_traits(family); + let script = |t: &FontTraits| { + if t.japanese { + 0 + } else if t.thai { + 1 + } else { + 2 + } + }; + let mut keyed: Vec<(bool, f32, &String)> = families + .iter() + .map(|f| { + let traits = self.family_traits(f); + let d = if f.eq_ignore_ascii_case(family) { + -1.0 + } else { + base.likeness.distance(&traits.likeness) + if traits.class == base.class { 0.0 } else { 2.0 } + }; + (script(&traits) != script(&base), d, f) + }) + .collect(); + keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + keyed.into_iter().map(|(_, _, f)| f.clone()).collect() + } + /// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how /// it matched. A composite font matches as its base font does ([`Self::composite_base`]). pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc, FontMatch)> { diff --git a/crates/text/src/fontdb/scan.rs b/crates/text/src/fontdb/scan.rs index ebe4d4d443..e25891fb32 100644 --- a/crates/text/src/fontdb/scan.rs +++ b/crates/text/src/fontdb/scan.rs @@ -160,6 +160,8 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa use std::io::SeekFrom; /// The largest table read from a (possibly damaged) file. const MAX_NAME_TABLE: u32 = 1 << 20; + /// The `post` table's header: version, italic angle, underline and fixed-pitch fields. + const POST_HEADER: u32 = 32; let mut read = 0u64; let mut read_at = |offset: u64, len: usize| -> Option> { read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?; @@ -186,26 +188,34 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) { return None; } - let mut table = |tag: &[u8; 4]| -> Option> { + // A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing. + let mut table_within = |tag: &[u8; 4], most: u32| -> Option> { let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?; - let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?); + let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most)); if len > MAX_NAME_TABLE { return None; } read_at(offset.into(), len as usize) }; - let name = table(b"name")?; + let name = table_within(b"name", u32::MAX)?; // A variable font's named instances are styles too. - let fvar = table(b"fvar"); + let fvar = table_within(b"fvar", u32::MAX); // Its OS/2 table (the font's classification, for the menus' filters), when it has one. - let os2 = table(b"OS/2"); + let os2 = table_within(b"OS/2", u32::MAX); + // Its units per em and italic angle, for Show Similar Fonts ([`super::FontLikeness`]): + // the `head` table and the `post` table's 32-byte header, as a version 3 table (one + // without glyph names). + let head = table_within(b"head", u32::MAX); + let post = table_within(b"post", POST_HEADER).filter(|p| p.len() == POST_HEADER as usize).map(|mut p| { + p[..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes()); + p + }); // A font holding just these tables, to read them as the font itself would. let mut tables: Vec<(&[u8; 4], &[u8])> = vec![(b"name", &name)]; - if let Some(fvar) = &fvar { - tables.push((b"fvar", fvar)); - } - if let Some(os2) = &os2 { - tables.push((b"OS/2", os2)); + for (tag, data) in [(b"fvar", &fvar), (b"OS/2", &os2), (b"head", &head), (b"post", &post)] { + if let Some(data) = data { + tables.push((tag, data.as_slice())); + } } let font = sfnt_of(&tables)?; Some(face_styles(&skrifa::FontRef::new(&font).ok()?)) diff --git a/crates/text/src/fontdb/traits.rs b/crates/text/src/fontdb/traits.rs index b6244b81d9..335e4dba13 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -101,6 +101,111 @@ pub struct FontTraits { /// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of /// its faces has. pub variable: bool, + /// What Show Similar Fonts compares; for a family, its face nearest an upright Regular. + pub likeness: FontLikeness, +} + +/// The numbers a font menu's Show Similar Fonts compares faces by ([`FontLikeness::distance`]), +/// read from the face's OS/2, `head` and `post` tables only, so that the system font scan reads +/// the same numbers without loading the font ([`super::scan::file_face_names`]). Each is 0 (the +/// italic angle `None`) when the face does not say (no such table, or an OS/2 table too old to +/// hold the value). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FontLikeness { + /// The OS/2 PANOSE digits (0 is "any" and 1 "no fit" in each digit). + pub panose: [u8; 10], + /// The OS/2 weight class, at most 1000; a named instance's `wght` setting. + pub weight: u16, + /// The OS/2 width class, 1 to 9. + pub width: u8, + /// The OS/2 x-height and cap height in thousandths of the em. + pub x_height: u16, + pub cap_height: u16, + /// The OS/2 average character width in thousandths of the em. + pub avg_width: u16, + /// The `post` table's italic angle in tenths of a degree (negative: leaning right); a named + /// instance's `slnt` setting. + pub italic_angle: Option, + /// The face is italic or oblique: by its OS/2 selection flags or a nonzero italic angle; a + /// named instance by its `ital` or `slnt` setting or its name. Not compared; it picks a + /// family's face nearest an upright Regular. + pub italic: bool, +} + +impl FontLikeness { + /// From a face's tables, with a named instance's `variations` (its axis settings in user + /// units; empty for the face itself): its `weight` (`wght` setting) in place of the OS/2 + /// weight class, its `slnt` setting in place of the italic angle, and whether it is + /// `italic`. The heights and the average width need the `head` table's units per em (16 to + /// 16384). + fn of(font: &skrifa::FontRef<'_>, variations: &[Variation], weight: Option, italic: Option) -> Self { + use skrifa::raw::TableProvider; + let em = font.head().ok().map(|h| h.units_per_em()).filter(|u| (16..=16384).contains(u)).map(f32::from); + // Thousandths of the em, 0 for nothing (and for a value at or below 0). + let per_mille = |v: i16| match em { + Some(em) if v > 0 => (f32::from(v) / em * 1000.0).round().min(4000.0) as u16, + _ => 0, + }; + let mut likeness = Self::default(); + if let Ok(o) = font.os2() { + for (digit, value) in likeness.panose.iter_mut().zip(o.panose_10()) { + *digit = *value; + } + likeness.weight = o.us_weight_class().min(1000); + likeness.width = u8::try_from(o.us_width_class()).ok().filter(|w| (1..=9).contains(w)).unwrap_or(0); + likeness.x_height = o.sx_height().map_or(0, per_mille); + likeness.cap_height = o.s_cap_height().map_or(0, per_mille); + likeness.avg_width = per_mille(o.x_avg_char_width()); + // fsSelection's ITALIC (bit 0) and OBLIQUE (bit 9) flags. + likeness.italic = o.fs_selection().bits() & 0x0201 != 0; + } + if let Some(w) = weight.filter(|w| w.is_finite()) { + likeness.weight = w.round().clamp(1.0, 1000.0) as u16; + } + let angle = |a: f32| (a.is_finite() && a.abs() <= 90.0).then(|| (a * 10.0).round() as i16); + likeness.italic_angle = match variations.iter().find(|(tag, _)| tag == b"slnt") { + Some((_, slant)) => angle(*slant), + None => font.post().ok().and_then(|p| angle(p.italic_angle().to_f32())), + }; + likeness.italic = italic.unwrap_or(likeness.italic || likeness.italic_angle.is_some_and(|a| a != 0)); + likeness + } + + /// How unlike two faces look: 0 for faces whose numbers are all the same, more the further + /// apart they are. A number one of the faces does not give is left out. PANOSE digits are + /// compared only between faces of the same PANOSE family kind; faces of different kinds count + /// 3 apart. The weights and scales are VectorCraft's own. + pub fn distance(&self, other: &Self) -> f32 { + let mut d = 0.0; + let (kind, other_kind) = (self.panose[0], other.panose[0]); + if kind > 1 && other_kind > 1 { + if kind == other_kind { + for (a, b) in self.panose.iter().zip(&other.panose).skip(1) { + if *a > 1 && *b > 1 { + d += f32::from(a.abs_diff(*b)) * 0.15; + } + } + } else { + d += 3.0; + } + } + if self.weight != 0 && other.weight != 0 { + d += f32::from(self.weight.abs_diff(other.weight)) / 200.0; + } + if self.width != 0 && other.width != 0 { + d += f32::from(self.width.abs_diff(other.width)) * 0.5; + } + for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)] + { + if a != 0 && b != 0 { + d += f32::from(a.abs_diff(b)) / 1000.0 * scale; + } + } + if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) { + d += f32::from(a.abs_diff(b)) / 50.0; + } + d + } } impl FontTraits { @@ -216,10 +321,20 @@ impl FontTraits { FontClass::Other }; let variable = (1..=MAX_AXES).contains(&font.axes().len()); - FontTraits { japanese, thai, class, variable } + FontTraits { japanese, thai, class, variable, likeness: FontLikeness::of(font, &[], None, None) } } } +/// How far a face is from an upright Regular by its `likeness`: an italic or oblique face +/// ([`FontLikeness::italic`]) after every upright one, then by how far its weight is from 400 (a +/// face that gives no weight last), then by the numbers themselves, so that the same faces give +/// the same answer whichever is found or loaded first. The lower, the nearer. A family's likeness +/// ([`FontTraits::likeness`]) is its lowest-ranked face's, whether the faces are scanned or loaded. +pub(super) fn regular_rank(likeness: &FontLikeness) -> (bool, u16, FontLikeness) { + let off = if likeness.weight == 0 { u16::MAX } else { likeness.weight.abs_diff(400) }; + (likeness.italic, off, *likeness) +} + /// What a name other than a family's own one stands for ([`FontDb::canonical`]). #[derive(Clone, Debug)] pub(super) struct Alias { @@ -342,11 +457,7 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec { let Some((family, style)) = face_names(f) else { return vec![] }; let native_family = native_family_name(f, &family); let mut keys = FaceKeys::of(f, &family, &style); - let traits = FontTraits::of(f, &keys); - let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone()); - for i in &mut instances { - i.traits = traits; - } + let mut traits = FontTraits::of(f, &keys); // A variable font's default face renders at its `wght` default, whatever its name table and // OS/2 table say (Noto Sans Hebrew: named `Light`, weight class 300, default instance Regular // at 400): weigh it so, and name it by its default instance when that is another weight. @@ -357,6 +468,19 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec { .map(|a| a.default_value()) .filter(|w| w.is_finite()) .map(|w| w.clamp(1.0, 1000.0)); + // Its likeness is likewise taken at its axes' defaults (`wght` and `slnt`). + if f.axes().len() <= MAX_AXES { + let defaults: Vec = f.axes().iter().map(|a| (a.tag().to_be_bytes(), a.default_value())).collect(); + traits.likeness = FontLikeness::of(f, &defaults, weight, None); + } + let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone()); + // Each named instance shares the face's kind; its likeness is measured at its own axis settings. + // Without an `ital` or `slnt` axis, an instance of an italic face is italic too. + for i in &mut instances { + let slant_axis = i.variations.iter().any(|(tag, _)| tag == b"ital" || tag == b"slnt"); + let italic = i.italic || (!slant_axis && traits.likeness.italic); + i.traits = FontTraits { likeness: FontLikeness::of(f, &i.variations, i.weight, Some(italic)), ..traits }; + } let style = renamed.unwrap_or(style); let face = FaceStyle { family, native_family, style, keys, variations: vec![], weight, italic: false, traits }; std::iter::once(face).chain(instances).collect() diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..5733871779 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -41,10 +41,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, JoiningPosition, - LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, - user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, + JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, + is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, + system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4bab8aa561..b9a0b5d216 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -28,6 +28,7 @@ mod path_joins; mod ruby; mod scripts; mod shape_plans; +mod similar; mod snap; mod svg_glyphs; mod sysfonts; diff --git a/crates/text/src/tests/similar.rs b/crates/text/src/tests/similar.rs new file mode 100644 index 0000000000..718f4607ea --- /dev/null +++ b/crates/text/src/tests/similar.rs @@ -0,0 +1,119 @@ +//! Show Similar Fonts: the numbers a face is compared by ([`FontLikeness`]), a family's likeness +//! from its face nearest an upright Regular, and families ordered by likeness. + +use skrifa::raw::TableProvider; + +use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font}; +use crate::*; + +/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without +/// heights in their OS/2 tables. +fn db() -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + for heights in [true, false] { + assert_eq!(db.add_font(height_font(heights).expect("the test font builds")), 1); + } + db +} + +fn names(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn a_face_is_compared_by_its_tables() { + let db = db(); + let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness; + assert_eq!(regular.weight, 400); + assert_eq!(regular.italic_angle, Some(0)); + assert!(regular.panose[0] > 1, "a PANOSE family kind: {regular:?}"); + assert!(regular.x_height > 300 && regular.cap_height > regular.x_height, "{regular:?}"); + // The OS/2 average character width, in thousandths of the em. + let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSans3-Regular.ttf")).expect("bundled"); + let font = skrifa::FontRef::new(&bytes).expect("it parses"); + let (avg, em) = (font.os2().expect("an OS/2 table").x_avg_char_width(), font.head().expect("a head table").units_per_em()); + assert_eq!(f32::from(regular.avg_width), (f32::from(avg) / f32::from(em) * 1000.0).round()); + let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness; + assert!(italic.italic_angle.is_some_and(|a| a < 0), "leans right: {italic:?}"); + assert!(italic.italic && !regular.italic); + let bold = db.face("Source Sans 3", "Bold").expect("bundled").traits.likeness; + assert_eq!(bold.weight, 700); + // The OS/2 heights, in thousandths of its 1,000-unit em. + let heights = db.family_traits(HEIGHT_FAMILY).likeness; + assert_eq!((heights.x_height, heights.cap_height), (HEIGHT_X as u16, HEIGHT_CAP as u16)); + // Without them (a version 1 OS/2 table), the heights are left out. + let heightless = db.family_traits(HEIGHTLESS_FAMILY).likeness; + assert_eq!((heightless.x_height, heightless.cap_height), (0, 0), "{heightless:?}"); + assert_eq!(heightless.avg_width, regular.avg_width); +} + +/// A variable font's named instance takes its `wght` setting as its weight; the default face its +/// default weight. +#[test] +fn a_named_instance_is_weighed_by_its_axis_setting() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(variable_font().expect("the test font builds")), 3); + let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the default face").traits.likeness; + let semibold = db.face(VARIABLE_FAMILY, "SemiBold").expect("a named instance").traits.likeness; + let bold = db.face(VARIABLE_FAMILY, "Bold").expect("a named instance").traits.likeness; + assert_eq!((regular.weight, semibold.weight, bold.weight), (400, 550, 700)); + // The family is compared by its Regular face. + assert_eq!(db.family_traits(VARIABLE_FAMILY).likeness, regular); +} + +/// A face without an italic angle is compared by the other numbers only. +#[test] +fn a_missing_italic_angle_is_left_out() { + let db = db(); + let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness; + assert_eq!(italic.distance(&FontLikeness { italic_angle: None, ..italic }), 0.0); + assert!(italic.distance(&FontLikeness { italic_angle: Some(0), ..italic }) > 0.0); +} + +/// A family is compared by its face nearest an upright Regular, not by the first one loaded. +#[test] +fn a_family_is_compared_by_its_regular_face() { + let db = db(); + let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness; + assert_eq!(db.family_traits("Source Sans 3").likeness, regular); + assert_eq!(db.family_traits("source sans 3").likeness, regular, "by any case"); +} + +#[test] +fn likeness_is_a_distance() { + let db = db(); + let (sans, serif, mono) = + (db.family_traits("Source Sans 3").likeness, db.family_traits("Source Serif 4").likeness, db.family_traits("JetBrains Mono").likeness); + assert_eq!(sans.distance(&sans), 0.0); + assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric"); + assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0); + // A number a face does not give is left out, not counted as 0. + let unknown = FontLikeness::default(); + assert_eq!(sans.distance(&unknown), 0.0); + let lighter = FontLikeness { weight: 300, ..sans }; + assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart"); +} + +/// The family itself first, then nearest first: a copy of Source Sans 3 Regular comes before every +/// other family, and the order never moves away from the family and back. +#[test] +fn families_are_ordered_by_likeness() { + let db = db(); + let families = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]); + let order = db.similar_families("Source Sans 3", &families); + assert_eq!(order.len(), families.len()); + assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}"); + let base = db.family_traits("Source Sans 3"); + let far = |f: &str| { + let t = db.family_traits(f); + base.likeness.distance(&t.likeness) + if t.class == base.class { 0.0 } else { 2.0 } + }; + for pair in order[1..].windows(2) { + assert!(far(&pair[0]) <= far(&pair[1]), "{order:?}"); + } + // Asked by another case, or for a family not in the list. + assert_eq!(db.similar_families("SOURCE SANS 3", &families)[0], "Source Sans 3"); + let without = db.similar_families("Source Sans 3", &families[..4]); + assert_eq!(without[0], HEIGHTLESS_FAMILY); + assert!(db.similar_families("Source Sans 3", &[]).is_empty()); +} diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index d4068eb5da..9176248ffc 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -428,6 +428,29 @@ fn a_family_with_a_variable_file_beside_static_ones_is_variable() { assert!(db.family_traits(FAMILY).variable); } +/// Show Similar Fonts: the scan reads the numbers a face is compared by as loading the face does, +/// and a family's are its Regular face's whichever file is found first. +#[test] +fn the_scan_reads_a_familys_likeness_without_loading_it() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-likeness", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Sysfont-Italic.ttf"), renamed("SourceSans3-It.ttf")).unwrap(); + std::fs::write(dir.join("Sysfont-Regular.ttf"), renamed("SourceSans3-Regular.ttf")).unwrap(); + let scanned = FontDb::with_font_dirs(vec![dir.clone()]); + let likeness = scanned.family_traits(FAMILY).likeness; + assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded"); + let loaded = FontDb::with_font_dirs(vec![]); + assert_eq!(loaded.add_font(renamed("SourceSans3-Regular.ttf")), 1); + assert_eq!(likeness, loaded.face(FAMILY, "Regular").unwrap().traits.likeness); + assert!(likeness.avg_width > 0 && likeness.x_height > 0 && likeness.italic_angle == Some(0), "{likeness:?}"); + // With only the italic loaded, the scanned Regular face still gives the family's numbers. + assert_eq!(scanned.add_font(renamed("SourceSans3-It.ttf")), 1); + assert!(scanned.is_loaded(FAMILY)); + assert_eq!(scanned.family_traits(FAMILY).likeness, likeness); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn registered_fonts_outside_the_font_folders_are_their_full_paths() { let dir = std::env::temp_dir().join("Fonts"); @@ -697,8 +720,8 @@ fn a_search_reads_at_most_its_share_of_a_font_file() { let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap(); u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap())) }; - // What one face costs: its table directory and its name and OS/2 tables. - let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2"); + // What one face costs: its table directory, its name, OS/2 and head tables and the post table's header. + let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2") + len(b"head") + 32; let n = 300; let base = 12 + 4 * n; let mut ttc = b"ttcf".to_vec(); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 9b829114c2..084311e93c 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -4,7 +4,10 @@ //! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in //! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text //! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the -//! document. A star marks a favourite family, and the ★ filter lists only those. The Font +//! document. A star marks a favourite family, and the ★ filter lists only those. The ≈ button +//! before a family's star (Show Similar Fonts) orders the listed families by how alike they look to +//! it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent +//! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable //! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays //! out its filters on the same four rows wherever it opens. However narrow its field, it opens at @@ -160,6 +163,8 @@ impl<'a> MenuLook<'a> { const ROW: f32 = 24.0; /// Width of the star at the end of a family's row. const STAR: f32 = 18.0; +/// Width of the Show Similar Fonts button before the star. +const SIMILAR: f32 = 18.0; /// The least share of a row the family's name takes when the row is too narrow for the widest /// name and [`SAMPLE_W`]; the sample fills the rest. const NAME_SHARE: f32 = 0.5; @@ -305,8 +310,8 @@ fn remap_highlight(before: &[Row], selected: Option, after: &[Row]) -> Op /// What the rows were listed for: the query, the script, kind, font technology (variable only) and /// favourites filters, Show Font Names in English, the expanded families, favourites, recent -/// history and font list generation. -type RowsKey = (String, usize, Option, bool, bool, bool, Vec, Vec, Vec, u64); +/// history, font list generation and the family Show Similar Fonts orders by. +type RowsKey = (String, usize, Option, bool, bool, bool, Vec, Vec, Vec, u64, Option); /// The menu's state between frames. #[derive(Clone, Default)] @@ -330,6 +335,12 @@ struct MenuState { favorites_only: bool, /// Families whose styles are listed (lowercase). expanded: Vec, + /// Show Similar Fonts: the family the list is ordered by likeness to, until it is cleared or + /// the menu closes. + similar: Option, + /// Show Similar Fonts was chosen or cleared: the family it ordered by, which is highlighted + /// and scrolled to once (to the top while the list is ordered by it). + similar_moved: Option, /// What was previewed last (None: nothing is previewed). previewed: Option<(String, Option)>, /// The rows listed, and what for: built again only when that changes, not every frame. @@ -1043,6 +1054,8 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, st.highlight = None; st.query.clear(); st.current = current.to_string(); + st.similar = None; + st.similar_moved = None; } st.last = pass; // For [`end_stale_preview`]: the menu is open, in this layer. @@ -1080,10 +1093,15 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, look.favorites.to_vec(), look.recent.to_vec(), db.generation(), + st.similar.clone(), ); if st.rows_key.as_ref() != Some(&key) { let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect(); - let rows = grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)); + // Show Similar Fonts orders every listed family by likeness, the recent ones among them. + let rows = match &st.similar { + Some(base) => grouped_rows(&db.similar_families(base, &families), &[], &st.expanded, |f| db.styles(f)), + None => grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)), + }; // Filter changes (including un-starring a favourite) may remove rows; expanding // another family or a background font scan can insert rows before the highlight. // Never preview an unrelated family because the old numeric index now points to it. @@ -1096,6 +1114,9 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, st.query = query.clone(); st.highlight = None; } + if let Some(base) = &st.similar_moved { + st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(base))); + } if st.highlight.is_none() && query.is_empty() { st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(current))); } @@ -1196,16 +1217,29 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool { }); } st.filters = widest; + // While Show Similar Fonts orders the list: the family it orders by, which clears it. Its + // width is left out of the widest row: a long name wraps instead of widening the menu. + if let Some(base) = st.similar.clone() { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 2.0); + let chip = egui::RichText::new(format!("≈ {base} ✕")).size(FILTER_SIZE); + if ui.selectable_label(true, chip).on_hover_text(tl!("Clear Similar Fonts")).clicked() { + st.similar_moved = st.similar.take(); + refilter = true; + } + }); + } refilter } /// The width the open menu takes at least: the widest row of filters last frame, and the widest -/// name up to [`NAME_MAX`] with room for its sample, the star and the scroll bar beside it, within -/// [`WINDOW_SHARE`] of the window. The menu is never narrower than its field. +/// name up to [`NAME_MAX`] with room for its sample, the Show Similar Fonts button, the star and the +/// scroll bar beside it, within [`WINDOW_SHARE`] of the window. The menu is never narrower than its +/// field. fn menu_width(ui: &Ui, st: &MenuState, look: MenuLook) -> f32 { let sample = if look.samples { SAMPLE_W } else { 0.0 }; let names = name_width(ui, vectorcraft_text::FontDb::global(), look.english_names, &st.rows).min(NAME_MAX); - let row = DISCLOSURE + names + NAME_GAP + sample + STAR + 2.0 + widgets::list_scroll_style().allocated_width(); + let row = DISCLOSURE + names + NAME_GAP + sample + SIMILAR + STAR + 2.0 + widgets::list_scroll_style().allocated_width(); // Rounding in the chips' widths must not wrap the widest row. let filters = if st.filters > 0.0 { st.filters.ceil() + 1.0 } else { 0.0 }; filters.max(row).min(ui.ctx().content_rect().width() * WINDOW_SHARE) @@ -1267,13 +1301,14 @@ fn widest_label(ui: &Ui, labels: Vec) -> f32 { } /// Where a row `width` wide puts its sample, after the name column: room for the widest name -/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`] and the star for the sample or -/// [`NAME_SHARE`] of the row for the name. Without samples the name runs to the star. +/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`], the Show Similar Fonts button and the +/// star for the sample or [`NAME_SHARE`] of the row for the name. Without samples the name runs to +/// the Show Similar Fonts button. fn name_column(width: f32, widest: f32, samples: bool) -> f32 { if !samples { - return width - STAR; + return width - SIMILAR - STAR; } - (DISCLOSURE + widest + NAME_GAP).min((width - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE)) + (DISCLOSURE + widest + NAME_GAP).min((width - SIMILAR - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE)) } /// The disclosure triangle of a family with several styles; whether the pointer is on it. @@ -1293,6 +1328,18 @@ fn star_cell(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, (on, hi resp.interact_pointer_pos().is_some_and(|pos| star.contains(pos)) } +/// The Show Similar Fonts button before a family's star, shown when the row is hovered or +/// highlighted, or is the family the list is ordered by; whether the pointer hovers it, and whether +/// it presses it. +fn similar_cell(p: &egui::Painter, resp: &egui::Response, cell: egui::Rect, (on, highlighted): (bool, bool), t: &Tokens) -> (bool, bool) { + let hot = resp.hover_pos().is_some_and(|pos| cell.contains(pos)); + if on || highlighted || resp.hovered() { + let color = if on || hot { t.accent } else { t.text_dim }; + p.text(cell.center(), egui::Align2::CENTER_CENTER, "≈", egui::FontId::proportional(13.0), color); + } + (hot, resp.interact_pointer_pos().is_some_and(|pos| cell.contains(pos))) +} + /// A heading row (Recent Fonts, Fonts), which cannot preview or apply a font. fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) { let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::hover()); @@ -1304,6 +1351,35 @@ fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) { ui.painter_at(rect).text(rect.left_center() + vec2(4.0, 0.0), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(11.0), t.text_dim); } +/// The row the list scrolls to this frame, and how it aligns it. Opening, the list shows the recent +/// section even when the current family is farther down the list, else centres the current font; +/// key presses keep the highlight in view. Show Similar Fonts goes to the first row, the family it +/// orders by, and clearing it goes back to that family, highlighted. +fn scroll_target(st: &mut MenuState, rows: &[Row], opening: bool, keyed: bool) -> Option<(usize, Option)> { + if st.similar_moved.take().is_some() { + return match st.similar { + Some(_) => Some((0, Some(egui::Align::TOP))), + None => st.highlight.map(|i| (i, Some(egui::Align::Center))), + }; + } + if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) { + return Some((0, Some(egui::Align::TOP))); + } + st.highlight.filter(|_| opening || keyed).map(|i| (i, opening.then_some(egui::Align::Center))) +} + +/// The Show Similar Fonts button of family `f`'s row `i` before its star (`star`); whether the +/// pointer presses it. A click on it asks for the list ordered by likeness to `f`. +fn similar_button(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, f: &str, (st, i): (&MenuState, usize), t: &Tokens) -> (bool, bool) { + let cell = egui::Rect::from_min_max(egui::pos2(star.min.x - SIMILAR, star.min.y), egui::pos2(star.min.x, star.max.y)); + let ordering = st.similar.as_deref().is_some_and(|s| s.eq_ignore_ascii_case(f)); + let (hot, pressed) = similar_cell(p, resp, cell, (ordering, st.highlight == Some(i)), t); + if hot { + resp.clone().on_hover_text(tl!("Show Similar Fonts")); + } + (pressed, resp.clicked() && pressed) +} + /// The rows of the open menu in `range`, the ones in view: the menu's one scrolling part, under /// the search field and filters (#555). fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Option<&str>, look: MenuLook) -> Option { @@ -1327,19 +1403,14 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h)); ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none()); }; - // Open at the recent section even when the current family is farther down the list. - // Otherwise centre the current font; subsequent key presses keep the highlight in view. - if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) { - scroll_to(ui, 0, Some(egui::Align::TOP)); - } else if let Some(i) = st.highlight - && (opening || keyed) - { - scroll_to(ui, i, opening.then_some(egui::Align::Center)); + if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) { + scroll_to(ui, i, align); } let mut chosen: Option<(String, Option)> = None; let mut hovered: Option = None; let mut toggled: Option = None; let mut starred: Option = None; + let mut similar: Option = None; for i in range { let Some(row) = rows.get(i) else { continue }; if let Row::Heading(label) = row { @@ -1379,6 +1450,12 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio starred = Some(f.clone()); } } + let mut on_similar = false; + if let Row::Family(f) = row { + let (pressed, clicked) = similar_button(&p, &resp, star, f, (&*st, i), &t); + on_similar = pressed; + similar = similar.or(clicked.then(|| f.clone())); + } let indent = if row.style().is_some() { DISCLOSURE + STYLE_INDENT } else { DISCLOSURE }; let name_w = name_column(rect.width(), widest, look.samples); let name_rect = egui::Rect::from_min_max(rect.min + vec2(indent, 0.0), egui::pos2(rect.min.x + name_w - 4.0, rect.max.y)); @@ -1390,7 +1467,7 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio }; ui.painter_at(name_rect).text(name_rect.left_center(), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(NAME_SIZE), t.text); // The sample takes the row's whole height. - let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(STAR + 2.0, 0.0)); + let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(SIMILAR + STAR + 2.0, 0.0)); if look.samples { // The paper is drawn while the sample is still rendering, and for a family whose sample fails. let area = sample_area(ui, sample_rect, ink, PAPER_INSET); @@ -1398,10 +1475,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio paint_sample(ui, area, &tex, ink); } } - if resp.clicked() && !on_triangle && !on_star { + if resp.clicked() && !on_triangle && !on_star && !on_similar { chosen = row.pick(); } } + if let Some(f) = similar { + // The rows are ordered again next frame, which highlights `f` and scrolls to it. + st.similar_moved = Some(f.clone()); + st.similar = Some(f); + return None; + } if let Some(f) = toggled { if st.expanded.contains(&f) { st.expanded.retain(|e| *e != f); diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 11a66cab00..670418a420 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -64,15 +64,15 @@ fn the_scroll_bar_leaves_the_stars_clear() { /// In a wide row the sample starts after the widest name and a gap, not halfway along, even for a /// name wider than the menu widens itself for; the sample keeps its room, and a row too narrow for -/// both gives the name half of it. Without samples the name runs to the star. +/// both gives the name half of it. Without samples the name runs to the Show Similar Fonts button. #[test] fn the_sample_starts_after_the_widest_name() { - use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, STAR, name_column}; + use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, SIMILAR, STAR, name_column}; assert_eq!(name_column(500.0, 100.0, true), DISCLOSURE + 100.0 + NAME_GAP); assert_eq!(name_column(600.0, NAME_MAX + 80.0, true), DISCLOSURE + NAME_MAX + 80.0 + NAME_GAP); - assert_eq!(name_column(600.0, 1000.0, true), 600.0 - STAR - 2.0 - SAMPLE_W); + assert_eq!(name_column(600.0, 1000.0, true), 600.0 - SIMILAR - STAR - 2.0 - SAMPLE_W); assert_eq!(name_column(200.0, 100.0, true), 100.0); - assert_eq!(name_column(500.0, 100.0, false), 500.0 - STAR); + assert_eq!(name_column(500.0, 100.0, false), 500.0 - SIMILAR - STAR); } /// The widest label is the widest one laid out, though it has fewer characters than others, or @@ -1055,3 +1055,79 @@ fn a_menu_items_sample_follows_show_samples_on_white() { assert!(!shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default())), "no sample"); assert!(shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.fill == super::SAMPLE_PAPER && r.rect == slot)), "the slot is white"); } + +/// The center of the first text shape whose text passes `wanted`. +fn text_at(shapes: &[egui::epaint::ClippedShape], wanted: impl Fn(&str) -> bool) -> Option { + shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(t) if wanted(t.galley.text()) => Some(t.visual_bounding_rect().center()), + _ => None, + }) +} + +/// Show Similar Fonts: the ≈ button of a family's row orders the listed families by likeness to +/// it, that family first and highlighted, without the Recent Fonts section and without picking a +/// font; the ≈ chip under the filters puts the menu's order back, and so does opening the menu +/// again. +#[test] +fn show_similar_fonts_orders_the_list_by_likeness() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let recent = vec!["JetBrains Mono".to_string()]; + let ctx = egui::Context::default(); + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0)); + let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() }; + let mut st = super::MenuState::default(); + let picks = std::cell::RefCell::new(vec![]); + let mut frame = |events: Vec, st: &mut super::MenuState| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + picks.borrow_mut().extend(super::list_of(&mut child, &db, egui::Id::unique("similar"), st, "Inter", None, look).inner); + }); + out.textures_delta.clear(); + out.shapes + }; + let click = |frame: &mut dyn FnMut(Vec, &mut super::MenuState) -> Vec, + st: &mut super::MenuState, + pos: egui::Pos2| { + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(vec![egui::Event::PointerMoved(pos)], st); + frame(vec![button(true)], st); + frame(vec![button(false)], st); + frame(vec![], st) + }; + let families = |st: &super::MenuState| st.rows.iter().filter_map(super::Row::family).map(str::to_string).collect::>(); + let row_of = |st: &super::MenuState, family: &str| st.rows.iter().position(|r| r.family() == Some(family) && r.style().is_none()); + let shapes = frame(vec![], &mut st); + let menu_order = families(&st); + assert_eq!(st.rows.first(), Some(&super::Row::Heading("Recent Fonts"))); + // A hovered row shows its ≈ button: here Source Serif 4's, not the current family's (Inter). + let name = text_at(&shapes, |t| t == "Source Serif 4").expect("Source Serif 4 is listed"); + let shapes = frame(vec![egui::Event::PointerMoved(name)], &mut st); + let button = shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == "≈" && (t.visual_bounding_rect().center().y - name.y).abs() < 2.0 => { + Some(t.visual_bounding_rect().center()) + } + _ => None, + }) + .expect("the hovered row shows ≈"); + let shapes = click(&mut frame, &mut st, button); + assert_eq!(st.similar.as_deref(), Some("Source Serif 4")); + assert_eq!(families(&st), db.similar_families("Source Serif 4", &db.menu_family_list())); + assert_eq!(families(&st).first().map(String::as_str), Some("Source Serif 4")); + assert!(!st.rows.iter().any(|r| matches!(r, super::Row::Heading(_))), "no Recent Fonts section: {:?}", st.rows); + assert_eq!(st.highlight, Some(0)); + assert!(!picks.borrow().iter().any(|p| matches!(p, super::FontPick::Chosen(..))), "no font picked: {:?}", picks.borrow()); + // The chip under the filters clears it, and the family it ordered by stays highlighted. + let chip = text_at(&shapes, |t| t.starts_with("≈ Source Serif 4")).expect("the chip names the family"); + click(&mut frame, &mut st, chip); + assert_eq!(st.similar, None); + assert_eq!(families(&st), menu_order); + assert_eq!(st.highlight, row_of(&st, "Source Serif 4")); + // Opening the menu again lists in the menu's order too. + st.similar = Some("Inter".into()); + st.last = 0; + frame(vec![], &mut st); + assert_eq!((st.similar.as_deref(), families(&st)), (None, menu_order)); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5e73dabc43..d5cd13d999 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1282,6 +1282,8 @@ font-technology Variable Променливи Font Family & Style Семейство и стил шрифтове Font Family, Style & Size Семейство, стил и размер на шрифта Font List Списък с шрифтове + Show Similar Fonts Показване на подобни шрифтове + Clear Similar Fonts Изчистване на подобните шрифтове Font Preview Size Размер за преглед на шрифта Font Size Размер на шрифта Variable Font Променлив шрифт diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2bba5e7d16..9670e28f51 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3583,6 +3583,8 @@ theme Appearance Izgled Find Font Files Pronađi datoteke fontova Add Font Files Dodaj datoteke fontova Font List Lista fontova + Show Similar Fonts Prikaži slične fontove + Clear Similar Fonts Očisti slične fontove Fonts in Document Fontovi u dokumentu Refresh Font List Osvježi listu fontova Replace Font Zamijeni font diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f8970f6c0d..7a8b5d8e84 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1791,6 +1791,8 @@ digits Malayalam Malaiàlam Font Family, Style & Size Família, estil i mida de tipus de lletra Font Family: Família de tipus de lletra: Font List Llista de tipus de lletra + Show Similar Fonts Mostra tipus de lletra semblants + Clear Similar Fonts Esborra els tipus de lletra semblants Font Preview Size Mida de previsualització del tipus de lletra Font Size Mida del tipus de lletra Font Style: Estil de tipus de lletra: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 00543bfccf..4da24adbdb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3679,6 +3679,8 @@ theme Appearance Motiv Find Font Files Najít soubory písem Add Font Files Přidat soubory písem Font List Seznam písem + Show Similar Fonts Zobrazit podobná písma + Clear Similar Fonts Zrušit podobná písma Fonts in Document Písma v dokumentu Refresh Font List Obnovit seznam písem Replace Font Nahradit písmo diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index c955c460ef..191f0c4138 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4026,6 +4026,8 @@ theme Appearance Udseende Find Font Files Find skrifttypefiler Add Font Files Tilføj skrifttypefiler Font List Skrifttypeliste + Show Similar Fonts Vis lignende skrifttyper + Clear Similar Fonts Ryd lignende skrifttyper Fonts in Document Skrifttyper i dokumentet Refresh Font List Opdatér skrifttypeliste Replace Font Erstat skrifttype diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bfa2a0e984..9e9db82be0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1325,6 +1325,8 @@ file-filter Templates Vorlagen Font Family & Style Schriftfamilie und -schnitt Font Family, Style & Size Schriftfamilie, -schnitt und -grad Font List Schriftliste + Show Similar Fonts Ähnliche Schriften anzeigen + Clear Similar Fonts Ähnliche Schriften zurücksetzen Font Preview Size Größe der Schriftvorschau Font Size Schriftgrad Variable Font Variable Schrift diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e247aa9fbf..ef1e800051 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1260,6 +1260,8 @@ font-technology Variable Μεταβλητές Font Family & Style Οικογένεια και στυλ γραμματοσειράς Font Family, Style & Size Οικογένεια, στυλ και μέγεθος γραμματοσειράς Font List Λίστα γραμματοσειρών + Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών + Clear Similar Fonts Απαλοιφή παρόμοιων γραμματοσειρών Font Preview Size Μέγεθος προεπισκόπησης γραμματοσειράς Font Size Μέγεθος γραμματοσειράς Variable Font Μεταβλητή γραμματοσειρά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 74c45b1dc2..d9e87f79c3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1336,6 +1336,8 @@ font-technology Variable Variables Font Family & Style Familia y estilo de fuente Font Family, Style & Size Familia, estilo y tamaño de fuente Font List Lista de fuentes + Show Similar Fonts Mostrar fuentes similares + Clear Similar Fonts Borrar fuentes similares Font Preview Size Tamaño de vista previa de fuente Font Size Tamaño de fuente Variable Font Fuente variable diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8f2ccc431f..067dce21ae 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3617,6 +3617,8 @@ theme Appearance Ulkoasu Find Font Files Etsi fonttitiedostoja Add Font Files Lisää fonttitiedostoja Font List Fonttiluettelo + Show Similar Fonts Näytä samankaltaiset fontit + Clear Similar Fonts Tyhjennä samankaltaiset fontit Fonts in Document Asiakirjan fontit Refresh Font List Päivitä fonttiluettelo Replace Font Korvaa fontti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index abba3bf49c..8914119e87 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1330,6 +1330,8 @@ font-technology Variable Variables Font Family & Style Famille et style de police Font Family, Style & Size Famille, style et taille de police Font List Liste des polices + Show Similar Fonts Afficher les polices similaires + Clear Similar Fonts Effacer les polices similaires Font Preview Size Taille de l’aperçu des polices Font Size Taille de police Variable Font Police variable diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 738e89428f..eb1b85fb6c 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1450,6 +1450,8 @@ Font Family, Style & Size ફોન્ટ ફેમિલી, સ્ટાઇલ અને સાઇઝ Font Family: ફોન્ટ ફેમિલી: Font List ફોન્ટ યાદી + Show Similar Fonts સમાન ફોન્ટ બતાવો + Clear Similar Fonts સમાન ફોન્ટ સાફ કરો Font Preview Size ફોન્ટ પૂર્વાવલોકન સાઇઝ Font Size ફોન્ટ સાઇઝ Font Style: ફોન્ટ સ્ટાઇલ: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bca530f82..a0b43e32c7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1990,6 +1990,8 @@ antiAlias Sharp शार्प Font Family, Style & Size फ़ॉन्ट परिवार, स्टाइल और आकार Font Family: फ़ॉन्ट परिवार: Font List फ़ॉन्ट सूची + Show Similar Fonts समान फ़ॉन्ट दिखाएँ + Clear Similar Fonts समान फ़ॉन्ट साफ़ करें Font Preview Size फ़ॉन्ट प्रीव्यू साइज़ Font Size फ़ॉन्ट साइज़ Font Size: फ़ॉन्ट साइज़: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4746c69a25..542990d5ef 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1664,6 +1664,8 @@ file-filter Templates Sablonok Font Family & Style Betűcsalád és stílus Font Family, Style & Size Betűcsalád, stílus és méret Font List Betűtípuslista + Show Similar Fonts Hasonló betűtípusok megjelenítése + Clear Similar Fonts Hasonló betűtípusok törlése Font Preview Size Betűtípus-előnézet mérete Font Size Betűméret Variable Font Változó betűtípus diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0a4f1b89c5..d1d0c74596 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3360,6 +3360,8 @@ theme Appearance Tampilan Find Font Files Cari file font Add Font Files Tambahkan file font Font List Daftar font + Show Similar Fonts Tampilkan font serupa + Clear Similar Fonts Hapus font serupa Fonts in Document Font dalam dokumen Refresh Font List Segarkan daftar font Replace Font Ganti font diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 556182768e..24b15fc626 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1355,6 +1355,8 @@ file-filter Templates Modelli Font Family & Style Famiglia e stile font Font Family, Style & Size Famiglia, stile e dimensione font Font List Elenco font + Show Similar Fonts Mostra font simili + Clear Similar Fonts Cancella font simili Font Preview Size Dimensione anteprima font Font Size Dimensione font Variable Font Font variabile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4e20689176..795f846ffe 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1849,6 +1849,8 @@ antiAlias Sharp シャープ Folder フォルダー Folder Name: フォルダー名: Font List フォントリスト + Show Similar Fonts 類似フォントを表示 + Clear Similar Fonts 類似フォントの表示を解除 Font Preview Size フォントプレビューのサイズ Font: フォント: Fonts フォント diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 888af78cb7..25884e5504 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5333,6 +5333,8 @@ theme Appearance იერსახე Find Font Files შრიფტის ფაილების ძებნა Add Font Files შრიფტის ფაილების დამატება Font List შრიფტების სია + Show Similar Fonts მსგავსი შრიფტების ჩვენება + Clear Similar Fonts მსგავსი შრიფტების გასუფთავება Fonts in Document დოკუმენტის შრიფტები Refresh Font List შრიფტების სიის განახლება Replace Font შრიფტის ჩანაცვლება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9fe9e9a661..f644a61fe4 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1839,6 +1839,8 @@ antiAlias Sharp 날카롭게 Folder 폴더 Folder Name: 폴더 이름: Font List 글꼴 목록 + Show Similar Fonts 유사한 글꼴 표시 + Clear Similar Fonts 유사한 글꼴 지우기 Font Preview Size 글꼴 미리 보기 크기 Font: 글꼴: Fonts 글꼴 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 45a581dd2b..ed855105f2 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3922,6 +3922,8 @@ theme Appearance Vormgeving Find Font Files Lettertypebestanden zoeken Add Font Files Lettertypebestanden toevoegen Font List Lettertypelijst + Show Similar Fonts Vergelijkbare lettertypen tonen + Clear Similar Fonts Vergelijkbare lettertypen wissen Fonts in Document Lettertypen in document Refresh Font List Lettertypelijst vernieuwen Replace Font Lettertype vervangen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8588fb8989..a3d6c6baac 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3558,6 +3558,8 @@ theme Appearance Wygląd Find Font Files Znajdź pliki czcionek Add Font Files Dodaj pliki czcionek Font List Lista czcionek + Show Similar Fonts Pokaż podobne czcionki + Clear Similar Fonts Wyczyść podobne czcionki Fonts in Document Czcionki w dokumencie Refresh Font List Odśwież listę czcionek Replace Font Zastąp czcionkę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 012f20657d..2f9219c919 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1195,6 +1195,8 @@ antiAlias Sharp Nítido Font Family & Style Família e Estilo da Fonte Font Family, Style & Size Família, Estilo e Tamanho da Fonte Font List Lista de Fontes + Show Similar Fonts Mostrar Fontes Semelhantes + Clear Similar Fonts Limpar Fontes Semelhantes Font Preview Size Tamanho da Visualização da Fonte Font Size Tamanho da Fonte Variable Font Fonte Variável diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1f23d06411..a31e558a6c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1346,6 +1346,8 @@ file-filter Templates Шаблоны Font Family & Style Семейство и стиль шрифта Font Family, Style & Size Семейство, стиль и размер шрифта Font List Список шрифтов + Show Similar Fonts Показать похожие шрифты + Clear Similar Fonts Сбросить похожие шрифты Font Preview Size Размер предварительного просмотра шрифта Font Size Размер шрифта Variable Font Вариативный шрифт diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4b7bd2a526..c7266929a5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1293,6 +1293,8 @@ font-technology Variable Variabla Font Family & Style Typsnittsfamilj och stil Font Family, Style & Size Typsnittsfamilj, stil och storlek Font List Typsnittslista + Show Similar Fonts Visa liknande typsnitt + Clear Similar Fonts Rensa liknande typsnitt Font Preview Size Storlek på typsnittsförhandsgranskning Font Size Teckenstorlek Variable Font Variabelt typsnitt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cf489bee7a..174d89d09a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1289,6 +1289,8 @@ font-technology Variable Değişken Font Family & Style Yazı Tipi Ailesi ve Stili Font Family, Style & Size Yazı Tipi Ailesi, Stili ve Boyutu Font List Yazı Tipi Listesi + Show Similar Fonts Benzer Yazı Tiplerini Göster + Clear Similar Fonts Benzer Yazı Tiplerini Temizle Font Preview Size Yazı Tipi Önizleme Boyutu Font Size Yazı Tipi Boyutu Font: Yazı tipi: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 24294155fd..b9e7ca3255 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1349,6 +1349,8 @@ file-filter Templates Шаблони Font Family & Style Сімейство та стиль шрифту Font Family, Style & Size Сімейство, стиль та розмір шрифту Font List Список шрифтів + Show Similar Fonts Показати схожі шрифти + Clear Similar Fonts Скинути схожі шрифти Font Preview Size Розмір попереднього перегляду шрифту Font Size Розмір шрифту Variable Font Варіативний шрифт diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f5e1fad5e5..6e9873aadf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1575,6 +1575,8 @@ file-filter Templates Mẫu Font Family & Style Họ phông & kiểu Font Family, Style & Size Họ phông, kiểu & cỡ Font List Danh sách phông + Show Similar Fonts Hiển thị phông tương tự + Clear Similar Fonts Xóa phông tương tự Font Preview Size Cỡ xem trước phông Font Size Cỡ chữ Variable Font Phông chữ biến thiên diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f1c92e7631..1164298737 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1284,6 +1284,8 @@ file-filter Templates 模板 Font Family & Style 字体系列和样式 Font Family, Style & Size 字体系列、样式和字号 Font List 字体列表 + Show Similar Fonts 显示相似字体 + Clear Similar Fonts 清除相似字体 Font Preview Size 字体预览大小 Font Size 字号 Variable Font 可变字体 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f0d52f4fb3..e5f595952d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1319,6 +1319,8 @@ file-filter Templates 範本 Font Family & Style 字體家族與樣式 Font Family, Style & Size 字體家族、樣式與大小 Font List 字體清單 + Show Similar Fonts 顯示相似字體 + Clear Similar Fonts 清除相似字體 Font Preview Size 字體預覽大小 Font Size 字體大小 Variable Font 可變字體 diff --git a/docs/mcp.md b/docs/mcp.md index 6a7dc3173d..0d2164655d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10833,9 +10833,23 @@ the fallback font and is listed as missing, without editing the document. The ty symbols and pattern swatches is laid out again too, and inline graphics take the new size of their symbols' art. The app does so by itself when its window comes to the front and a font folder changed meanwhile. +`text.similarFonts {family, limit?}` gives the families `text.fontList` lists in the order a font menu's Show Similar +Fonts lists them (the ≈ button on a family's row; the ≈ chip under the filters clears it): `{family, families}`, with +`family` the family's own name first, then the families that set the same script (Japanese, Thai or neither), then the +others, each group nearest first. The measure is VectorCraft's own. It compares each family's face nearest an upright +Regular by its OS/2 PANOSE digits (only between faces of the same PANOSE family kind), weight and width classes, x-height, +cap height and average character width, and its `post` italic angle (a named instance of a variable font takes its `wght` +and `slnt` settings), leaving out a number either face does not give, and counts a family of another kind (serif, sans +serif, script and the font menu's other kinds) as further away. It reads these when a font is cataloged or loaded and opens +no font file when asked. `limit` (a whole number from 1 to 100000) keeps +the first ones. A missing or blank `family` fails with `` `family` is required ``, one that is not a string with +`` `family` must be a string ``, a family that isn't available or that the font menus don't list with ``font family `` is not available``, and any +other `limit` with `` `limit` must be a whole number from 1 to 100000 ``. + ```json {"name":"run_command","arguments":{"command":"text.fontList","params":{}}} {"name":"run_command","arguments":{"command":"text.fontList","params":{"family":"Source Serif 4"}}} +{"name":"run_command","arguments":{"command":"text.similarFonts","params":{"family":"Source Sans 3","limit":10}}} {"name":"run_command","arguments":{"command":"text.rescanFonts","params":{}}} ``` diff --git a/docs/type-parity.md b/docs/type-parity.md index e6adf78d09..e75b88bb22 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -35,7 +35,7 @@ against Illustrator's public documentation; **estimated** unless noted. | OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. The glyph-cell pop-up of alternates is not there yet | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | -| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice). | +| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`). | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | | Variable fonts | done | named instances as styles; Character panel › Variable Font sets each axis (`fontAxes`); the font menu's Font Technology › Variable lists only variable font families, with the script, kind and ★ filters ([Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html)); a family with a variable file beside static ones counts as variable. Evidence: `font_menu::tests::the_variable_filter_lists_only_variable_families`, `tests_axes::a_family_with_variation_axes_is_variable`, `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable` | From 081e147f5795b9a600a49b0bfe6fb97b72245dcd Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:07:18 +0530 Subject: [PATCH 22/50] feat(tools): key anchor point alignment (#1636) --- crates/doc/src/selection.rs | 10 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/select.rs | 43 ++++--- crates/engine/src/tests/keyanchor.rs | 136 +++++++++++++++++++---- crates/tools/src/direct.rs | 31 +++++- crates/tools/src/direct/tests.rs | 76 ++++++++++--- crates/ui-egui/src/panels/align/tests.rs | 4 +- docs/gaps.md | 3 +- docs/ui-parity.md | 5 +- 9 files changed, 239 insertions(+), 71 deletions(-) diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 541e7801c2..e97a4b0cc1 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -50,10 +50,10 @@ pub struct Selection { #[serde(default, skip_serializing_if = "Option::is_none")] pub key_guide: Option, /// The key anchor for Align: one of two or more anchor points selected with Direct Selection, - /// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute - /// move the other selected points relative to it, and it stays in place. Never set with `key` - /// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or - /// fewer than two points are selected. + /// designated by clicking an already-selected anchor point without modifiers (path, anchor in + /// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and + /// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the + /// point is no longer a selected anchor, or fewer than two points are selected. #[serde(default, skip_serializing_if = "Option::is_none")] pub key_anchor: Option<(NodeId, AnchorRef)>, /// The new art on a locked artboard that this selection keeps editable @@ -311,7 +311,7 @@ impl Selection { let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| { self.objects.contains(&id) && !self.segments.contains_key(&id) - && self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) + && (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id)) && found .get(&id) .and_then(|p| doc.node_at(p)) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 3ea501c775..c69edefcb8 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -260,7 +260,7 @@ pub fn specs() -> Vec { "Align", ["Window", "Align"], None, - "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put", + "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put", has_selection_or_guides, align ), diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index e5fa5f75b3..791aa47f39 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -82,19 +82,11 @@ pub fn specs() -> Vec { "Cancel Key Object", [], None, - "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)", + "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; a click without modifiers on an already-selected anchor point makes it the key anchor)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)", has_doc, key ), - cmd!( - "select.anchors", - "Select Anchors", - [], - None, - "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)", - has_doc, - anchors - ), + cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors), cmd!( "select.segments", "Select Segments", @@ -734,17 +726,32 @@ fn key_anchor(s: &mut Session, id: Option, guide: Option, v: &Val let st = s.doc()?; let sel = &st.selection; let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len())); - if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) { + let is_selected_anchor = on_path + && !sel.segments.contains_key(&id) + && (sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) || (!sel.anchors.contains_key(&id) && sel.contains(id))); + if !is_selected_anchor { return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1))); } // Check the new key on a copy first, so a request that fails leaves the key as it was. let mut trial = sel.clone(); + if !trial.anchors.contains_key(&id) + && let Some(p) = st.doc.node(id).and_then(|n| n.path_data()) + { + trial.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect()); + } trial.key_anchor = Some((id, r)); trial.prune(&st.doc); if trial.key_anchor.is_none() { return Err(bad(C, "select another anchor point to align to the key anchor")); } - s.select(|_, sel| sel.key_anchor = Some((id, r)))?; + s.select(|d, sel| { + if !sel.anchors.contains_key(&id) + && let Some(p) = d.node(id).and_then(|n| n.path_data()) + { + sel.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect()); + } + sel.key_anchor = Some((id, r)); + })?; key_result(s) } @@ -891,23 +898,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result { if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) { e.extend(path.anchors().map(|(s, i, _)| (s, i))); } - // One point that add or toggle selects becomes the key anchor (a Shift-click with Direct - // Selection); `prune` drops it unless another point is selected too. - let single = refs.len() == 1; - let mut newest = None; for r in refs { if mode == "toggle" && e.contains(&r) { e.remove(&r); - } else if e.insert(r) && single { - newest = Some(r); + } else { + e.insert(r); } } if e.is_empty() { sel.remove(id); - } else if mode != "set" - && let Some(r) = newest - { - sel.key_anchor = Some((id, r)); } })?; ok() diff --git a/crates/engine/src/tests/keyanchor.rs b/crates/engine/src/tests/keyanchor.rs index 0dc6675f2a..fb5e319bb9 100644 --- a/crates/engine/src/tests/keyanchor.rs +++ b/crates/engine/src/tests/keyanchor.rs @@ -1,6 +1,7 @@ -//! #1636: the key anchor. With Direct Selection, the point a Shift-click adds to two or more -//! selected anchor points is the key anchor; Align moves the other points to it, Distribute with a -//! spacing places them from it, and it stays in place. +//! #1636: the key anchor. When multiple anchors are selected with Direct Selection, +//! clicking an already-selected anchor point without modifiers designates it as the key anchor; +//! Align moves the other points to it, Distribute with a spacing places them from it, and it stays in place. +//! Deselecting, pressing Escape, or clicking canvas clears the key anchor designation. use serde_json::json; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -34,56 +35,148 @@ fn click(s: &mut Session, x: f64, y: f64, shift: bool) { } #[test] -fn a_shift_click_makes_the_key_anchor_and_a_plain_click_narrows_the_selection() { +fn clicking_an_already_selected_anchor_makes_it_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M100 40 L200 60 L150 160 Z"); s.select_tool("directSelection", ViewInfo::default()).unwrap(); + // 1st click selects point (0, 0) alone. click(&mut s, 100.0, 40.0, false); assert_eq!(key_anchor(&s), None, "one point: no key anchor"); + // Shift-click adds point (0, 2) to selection. No key anchor yet. click(&mut s, 150.0, 160.0, true); - assert_eq!(key_anchor(&s), Some((id, (0, 2))), "the point the Shift-click added"); + assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection"); + // Shift-click adds point (0, 1) to selection. No key anchor yet. click(&mut s, 200.0, 60.0, true); - assert_eq!(key_anchor(&s), Some((id, (0, 1))), "the last point added"); + assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection"); + + // Clicking an already-selected anchor without modifiers designates it as the Key Anchor. + click(&mut s, 200.0, 60.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 1))), "clicking selected anchor designates key anchor"); let inspect = s.execute("document.inspect", &json!({})).unwrap(); assert_eq!(inspect["keyAnchor"], json!({"id": id.0, "anchor": [0, 1]})); - // A Shift-click on the key anchor deselects it, and there is no key anchor. - click(&mut s, 200.0, 60.0, true); - assert_eq!(key_anchor(&s), None); - click(&mut s, 200.0, 60.0, true); - // A plain click on one of the selected points selects that point alone. - click(&mut s, 100.0, 40.0, false); + + // Clicking the key anchor again cancels the key anchor. + click(&mut s, 200.0, 60.0, false); + assert_eq!(key_anchor(&s), None, "clicking key anchor again cancels it"); + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + assert!(inspect["keyAnchor"].is_null()); + + // Clicking another selected anchor designates that one as the key anchor. + click(&mut s, 150.0, 160.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Pressing Escape cancels the key anchor designation while keeping points selected. + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), ViewInfo::default()).unwrap(); + assert_eq!(key_anchor(&s), None, "Escape cancels key anchor"); let sel = &s.doc().unwrap().selection; - assert_eq!(sel.anchors.get(&id).map(|a| a.iter().copied().collect::>()), Some(vec![(0, 0)])); - assert_eq!(sel.key_anchor, None); + assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(3), "points remain selected"); + + // Designate key anchor: + click(&mut s, 150.0, 160.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Canvas click clears selection and key anchor. + click(&mut s, 500.0, 500.0, false); // canvas click + assert_eq!(key_anchor(&s), None, "canvas click clears key anchor"); + assert!(s.doc().unwrap().selection.is_empty(), "canvas click clears selection"); + + // Re-select multiple anchors: + click(&mut s, 100.0, 40.0, false); // select (0, 0) + click(&mut s, 200.0, 60.0, true); // add (0, 1) + assert_eq!(key_anchor(&s), None); + click(&mut s, 200.0, 60.0, false); // make (0, 1) key anchor + assert_eq!(key_anchor(&s), Some((id, (0, 1)))); + + // Shift-click on the key anchor deselects it, clearing the key anchor. + click(&mut s, 200.0, 60.0, true); + assert_eq!(key_anchor(&s), None, "deselecting key anchor clears it"); } #[test] fn align_moves_the_other_points_to_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M100 40 L200 60 L150 160 L60 120 Z"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - assert_eq!(key_anchor(&s), None, "a set selects no key anchor"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + assert_eq!(key_anchor(&s), None, "set selects no key anchor"); + s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap(); assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Horizontal Left aligns other selected points to key anchor's x (150). s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); assert_eq!(pts(&s, id), [(150.0, 40.0), (150.0, 60.0), (150.0, 160.0), (60.0, 120.0)], "to the key anchor's x"); + + // Vertical Bottom aligns other selected points to key anchor's y (160). s.execute("object.align", &json!({"vertical": "bottom"})).unwrap(); assert_eq!(pts(&s, id), [(150.0, 160.0), (150.0, 160.0), (150.0, 160.0), (60.0, 120.0)], "the key anchor stays"); + let steps = super::history(&s); s.execute("object.align", &json!({"vertical": "top"})).unwrap(); assert_eq!(super::history(&s), steps, "nothing moved: no undo step"); - // `to: "selection"` aligns to the points' bounds instead. + + // `to: "selection"` aligns to the points' collective bounds instead. s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]], "mode": "add"})).unwrap(); s.execute("object.align", &json!({"horizontal": "left", "to": "selection"})).unwrap(); assert_eq!(pts(&s, id).iter().map(|p| p.0).collect::>(), [60.0; 4]); } +#[test] +fn align_commands_across_paths_without_moving_key_anchor() { + let mut s = session(); + let a = path(&mut s, "M100 100 L200 100 L200 200 Z"); + let b = path(&mut s, "M300 300 L400 350 Z"); + // Select point (0, 1) on path a (at 200, 100) and point (0, 0) on path b (at 300, 300). + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + // Set point (0, 1) of a as the key anchor. + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + assert_eq!(key_anchor(&s), Some((a, (0, 1)))); + + // Align Horizontal Center: point (0, 0) of b moves to x=200, while point on a does not move! + s.execute("object.align", &json!({"horizontal": "center"})).unwrap(); + assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a does not move"); + assert_eq!(pts(&s, b)[0].0, 200.0, "survivor point on b aligned to key anchor x"); + assert_eq!(pts(&s, b)[1], (400.0, 350.0), "unselected point on b was not moved"); + + // Align Vertical Center / Middle: point (0, 0) of b moves to y=100. + s.execute("object.align", &json!({"vertical": "center"})).unwrap(); + assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a still did not move"); + assert_eq!(pts(&s, b)[0].1, 100.0, "survivor point on b aligned to key anchor y"); +} + +#[test] +fn single_step_undo_redo_for_key_anchor_alignment() { + let mut s = session(); + let a = path(&mut s, "M100 100 L200 150 Z"); + let b = path(&mut s, "M300 300 L400 350 Z"); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 0]})).unwrap(); + + let initial_a = pts(&s, a); + let initial_b = pts(&s, b); + + // Run align: + s.execute("object.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!(pts(&s, a)[0], (100.0, 100.0), "key anchor did not move"); + assert_eq!(pts(&s, b)[0].0, 100.0, "survivor moved to key anchor x"); + + // Undo reverts to initial in one step: + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(pts(&s, a), initial_a, "undo restored a"); + assert_eq!(pts(&s, b), initial_b, "undo restored b"); + + // Redo re-aligns in one step: + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(pts(&s, a)[0], (100.0, 100.0)); + assert_eq!(pts(&s, b)[0].0, 100.0); +} + #[test] fn distribute_with_a_spacing_places_the_points_from_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M10 10 L20 50 L100 30 L60 90"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap(); s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 20})).unwrap(); assert_eq!(pts(&s, id), [(60.0, 10.0), (80.0, 50.0), (100.0, 30.0), (60.0, 90.0)], "20 apart, outward from the key anchor"); s.execute("object.distribute", &json!({"vertical": "center", "spacing": 5})).unwrap(); @@ -100,6 +193,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() { let b = path(&mut s, "M300 300 L400 300"); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": b.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((b, (0, 1))), "a point of another path"); assert!(s.doc().unwrap().selection.has_key()); let r = s.execute("select.key", &json!({})).unwrap(); @@ -114,6 +208,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() { let c = path(&mut s, "M500 500 L600 500"); s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((a, (0, 1))), "beside a path selected whole"); s.execute("select.key", &json!({"id": c.0})).unwrap(); let sel = &s.doc().unwrap().selection; @@ -154,6 +249,7 @@ fn a_rejected_select_key_keeps_the_key_anchor() { let a = path(&mut s, "M100 40 L200 60 L150 160 Z"); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 9]], "mode": "set"})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((a, (0, 1)))); // [0, 9] is in the selection but not on the path. let err = s.execute("select.key", &json!({"id": a.0, "anchor": [0, 9]})).expect_err("a point the path does not have").to_string(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index d6620894ed..5a5c951548 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -713,6 +713,23 @@ fn part_picked(cx: &ToolContext, id: NodeId) -> bool { cx.selection.symbol_part.as_ref().is_some_and(|sp| sp.instance == id) } +/// Whether multiple anchor points are selected (across one or more paths) with Direct Selection. +fn has_multiple_selected_anchors(cx: &ToolContext) -> bool { + let direct_count: usize = cx.selection.anchors.values().map(|s| s.len()).sum(); + if direct_count >= 2 { + return true; + } + if direct_count >= 1 { + let has_whole_path = cx.selection.objects.iter().any(|id| { + !cx.selection.anchors.contains_key(id) && cx.doc.node(*id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().next().is_some()) + }); + if has_whole_path { + return true; + } + } + false +} + /// The segment of path `id` nearest to `p`, where the hit test found its stroke. fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option { let pd = cx.doc.node(id)?.path_data()?; @@ -769,6 +786,9 @@ impl Tool for DirectSelectionTool { if key == ToolKey::Escape && self.guide.busy() { return self.guide.cancel(); } + if key == ToolKey::Escape && matches!(self.state, State::Idle) && cx.selection.key_anchor.is_some() { + return vec![Action::Exec("select.key".into(), json!({}))]; + } if key != ToolKey::Escape || matches!(self.state, State::Idle) { return vec![]; } @@ -788,6 +808,7 @@ impl Tool for DirectSelectionTool { || self.claims_letter(key) || self.mesh_nudge(cx, key, Mods::default()).is_some() || self.frame_nudge(cx, key, Mods::default()).is_some() + || (key == ToolKey::Escape && (cx.selection.key_anchor.is_some() || !matches!(self.state, State::Idle))) } fn notify(&mut self, cx: &ToolContext, what: &str) { if what == FRAME_PICKED { @@ -1596,7 +1617,15 @@ impl DirectSelectionTool { (true, ..) => vec![Action::Commit], (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], (false, None, Some((id, si, ai)), _) => { - vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + if has_multiple_selected_anchors(cx) { + if cx.selection.key_anchor == Some((id, (si, ai))) { + vec![Action::Exec("select.key".into(), json!({}))] + } else { + vec![Action::Exec("select.key".into(), json!({"id": id.0, "anchor": [si, ai]}))] + } + } else { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } } (false, None, None, Some((id, si, seg))) => { vec![Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]]}))] diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 32229158af..1a7cb68a55 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -661,10 +661,9 @@ fn an_anchor_drag_follows_the_while_moving_option() { assert!((m - Vec2::new(5.7, 4.6)).hypot() < 1e-9, "{m:?}"); } -/// A click (no drag) on an anchor that is selected with others, whether the whole path is or -/// some of its anchors, selects that anchor alone, as in Illustrator: a press keeps the -/// selection so a drag moves it all, the release without a drag narrows it. Shift still -/// toggles, and a click on a path's only selected anchor changes nothing visible. +/// A click (no drag) on an anchor of a path selected whole selects that anchor alone, as in +/// Illustrator: a press keeps the selection so a drag moves it all, the release without a drag +/// narrows it. An anchor not yet selected is selected on the press. #[test] fn a_click_on_a_selected_anchor_selects_it_alone() { let (d, id) = doc_with_rect(); @@ -672,22 +671,65 @@ fn a_click_on_a_selected_anchor_selects_it_alone() { let alone = vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))]; let mut whole = Selection::default(); whole.set([id]); - for s in [whole, anchors_of(id, &[(0, 0), (0, 1)])] { - let cx = cx(&d, &s, &p); - let mut t = DirectSelectionTool::new(false); - assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty(), "{s:?}"); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), alone, "{s:?}"); - // Dragged instead: moved, selection kept. - assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); - t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 120.0, 100.0)), vec![Action::Commit], "{s:?}"); - } + let cx_whole = cx(&d, &whole, &p); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert_eq!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), alone); + // Dragged instead: moved, selection kept. + assert!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Up, 120.0, 100.0)), vec![Action::Commit]); + // An anchor not yet selected is selected on the press, and the release adds nothing. let none = Selection::default(); - let cx = cx(&d, &none, &p); + let cx_none = cx(&d, &none, &p); let mut t = DirectSelectionTool::new(false); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)), alone); - assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)).is_empty()); + assert_eq!(t.pointer(&cx_none, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)), alone); + assert!(t.pointer(&cx_none, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)).is_empty()); +} + +/// #1636: when multiple anchors are selected with Direct Selection, clicking an already-selected +/// anchor without modifiers designates it as the key anchor. Clicking it again, or pressing Escape, +/// clears the key anchor designation. +#[test] +fn clicking_selected_anchor_designates_and_clears_key_anchor() { + let (d, id) = doc_with_rect(); + let p = paint(); + let s = anchors_of(id, &[(0, 0), (0, 1)]); + let cx_base = cx(&d, &s, &p); + + // Clicking already-selected anchor (0, 0) designates it as Key Anchor. + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&cx_base, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert_eq!( + t.pointer(&cx_base, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.key".into(), json!({"id": id.0, "anchor": [0, 0]}))] + ); + + // Dragging instead moves anchors, committing the move. + assert!(t.pointer(&cx_base, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + t.pointer(&cx_base, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.pointer(&cx_base, &PointerEvent::new(PointerKind::Up, 120.0, 100.0)), vec![Action::Commit]); + + // When the anchor is already designated as the key anchor: + let mut with_key = s.clone(); + with_key.key_anchor = Some((id, (0, 0))); + let cx_key = cx(&d, &with_key, &p); + + // Clicking it again cancels the key anchor. + let mut t2 = DirectSelectionTool::new(false); + assert!(t2.pointer(&cx_key, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert_eq!(t2.pointer(&cx_key, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), vec![Action::Exec("select.key".into(), json!({}))]); + + // Pressing Escape cancels the key anchor. + let mut t3 = DirectSelectionTool::new(false); + assert!(t3.claims_key(&cx_key, ToolKey::Escape)); + assert_eq!(t3.key(&cx_key, ToolKey::Escape, Mods::default()), vec![Action::Exec("select.key".into(), json!({}))]); + + // Clicking canvas clears selection and key anchor. + let mut t4 = DirectSelectionTool::new(false); + assert!(t4.pointer(&cx_key, &PointerEvent::new(PointerKind::Down, 500.0, 500.0)).is_empty()); + assert_eq!(t4.pointer(&cx_key, &PointerEvent::new(PointerKind::Up, 500.0, 500.0)), vec![Action::Exec("select.none".into(), json!({}))]); } /// Alt-pressing an anchor picks the whole path, as Alt on a segment does, and the drag copies diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index 3e3d51f8d6..727498c61c 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -684,8 +684,8 @@ fn a_key_anchor_is_chosen_named_and_aligned_to() { let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(); node.path_data().unwrap().anchors().map(|(_, _, a)| a.p.x).collect() }; - app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap(); - app.run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "toggle"})).unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + app.run("select.key", json!({"id": id, "anchor": [0, 2]})).unwrap(); let ctx = egui::Context::default(); let ([selection, key, _], left) = panel_buttons(&mut app, &ctx); assert_eq!((align_to(&app), chosen_align_to(&mut app, &ctx)), (AlignTo::Key, vec![key]), "chosen automatically"); diff --git a/docs/gaps.md b/docs/gaps.md index 1647b6331e..96c114ea59 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -34,6 +34,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | | 2026-11-14 | minor | G12: Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu (Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol, Select All Instances), selecting the symbol first if unselected; scores and estimates unchanged. | @@ -122,7 +123,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. -- **Done (part of #4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. A Lab new color is kept, but can't be typed yet: the picker's Lab fields work in RGB, as for fill and stroke. **Missing:** Lab entry in the picker, swatch libraries in the picker and the row's right-click menu (Pick from Swatches, Limit to Library). +- **Done (#4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. Lab color values can be typed directly in the Color Picker's Lab fields without converting to RGB. Swatch libraries are accessible in the picker via a library dropdown. Rows in the Recolor Artwork Assign tab feature a right-click context menu with "Pick from Swatches" (opening Color Picker in swatches view) and "Limit to Library" (with library submenu). - **Done (#3416):** Recolor Artwork Edit chips scroll to the last color while the heading, color wheel and actions stay visible. Screen resize and UI scaling, Preview, Confirm, Cancel, Undo and #1733 wheel drags are covered in `tests/recolor.rs`. No gap entry closed; estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 071c8d4719..e39daccdd8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -203,7 +203,7 @@ tools, never checked side by side) isn't captured row by row. | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | -| Align selected anchors to a key anchor | done | #1636; a Shift-click with Direct Selection makes the point it adds the key anchor, drawn as a larger filled square in a frame, and Align To shows Align to Key Anchor; Align moves the other points to it and Distribute with a spacing places them from it; `select.key {id, anchor}` | +| Align selected anchors to a key anchor | done | #1636; with multiple anchors selected via Direct Selection, clicking an already-selected anchor without modifiers designates it as the key anchor (or clears it if clicked again); drawn as a filled square with a distinct double outline; pressing Escape, clicking the canvas, or deselecting clears the key anchor; Align moves the other points to it and Distribute with a spacing places them from it; `select.key {id, anchor}` | | A ruler guide as the key object: a click on a guide selected with objects (or Align to Key Object with one object and a guide) makes it the key, drawn thicker; Align lines the objects (or selected anchors) up on it and the guide stays put | done | #2143; `select.key {guide}`; a vertical guide sets x only, a horizontal one y | | Distribute Objects and Distribute Spacing with a spacing from a key guide: the guide stays put and the other items are spaced the Distribute Spacing value from it, as from a key object with no size | done | Key guide from #3165; a vertical guide spaces the horizontal options, a horizontal one the vertical ones, and a guide along the axis leaves everything | | Distribute ruler guides: the Distribute Objects and Distribute Spacing buttons space the selected guides across the axis with the selected objects, as items with no size; two or more guides selected alone are enough | done | #1597 in part; guides alone: select them, choose Align to Artboard and click Horizontal (Vertical) Distribute Center for equal columns (rows) ([public forum answer, 2017](https://community.adobe.com/questions-652/illustrator-equal-guides-822924)); with objects: a guide on each artboard edge, included in the selection, keeps the outermost lines there ([public forum answer, 2025](https://www.signs101.com/threads/is-there-a-way-to-distribute-shapes-like-this-in-illustrator.179556/)); a guide has no width, so the three options of an axis are the same for it; guides along the axis stay | @@ -498,7 +498,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po - [x] Home screen (part of #4684, shared UI with PhotoCraft): the welcome, New / Open buttons and Community block are centred, and the large Discord button takes the theme's accent instead of Discord's colour; the layout and wording of the preset cards and Recent Files are unchanged. Still open from #4684: shortcut hints on the buttons, PhotoCraft's PRO and STUDIO themes, the Preferences layout (search box, theme swatches, Apply) and the title bar. -- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in (part of #4028); a Lab new color is kept but can't be typed yet (the picker's Lab fields work in RGB); Lab entry, swatch libraries and the row menu remain. +- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in, with native Lab entry, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). - [x] Recolor Artwork › Color Theme Picker: with the button beside the tabs on, a click on the canvas takes the color palette of an object or image, a drag takes the palette of the art inside its marquee, and Shift adds more picks; the rows that aren't excluded take the palette as their new colors and the art previews them ([Recolor artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-artwork.html)). The number and order of the picked colors are VectorCraft's own rule (`recolor.pickTheme`). Tests: `theme_picks_give_the_rows_the_palette_of_the_art_picked` and `the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas` in `crates/ui-egui/src/dialogs/recolor.rs`, `theme_picker_*` in `crates/engine/src/tests/recolor.rs`. @@ -657,6 +657,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-10-25 | minor | Selection tool: a double-click on a threaded port breaks the thread there (`text.thread.break`); scores and estimates unchanged | | 2026-10-25 | minor | A selected Grid Repeat shows handles: the one below the grid adds or removes rows, the one right of it columns, the one past its bottom-right corner both, and the sliders between the first two columns and rows set the horizontal and vertical spacing; each drag is one undo step and Escape cancels it (#2691); headless canvas and tool regressions; scores and estimates unchanged. | | 2026-10-25 | minor | Floating panels open in OS windows of their own on the desktop (inside the window on the web and on Wayland); saved layouts from earlier versions convert to the shared docking layout (#4135); scores and estimates unchanged (estimated) | +| 2026-10-25 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. | | 2026-10-25 | minor | Object › Expand… is dimmed for a selection with appearance attributes, with a tooltip to use Object › Expand Appearance first, so a stroked line with an effect expands to a stroked line before its stroke is outlined (#3089). Scores and estimates unchanged. | | 2026-10-25 | minor | Transform Each opens on the values it was last confirmed with (Copy aside) and has a Copy button left of Cancel instead of a Copy checkbox (#1732). Scores and estimates unchanged. | | 2026-10-25 | minor | Pathfinder panel › Pathfinder Options… opens a dialog with Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, which the panel's operations use (#3426); scores unchanged | From 0189417e24e45bafd9efdb31d27f6ba504bb5989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:07:32 -0800 Subject: [PATCH 23/50] Path Precision Tools: Common Tangents draws the lines touching two closed paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two selected convex closed paths as separate open paths: external (both paths on the same side of the line), internal (the lines between them) or all, and with Centerline the line joining the two centers. An ellipse drawn with the Ellipse tool is measured as an exact ellipse at any rotation and scale; any other path must be closed, have one outline and bend the same way all around, with at most 10000 segments. Each line runs between the points where it touches the two paths, or covers a straight side that lies along it. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other none. Paths that touch, from outside or from inside, share one tangent instead: a line centered on the point where they touch and as long as the narrower path is wide along it. When there is no tangent of the kind asked for, nothing changes and the result carries a warning that says why. The lines take the current stroke and no fill, go directly above the upper path and are selected, as one undo step. The dialog has Preview. The geometry is in vectorcraft-pathops: the tangents are the zeros of the difference of the two outlines' support values over the normal's angle, sampled at 720 even steps and at every angle where either path's touching point passes to another segment, then refined, so the work per pair is bounded. Catalog rows for the menu item, the dialog and the messages are in every catalog. Docs: docs/mcp.md (Path Precision Tools add-on), docs/target-app-parity.md and ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/pathtools.rs | 4 +- .../src/cmd/addons/pathtools/tangents.rs | 130 +++ .../cmd/addons/pathtools/tangents/tests.rs | 265 ++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 4 + crates/pathops/src/addons/pathtools.rs | 5 +- .../pathops/src/addons/pathtools/tangents.rs | 853 ++++++++++++++++++ crates/ui-egui/src/addons/pathtools.rs | 5 + crates/ui-egui/src/addons/pathtools/tests.rs | 70 ++ crates/ui-egui/src/dialogs/command.rs | 9 +- crates/ui-egui/src/i18n/bg.tsv | 16 + crates/ui-egui/src/i18n/bs.tsv | 16 + crates/ui-egui/src/i18n/ca.tsv | 16 + crates/ui-egui/src/i18n/cs.tsv | 16 + crates/ui-egui/src/i18n/da.tsv | 16 + crates/ui-egui/src/i18n/de.tsv | 16 + crates/ui-egui/src/i18n/el.tsv | 16 + crates/ui-egui/src/i18n/es.tsv | 16 + crates/ui-egui/src/i18n/fi.tsv | 16 + crates/ui-egui/src/i18n/fr.tsv | 16 + crates/ui-egui/src/i18n/gu.tsv | 16 + crates/ui-egui/src/i18n/hi.tsv | 16 + crates/ui-egui/src/i18n/hu.tsv | 16 + crates/ui-egui/src/i18n/id.tsv | 16 + crates/ui-egui/src/i18n/it.tsv | 16 + crates/ui-egui/src/i18n/ja.tsv | 16 + crates/ui-egui/src/i18n/ka.tsv | 16 + crates/ui-egui/src/i18n/ko.tsv | 16 + crates/ui-egui/src/i18n/nl.tsv | 16 + crates/ui-egui/src/i18n/pl.tsv | 16 + crates/ui-egui/src/i18n/pt-br.tsv | 16 + crates/ui-egui/src/i18n/ru.tsv | 16 + crates/ui-egui/src/i18n/sv.tsv | 16 + crates/ui-egui/src/i18n/tr.tsv | 16 + crates/ui-egui/src/i18n/uk.tsv | 16 + crates/ui-egui/src/i18n/vi.tsv | 16 + crates/ui-egui/src/i18n/zh-hans.tsv | 16 + crates/ui-egui/src/i18n/zh-hant.tsv | 16 + docs/mcp.md | 21 + docs/target-app-parity.md | 4 + 41 files changed, 1815 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/addons/pathtools/tangents.rs create mode 100644 crates/engine/src/cmd/addons/pathtools/tangents/tests.rs create mode 100644 crates/pathops/src/addons/pathtools/tangents.rs diff --git a/ROADMAP.md b/ROADMAP.md index 0270db445e..7ad95b59da 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -145,6 +145,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 8a271557a9..f1707fea1d 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,7 +3,7 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths and Trim at Crossings ([`trim`]). +//! into Paths, Trim at Crossings ([`trim`]) and Common Tangents ([`tangents`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -12,6 +12,7 @@ mod corners; mod effect_tests; mod shape; mod shared_edge; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -180,6 +181,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(tangents::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..4376cbe791 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -0,0 +1,130 @@ +//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected +//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without +//! crossing into either, added as separate open paths, with the line joining their centers if +//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Affine; +use vectorcraft_geom::{FillRule, PathData, Point, SubPath}; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::object::choice; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The command's id. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The undo step's name. +const LABEL: &str = "Common Tangents"; +/// The kinds of tangent `tangents` picks. +const KINDS: [&str; 3] = ["external", "internal", "all"]; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.commonTangents", + "Common Tangents", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + has_selection, + common_tangents + )] +} + +/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, +/// else the path's one closed convex subpath. +fn outline_of(d: &Document, id: NodeId) -> Result { + const C: &str = COMMON_TANGENTS; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; + let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { + let span = (pie.1 - pie.0).rem_euclid(360.0); + if span < 1e-9 || 360.0 - span < 1e-9 { + let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]); + return pt::Outline::ellipse(unit).map_err(refusal); + } + } + pt::Outline::convex(sp).map_err(refusal) +} + +fn refusal(e: pt::OutlineError) -> EngineError { + bad( + COMMON_TANGENTS, + match e { + pt::OutlineError::Open => "a selected path is open", + pt::OutlineError::NotConvex => "a selected path is not convex", + pt::OutlineError::Empty => "a selected path has no area", + pt::OutlineError::TooComplex => "a selected path has more than 10000 segments", + }, + ) +} + +fn common_tangents(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMON_TANGENTS; + let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let centerline = switch_or(p, "centerline", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ordered = d.paint_order(roots.iter().copied()); + let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; + let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; + let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); + let keep = |t: &&pt::Tangent| match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + }; + let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); + let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); + let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() { + // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one + // external tangent means one path lies inside the other and touches it there; paths that + // overlap without one inside the other have at least two. + let warning = match external { + 0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()), + 1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()), + _ => EngineError::Other("The paths overlap, so they have no internal tangents".into()), + }; + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + let fill = Paint::None; + let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; + let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); + // The new art's look may carry more fills than the top one: none of them is kept. + look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + let top = *second; + let (ids, center_id) = s.edit(LABEL, |d, sel| { + let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; + let mut ids = vec![]; + let mut center_id = None; + for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let id = d.alloc_id(); + let path = PathData::single(SubPath::polyline(&[from, to], false)); + let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + look.apply(d, &mut n); + d.insert(parent, idx + 1 + k, n)?; + if k == lines.len() { + center_id = Some(id); + } + ids.push(id); + } + sel.set(ids.iter().copied()); + Ok((ids, center_id)) + })?; + Ok(json!({ + "ids": ids.iter().map(|i| i.0).collect::>(), + "external": external_kept, + "internal": internal_kept, + "centerline": center_id.map(|i| i.0), + })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..5ed6e2b0d6 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -0,0 +1,265 @@ +//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline, +//! the paint, one undo step, the cases with no tangent, and refused selections and params. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; +use vectorcraft_geom::{Point, Vec2}; + +use crate::Session; + +const C: &str = super::COMMON_TANGENTS; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId { + id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The ends of each new line, as `ids` lists them. +fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> { + let d = &s.doc().unwrap().doc; + r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + (sp.anchors[0].p, sp.anchors[1].p) + }) + .collect() +} + +fn near(p: Point, q: Point) -> bool { + p.distance(q) < 1e-6 +} + +fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool { + found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p))) +} + +#[test] +fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 200.0, 20.0); + let b = circle(&mut s, 300.0, 200.0, 40.0); + select(&mut s, &[a, b]); + let before = steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 4); + let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3. + for (nx, external) in [(-0.1f64, true), (0.3, false)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 }; + assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}"); + } + } + // The lines are the selection, above the two circles. + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 4); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied())); + assert_eq!(&order[..2], &[a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all"); +} + +#[test] +fn turned_ellipses_are_measured_exactly() { + let mut s = session(); + let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap()); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap(); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap()); + select(&mut s, &[b]); + s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(C, &json!({"tangents": "all"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + // Each end lies on its ellipse, where the ellipse runs along the line: turned back about the + // center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line. + let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| { + let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians()); + // `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms. + let page = |v: Vec2| Vec2::new(v.x, -v.y); + let q = page((turn * page(p - center).to_point()).to_vec2()); + let d = page((turn * page(dir).to_point()).to_vec2()); + let value = (q.x / rx).powi(2) + (q.y / ry).powi(2); + let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry)); + (value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7 + }; + for (p, q) in lines(&s, &r) { + let dir = q - p; + assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse"); + assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse"); + } +} + +#[test] +fn a_convex_bezier_path_and_the_centerline() { + let mut s = session(); + let anchors = json!([ + {"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]}, + {"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]}, + {"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]}, + {"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]} + ]); + let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()); + let round = circle(&mut s, 300.0, 200.0, 30.0); + let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 5, "four tangents and the centerline"); + // The centerline is the last line and its id is given: from the blob's center of area to the + // circle's center. + assert_eq!(r["centerline"], r["ids"][4]); + let (from, to) = found[4]; + assert!(near(to, Point::new(300.0, 200.0)), "{to:?}"); + assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}"); + // A tangent touches without crossing: every point of both paths is on one side of it. + let d = &s.doc().unwrap().doc; + let points = |id: NodeId| { + let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect(); + segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::>() + }; + let (pa, pb) = (points(blob), points(round)); + for (p, q) in &found[..4] { + let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize(); + for pts in [&pa, &pb] { + let side: Vec = pts.iter().map(|x| (*x - *p).dot(n)).collect(); + let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + // The circle is measured as an exact circle, which its four curves follow to within + // about 0.03% of the radius. + assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}"); + } + } +} + +#[test] +fn the_lines_take_the_current_stroke_and_no_fill() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let d = &s.doc().unwrap().doc; + for v in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill"); + let st = n.appearance.stroke().expect("stroked"); + assert!(!st.paint.is_none(), "black when the stroke is None"); + } + // A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill. + let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0); + let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap(); + look.items.push(fill); + s.paint.appearance = Some(look); + s.paint.inherited = false; + let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + let d2 = &s.doc().unwrap().doc; + for v in r2["ids"].as_array().unwrap() { + let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all"); + assert!(n.appearance.stroke().is_some()); + } + // Two equal circles: the external tangents run along their tops and bottoms. + assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0))); + assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0))); +} + +#[test] +fn nested_and_overlapping_paths_change_nothing_and_say_why() { + let mut s = session(); + let big = circle(&mut s, 200.0, 200.0, 100.0); + let small = circle(&mut s, 220.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Overlapping circles have external tangents only. + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 140.0, 100.0, 30.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap(); + assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + // Circles that touch share the tangent where they touch. + let c = circle(&mut s, 100.0, 300.0, 10.0); + let e = circle(&mut s, 130.0, 300.0, 20.0); + let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["internal"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}"); + // A circle touching the inside of a larger one: no internal tangent, and the message says the + // one lies inside the other rather than that they overlap. + let outer = circle(&mut s, 400.0, 200.0, 50.0); + let inner = circle(&mut s, 430.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); +} + +#[test] +fn bad_selections_and_params_are_refused() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap()); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + let group_of = |s: &mut Session, ids: &[NodeId]| { + select(s, ids); + id_of(&s.execute("object.group", &json!({})).unwrap()) + }; + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused"); + assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex")); + assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open")); + assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()); + assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline")); + let g = group_of(&mut s, &[b]); + assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f445237d83..2615adb680 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -45,6 +45,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", "addon.pathtools.close", + "addon.pathtools.commonTangents", "addon.pathtools.corner", "addon.pathtools.cornerRemove", "addon.pathtools.cornerSet", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 30d0dc96cf..8cdac3bc34 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -984,6 +984,10 @@ fn structured_junk() { ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), + ("addon.pathtools.commonTangents", json!({"tangents": "all", "centerline": true})), + ("addon.pathtools.commonTangents", json!({"tangents": "x", "centerline": "y", "ids": [u64::MAX, -1]})), + ("addon.pathtools.commonTangents", json!({"tangents": null, "ids": [1, 2, 3, 4], "centerline": null})), + ("addon.pathtools.commonTangents", json!({"tangents": ["external"], "ids": "all"})), ("addon.pathtools.expandDashes", json!({})), ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index a20a4a5b36..0e5afd9ce7 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,7 +4,8 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]) and the Parametric Shape Tool's shapes ([`shapes`]). +//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]) and the +//! Parametric Shape Tool's shapes ([`shapes`]). mod crossings; mod dashes; @@ -12,6 +13,7 @@ mod extend; pub mod shapes; mod shared_edge; mod slide; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -28,6 +30,7 @@ pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at}; +pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents}; pub use trim::{Span, slice, span_at, spans, without_spans}; use crate::fit::{end_tangent, start_tangent}; diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..c0d66e0dc1 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -0,0 +1,853 @@ +//! Common Tangents: the straight lines that touch two convex closed outlines (ellipses at any +//! rotation and scale, and convex Bézier paths) without crossing into either. An external tangent +//! has both outlines on the same side of it; an internal one runs between them. +//! +//! A line with unit normal `n` touches an outline from outside where `p · n` reaches the +//! outline's support value `h(n)`, the largest `p · n` over its points. External tangents are the +//! normals where both outlines have the same support value, internal ones where `h₁(n) = -h₂(-n)`. +//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with +//! sampled minima refined too so that a double root (outlines that touch) or two roots between +//! neighboring samples are kept. + +use std::f64::consts::TAU; + +use kurbo::{Affine, CubicBez, ParamCurve, Point, Vec2}; +use vectorcraft_geom::SubPath; + +/// Most segments one outline may have. +pub const MAX_TANGENT_SEGMENTS: usize = 10_000; +/// Normal directions sampled around the circle before refining. +const SAMPLES: usize = 720; +/// Steps of bisection or golden-section search for each root. +const STEPS: usize = 64; +/// Straight pieces each segment is cut into to check that a path is convex and to find its center. +const FLATTEN: usize = 32; + +/// Which side of a tangent the two outlines lie on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TangentKind { + /// Both on the same side. + External, + /// One on each side. + Internal, +} + +/// One common tangent: the stretch of the line from where it touches the first outline to where +/// it touches the second. Where the outlines touch each other at one point, the stretch is +/// centered on that point and as long as the narrower outline is wide along the line, and `from` +/// is the end with the lower position along the line. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tangent { + pub kind: TangentKind, + pub from: Point, + pub to: Point, +} + +/// Why [`Outline::convex`] or [`Outline::ellipse`] cannot take a shape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineError { + /// The path is open. + Open, + /// The path bends inward somewhere, or winds around more than once. + NotConvex, + /// No area, or not finite. + Empty, + /// More than [`MAX_TANGENT_SEGMENTS`] segments. + TooComplex, +} + +/// The two outlines are the same, so every line touching one touches the other. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Coincide; + +/// A convex closed outline that [`common_tangents`] takes. +#[derive(Clone, Debug)] +pub enum Outline { + /// The unit circle under an affine map: the center is the map's translation, `m` its linear + /// part (`[a, b, c, d]`, as kurbo orders them). + Ellipse { center: Point, m: [f64; 4] }, + /// A convex closed path's segments, its center of area and the diagonal of its bounds. `ccw` + /// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then + /// comes later in the list as the angle of `n` grows. + Convex { segments: Vec, center: Point, size: f64, ccw: bool }, +} + +impl Outline { + /// The ellipse that `unit` maps the unit circle onto. + pub fn ellipse(unit: Affine) -> Result { + let [a, b, c, d, e, f] = unit.as_coeffs(); + let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm { + return Err(OutlineError::Empty); + } + Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) + } + + /// A closed subpath that bends one way all around and winds around once. + pub fn convex(sp: &SubPath) -> Result { + if !sp.closed { + return Err(OutlineError::Open); + } + let n = sp.segment_count(); + if n > MAX_TANGENT_SEGMENTS { + return Err(OutlineError::TooComplex); + } + let segments: Vec = (0..n).map(|k| sp.segment(k)).collect(); + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if segments.iter().any(|s| ![s.p0, s.p1, s.p2, s.p3].into_iter().all(finite)) { + return Err(OutlineError::Empty); + } + let mut pts: Vec = Vec::with_capacity(n * FLATTEN); + for s in &segments { + pts.extend((0..FLATTEN).map(|k| s.eval(k as f64 / FLATTEN as f64))); + } + let (lo, hi) = pts.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| { + (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))) + }); + let size = (hi - lo).hypot(); + if !size.is_finite() || size <= 0.0 { + return Err(OutlineError::Empty); + } + // Points closer than this to the one before are dropped: a retracted handle or a segment + // of no length gives no direction. + pts.dedup_by(|b, a| (*b - *a).hypot() <= 1e-9 * size); + while pts.len() > 1 && pts.first().zip(pts.last()).is_some_and(|(f, l)| (*f - *l).hypot() <= 1e-9 * size) { + pts.pop(); + } + let m = pts.len(); + if m < 3 { + return Err(OutlineError::Empty); + } + // Area, center and turns are worked out on the points taken about the first one and + // divided by the size. + let origin = pts[0].to_vec2(); + let unit: Vec = pts.iter().map(|p| (p.to_vec2() - origin) / size).collect(); + let (mut area2, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..m { + let (p, q) = (unit[i], unit[(i + 1) % m]); + let cross = p.cross(q); + area2 += cross; + cx += (p.x + q.x) * cross; + cy += (p.y + q.y) * cross; + } + if area2.abs() <= 1e-12 { + return Err(OutlineError::Empty); + } + let sign = area2.signum(); + // Every turn the same way (straight runs allowed), and one turn in all. + let mut turning = 0.0; + for i in 0..m { + let (p, q, r) = (unit[(i + m - 1) % m], unit[i], unit[(i + 1) % m]); + let (u, v) = (q - p, r - q); + let cross = u.cross(v) * sign; + if cross < -1e-12 { + return Err(OutlineError::NotConvex); + } + turning += cross.atan2(u.dot(v)); + } + if (turning - TAU).abs() > 1e-6 { + return Err(OutlineError::NotConvex); + } + let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); + if !center.x.is_finite() || !center.y.is_finite() { + return Err(OutlineError::Empty); + } + Ok(Outline::Convex { segments, center, size, ccw: sign > 0.0 }) + } + + /// The outline moved by `d`. + fn shifted(&self, d: Vec2) -> Self { + match self { + Outline::Ellipse { center, m } => Outline::Ellipse { center: *center + d, m: *m }, + Outline::Convex { segments, center, size, ccw } => Outline::Convex { + segments: segments.iter().map(|s| CubicBez::new(s.p0 + d, s.p1 + d, s.p2 + d, s.p3 + d)).collect(), + center: *center + d, + size: *size, + ccw: *ccw, + }, + } + } + + /// Adds to `out` the normal angles where the point of largest `p · n` can pass from one + /// segment to the next: square to each segment's direction at its ends, on both sides. + fn breaks(&self, out: &mut Vec) { + let Outline::Convex { segments, .. } = self else { return }; + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot2() > 0.0); + for s in segments { + let ends = [nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]), nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])]; + for d in ends.into_iter().flatten() { + let a = d.y.atan2(d.x); + out.extend([a + TAU / 4.0, a - TAU / 4.0]); + } + } + } + + /// The support value at `n` and the segment it is reached on, from every segment. + fn support_scan(&self, n: Vec2) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, .. } => { + let mut best = (f64::MIN, 0); + for (i, s) in segments.iter().enumerate() { + each_extreme(s, n, |_, v| { + if v > best.0 { + best = (v, i); + } + }); + } + best + } + } + } + + /// The support value at `n` and the segment it is reached on, walking on from segment `from`, + /// where the support value was reached at a normal angle a little less than `n`'s. + fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, ccw, .. } => { + let len = segments.len(); + if len == 0 { + return (f64::MIN, 0); + } + let step = if *ccw { 1 } else { len - 1 }; + let value = |i: usize| { + let mut best = f64::MIN; + if let Some(s) = segments.get(i) { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + }; + let mut i = from % len; + let mut v = value(i); + for _ in 0..len { + let j = (i + step) % len; + let w = value(j); + if w < v { + break; + } + (i, v) = (j, w); + } + (v, i) + } + } + } + + /// The center: an ellipse's, or a path's center of area. + pub fn center(&self) -> Point { + match self { + Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center, + } + } + + /// The diagonal of the bounds (an ellipse's: of the box its axes span). + fn size(&self) -> f64 { + match self { + Outline::Ellipse { m, .. } => { + let [a, b, c, d] = *m; + 2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt() + } + Outline::Convex { size, .. } => *size, + } + } + + /// The support value: the largest `p · n` over the outline's points. + fn support(&self, n: Vec2) -> f64 { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => center.to_vec2().dot(n) + Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y).hypot(), + Outline::Convex { segments, .. } => { + let mut best = f64::MIN; + for s in segments { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + } + } + } + + /// The points of the outline on the line `p · n = h`, its support value: the point where + /// `p · n` is largest, and the ends of any straight side along the line. Another point counts + /// when it lies within `tol` of the line plus `slope` times its distance from that largest + /// point, where `slope` is how far off the normal's angle may be. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => { + let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); + let w = w / w.hypot(); + vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] + } + Outline::Convex { segments, .. } => { + let mut all = vec![]; + for s in segments { + each_extreme(s, n, |p, v| all.push((p, v))); + } + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() + } + } + } +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. +fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); + f(s.p0, v0); + f(s.p3, v3); + // The derivative of p(t) · n, divided by 3: a quadratic in t. + let (d0, d1, d2) = (v1 - v0, v2 - v1, v3 - v2); + let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); + let mut root = |t: f64| { + if t > 0.0 && t < 1.0 { + let p = s.eval(t); + f(p, p.to_vec2().dot(n)); + } + }; + let scale = qa.abs().max(qb.abs()).max(qc.abs()); + if !scale.is_finite() || scale <= 0.0 { + return; + } + if qa.abs() <= 1e-12 * scale { + if qb != 0.0 { + root(-qc / qb); + } + return; + } + let disc = qb * qb - 4.0 * qa * qc; + if disc < 0.0 { + return; + } + // The stable form of the two roots; with `qb` zero the sign is taken as positive, so `q` is + // not zero. + let sign = if qb < 0.0 { -1.0 } else { 1.0 }; + let q = -0.5 * (qb + sign * disc.sqrt()); + root(q / qa); + if q != 0.0 { + root(qc / q); + } +} + +/// The unit vector at `angle` radians. +fn dir(angle: f64) -> Vec2 { + Vec2::new(angle.cos(), angle.sin()) +} + +/// The common tangents of `a` and `b`: the external ones, then the internal ones, each in order of +/// the angle of its normal. Separate outlines have two of each; overlapping ones only external +/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the +/// other none; outlines that touch share one tangent where they touch. +pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincide> { + // Worked out about the point between the two centers. + let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0; + let (a, b) = (&a.shifted(-origin), &b.shifted(-origin)); + let size = a.size().max(b.size()).max((a.center() - b.center()).hypot()); + let tol = 1e-9 * size; + // The normal angles sampled: evenly spaced ones, and every angle where the support value of + // either outline passes to another segment. Between two neighboring samples each outline is + // then touched on one segment. + let mut at: Vec = (0..SAMPLES).map(|k| k as f64 * TAU / SAMPLES as f64).collect(); + a.breaks(&mut at); + b.breaks(&mut at); + let mut at: Vec = at.into_iter().map(|t| t.rem_euclid(TAU)).map(|t| if t < TAU { t } else { 0.0 }).collect(); + at.sort_by(f64::total_cmp); + at.dedup_by(|y, x| *y - *x <= 1e-12); + // The segment each outline is touched on at each sample, found by walking around once. + let hints = |o: &Outline, sign: f64| -> Vec { + let mut out = Vec::with_capacity(at.len()); + let mut i = at.first().map_or(0, |t| o.support_scan(dir(*t) * sign).1); + for t in &at { + i = o.support_from(dir(*t) * sign, i).1; + out.push(i); + } + out + }; + let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0)); + let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); + let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; + let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let mut out = Vec::with_capacity(external.len() + internal.len()); + for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { + for root in list { + let t = tangent_at(a, b, kind, dir(root.angle), root.double, size); + out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); + } + } + Ok(out) +} + +/// A zero of a support-value difference: the normal's angle, and whether the difference only +/// touches zero there (outlines that touch) rather than crossing it. +#[derive(Clone, Copy, Debug)] +struct Root { + angle: f64, + double: bool, +} + +/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value, +/// and `b` on the same side (external) or the other side (internal). `double` when the outlines +/// touch there. +fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent { + // The rounding allowed in `p · n` grows with each outline's own size and its distance from the + // origin. + let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); + let (tol_a, tol_b) = (rounding(a), rounding(b)); + // Bisection finds a simple root's angle to about the rounding of the support values; the + // golden-section search finds a double root's to about 1e-8 radians. + let slope = if double { 1e-7 } else { 1e-10 }; + let ha = a.support(n); + let (on_a, on_b) = match kind { + TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)), + TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)), + }; + // Positions along the line, which runs square to `n` through `n * ha`. + let t = Vec2::new(-n.y, n.x); + let along = |p: &Point| p.to_vec2().dot(t); + let mean = |v: &[Point]| v.iter().map(along).sum::() / v.len().max(1) as f64; + let all = on_a.iter().chain(&on_b).map(along); + let (lo, hi) = all.fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(s), hi.max(s))); + let at = |s: f64| (n * ha + t * s).to_point(); + // A double root's angle is found less exactly than a simple one's, so touching points may + // stand a little apart. + let (from, to) = if double && hi - lo <= 1e-6 * size { + // Touching at one point: the narrower outline's width along the line, centered there. + let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min); + let mid = (lo + hi) / 2.0; + (mid - width / 2.0, mid + width / 2.0) + } else if mean(&on_a) <= mean(&on_b) { + (lo, hi) + } else { + (hi, lo) + }; + Tangent { kind, from: at(from), to: at(to) } +} + +/// The angles in `[0, 2π)` where `f` (periodic) is zero, within `tol`. An interval where it stays +/// zero (outlines that meet at a corner or along a shared stretch) gives the angle at its middle, +/// as a double root. +/// +/// `at` holds the sampled angles in increasing order, in `[0, 2π)`; `f(t, k)` is `f` at an angle +/// `t` at or after sample `k` and before the sample two on. +fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result, Coincide> { + let n = at.len(); + if n < 3 { + return Err(Coincide); + } + // The angle of sample `k + j`, counted on from sample `k` past 2π. + let ang = |k: usize, j: usize| at.get((k + j) % n).copied().unwrap_or(0.0) + TAU * ((k + j) / n) as f64; + let v: Vec = (0..n).map(|k| f(ang(k, 0), k)).collect(); + let val = |k: usize| v.get(k % n).copied().unwrap_or(0.0); + let zero = |x: f64| x.abs() <= tol; + let Some(start) = v.iter().position(|x| !zero(*x)) else { return Err(Coincide) }; + let simple = |angle: f64| Root { angle, double: false }; + let mut out = vec![]; + // Between `lo` (sample `k`) and `hi`, where `s * f` is positive at both ends: the least of + // `s * f`, a double root where it reaches zero, two roots where it goes past it, none where it + // stays above. + let dip = |out: &mut Vec, s: f64, k: usize, lo: f64, hi: f64| { + let g = |t: f64| f(t, k); + let (t, least) = golden(&|t| s * g(t), lo, hi); + if least < -tol { + out.push(simple(bisect(&g, lo, t))); + out.push(simple(bisect(&g, t, hi))); + } else if least <= tol { + out.push(Root { angle: t, double: true }); + } + }; + for i in 0..n { + let k = (start + i) % n; + let (prev, next) = ((k + n - 1) % n, k + 1); + let theta = ang(k, 0); + if zero(val(k)) { + continue; + } + if zero(val(next)) { + let len = (1..n).take_while(|j| zero(val(k + j))).count(); + if len == 1 { + // One sample on zero: a crossing when the samples beside it differ in sign, else a + // dip between them. + let (lo, hi) = (theta, ang(k, 2)); + let s = val(k).signum(); + if val(k + 2).signum() == s { + dip(&mut out, s, k, lo, hi); + } else { + out.push(simple(bisect(&|t| f(t, k), lo, hi))); + } + } else { + out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true }); + } + continue; + } + if val(k).signum() != val(next).signum() { + out.push(simple(bisect(&|t| f(t, k), theta, ang(k, 1)))); + continue; + } + // A sampled minimum of |f|: the curve may dip to zero (a double root), or across it and + // back (two roots), between the neighboring samples. + let (vp, vk, vn) = (val(prev), val(k), val(next)); + if !zero(vp) && vp.signum() == vk.signum() && vk.abs() < vp.abs() && vk.abs() <= vn.abs() { + let lo = if k == 0 { ang(prev, 0) - TAU } else { ang(prev, 0) }; + dip(&mut out, vk.signum(), prev, lo, ang(k, 1)); + } + } + let mut out: Vec = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect(); + out.sort_by(|a, b| a.angle.total_cmp(&b.angle)); + out.dedup_by(|b, a| { + let same = (b.angle - a.angle).abs() < 1e-7; + a.double |= same && b.double; + same + }); + if out.len() > 1 + && out.first().zip(out.last()).is_some_and(|(f, l)| f.angle + TAU - l.angle < 1e-7) + && let Some(last) = out.pop() + && let Some(first) = out.first_mut() + { + first.double |= last.double; + } + Ok(out) +} + +/// A root of `f` between `lo` and `hi`, where it has opposite signs. +fn bisect(f: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> f64 { + let s = f(lo).signum(); + for _ in 0..STEPS { + let mid = (lo + hi) / 2.0; + if f(mid).signum() == s { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 +} + +/// Where `g` is least between `lo` and `hi` (taken as having one minimum there), and its value. +fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { + let r = (5f64.sqrt() - 1.0) / 2.0; + let (mut x1, mut x2) = (hi - r * (hi - lo), lo + r * (hi - lo)); + let (mut g1, mut g2) = (g(x1), g(x2)); + for _ in 0..STEPS { + if g1 < g2 { + hi = x2; + (x2, g2) = (x1, g1); + x1 = hi - r * (hi - lo); + g1 = g(x1); + } else { + lo = x1; + (x1, g1) = (x2, g2); + x2 = lo + r * (hi - lo); + g2 = g(x2); + } + } + let t = (lo + hi) / 2.0; + (t, g(t)) +} + +#[cfg(test)] +mod tests { + use kurbo::Rect; + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(cx: f64, cy: f64, r: f64) -> Outline { + Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() + } + + /// An ellipse with semi-axes `rx`, `ry`, turned `deg` degrees, centered at (`cx`, `cy`). + fn ellipse_map(cx: f64, cy: f64, rx: f64, ry: f64, deg: f64) -> Affine { + Affine::translate((cx, cy)) * Affine::rotate(deg.to_radians()) * Affine::scale_non_uniform(rx, ry) + } + + /// Whether `t` has its two ends at `p` and `q`, in either order. + fn ends_at(t: &Tangent, p: Point, q: Point) -> bool { + ends_within(t, p, q, 1e-7) + } + + /// [`ends_at`] within `eps`: the angle of a tangent where outlines touch (a double root) is + /// found to about 1e-8 radians. + fn ends_within(t: &Tangent, p: Point, q: Point, eps: f64) -> bool { + let near = |a: Point, b: Point| (a - b).hypot() < eps; + (near(t.from, p) && near(t.to, q)) || (near(t.from, q) && near(t.to, p)) + } + + /// Checks `t` against dense samples of the two outlines, without support values: each lies on + /// one side of the line (the same side for an external tangent, opposite ones for an internal + /// one) and comes within `eps` of it. + fn check_against_samples(t: &Tangent, a: &[Point], b: &[Point], eps: f64) { + let d = t.to - t.from; + let n = Vec2::new(-d.y, d.x) / d.hypot(); + let side = |pts: &[Point]| { + let dist: Vec = pts.iter().map(|p| (*p - t.from).dot(n)).collect(); + let (lo, hi) = dist.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s))); + assert!(lo > -eps || hi < eps, "the line crosses the outline: {lo} .. {hi} ({t:?})"); + assert!(lo.abs() < eps || hi.abs() < eps, "the line misses the outline: {lo} .. {hi} ({t:?})"); + if hi < eps { -1.0 } else { 1.0 } + }; + let (sa, sb) = (side(a), side(b)); + match t.kind { + TangentKind::External => assert_eq!(sa, sb, "{t:?}"), + TangentKind::Internal => assert_ne!(sa, sb, "{t:?}"), + } + } + + fn sample_ellipse(m: Affine, count: usize) -> Vec { + (0..count).map(|k| m * Point::new((TAU * k as f64 / count as f64).cos(), (TAU * k as f64 / count as f64).sin())).collect() + } + + fn sample_path(sp: &SubPath, per_segment: usize) -> Vec { + (0..sp.segment_count()).flat_map(|k| (0..per_segment).map(move |j| sp.segment(k).eval(j as f64 / per_segment as f64))).collect() + } + + #[test] + fn two_circles_have_four_tangents_at_the_closed_form_points() { + let (c1, r1, c2, r2) = (Point::new(0.0, 0.0), 10.0, Point::new(100.0, 0.0), 20.0); + let all = common_tangents(&circle(c1.x, c1.y, r1), &circle(c2.x, c2.y, r2)).unwrap(); + assert_eq!(all.len(), 4, "{all:?}"); + // External: (c1 - c2) · n = r2 - r1, so n.x = -0.1; the points are c + r n on each. + // Internal: (c1 - c2) · n = -(r1 + r2), so n.x = 0.3; c1 + r1 n and c2 - r2 n. + for (kind, nx) in [(TangentKind::External, -0.1f64), (TangentKind::Internal, 0.3)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if kind == TangentKind::External { c2 + n * r2 } else { c2 - n * r2 }; + let found = all.iter().filter(|t| t.kind == kind && ends_at(t, c1 + n * r1, far)).count(); + assert_eq!(found, 1, "{kind:?} {n:?} in {all:?}"); + } + } + // Each runs from the first outline to the second. + assert!(all.iter().all(|t| (t.from - c1).hypot() < (t.to - c1).hypot())); + } + + #[test] + fn turned_ellipses_match_an_independent_numeric_solution() { + let (ma, mb) = (ellipse_map(0.0, 0.0, 40.0, 15.0, 30.0), ellipse_map(150.0, 60.0, 25.0, 60.0, -70.0)); + let all = common_tangents(&Outline::ellipse(ma).unwrap(), &Outline::ellipse(mb).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(ma, 5_000), sample_ellipse(mb, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // A brute-force scan of the normal's angle with support values read off the samples finds + // the same normals. + let support = |pts: &[Point], n: Vec2| pts.iter().map(|p| p.to_vec2().dot(n)).fold(f64::MIN, f64::max); + let scan = |f: &dyn Fn(Vec2) -> f64| { + let steps = 7_200; + let g = |k: usize| f(dir(TAU * k as f64 / steps as f64)); + (0..steps).filter(|&k| g(k).signum() != g((k + 1) % steps).signum()).map(|k| TAU * (k as f64 + 0.5) / steps as f64).collect::>() + }; + let ext = scan(&|n| support(&sa, n) - support(&sb, n)); + let int = scan(&|n| support(&sa, n) + support(&sb, -n)); + for (kind, expected) in [(TangentKind::External, ext), (TangentKind::Internal, int)] { + assert_eq!(expected.len(), 2); + for angle in expected { + let n = dir(angle); + let hit = all.iter().filter(|t| t.kind == kind).any(|t| { + let d = t.to - t.from; + let m = Vec2::new(d.y, -d.x) / d.hypot(); + m.dot(n).abs() > 1.0 - 1e-6 + }); + assert!(hit, "{kind:?} normal at {angle} in {all:?}"); + } + } + } + + #[test] + fn nested_overlapping_and_touching_circles() { + // One inside the other: none. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(5.0, 0.0, 10.0)).unwrap().is_empty()); + // Overlapping: the two external ones only. + let over = common_tangents(&circle(0.0, 0.0, 30.0), &circle(40.0, 0.0, 30.0)).unwrap(); + assert_eq!(over.len(), 2); + assert!(over.iter().all(|t| t.kind == TangentKind::External)); + assert!(over.iter().any(|t| ends_at(t, Point::new(0.0, 30.0), Point::new(40.0, 30.0)))); + // Touching from outside at (10, 0): two external ones and one shared internal one, square to + // the line of centers, as long as the smaller circle is wide. + let touch = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0, 0.0, 20.0)).unwrap(); + assert_eq!(touch.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{touch:?}"); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(ends_within(shared[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{shared:?}"); + // Touching along a direction between two sampled normals: the sampled minimum is refined + // down to the double root. + let along = dir(0.1234); + let off = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0 * along.x, 30.0 * along.y, 20.0)).unwrap(); + assert_eq!(off.iter().filter(|t| t.kind == TangentKind::Internal).count(), 1, "{off:?}"); + // A hair apart: two internal tangents less than a sample apart, both kept. + let d = 30.000_01; + let near_miss = common_tangents(&circle(0.0, 0.0, 10.0), &circle(d * along.x, d * along.y, 20.0)).unwrap(); + assert_eq!(near_miss.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{near_miss:?}"); + // Inside with a clearance of 1e-6: no tangent. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0 - 1e-6, 0.0, 10.0)).unwrap().is_empty()); + // Equal circles a hair apart: the two external tangents run between their real contact + // points, that hair apart, not as a touching tangent. + let hair = common_tangents(&circle(0.0, 0.0, 30.0), &circle(1e-5, 0.0, 30.0)).unwrap(); + assert_eq!(hair.len(), 2, "{hair:?}"); + assert!(hair.iter().all(|t| ((t.to - t.from).hypot() - 1e-5).abs() < 1e-9), "{hair:?}"); + // Touching from inside at (50, 0): the one shared external tangent. + let inside = common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0, 0.0, 10.0)).unwrap(); + assert_eq!(inside.len(), 1, "{inside:?}"); + assert!(ends_within(&inside[0], Point::new(50.0, -10.0), Point::new(50.0, 10.0), 1e-5), "{inside:?}"); + } + + #[test] + fn a_convex_bezier_blob_and_an_ellipse_path() { + // A lopsided convex blob of four curves. + let a = |x: f64, y: f64, ix: f64, iy: f64, ox: f64, oy: f64| { + vectorcraft_geom::Anchor::with_handles(Point::new(x, y), Point::new(ix, iy), Point::new(ox, oy)) + }; + let blob = SubPath::new( + vec![ + a(0.0, 40.0, 0.0, 70.0, 0.0, 10.0), + a(50.0, 0.0, 20.0, 0.0, 90.0, 0.0), + a(110.0, 50.0, 110.0, 20.0, 110.0, 90.0), + a(40.0, 100.0, 80.0, 100.0, 10.0, 100.0), + ], + true, + ); + let round = shapes::ellipse(Rect::new(200.0, 150.0, 260.0, 230.0)).subpaths[0].clone(); + let (oa, ob) = (Outline::convex(&blob).unwrap(), Outline::convex(&round).unwrap()); + let all = common_tangents(&oa, &ob).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_path(&blob, 4000), sample_path(&round, 4000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // The path's center is its center of area: the ellipse path's is its box's center. + assert!((ob.center() - Point::new(230.0, 190.0)).hypot() < 1e-6, "{:?}", ob.center()); + } + + #[test] + fn flat_sides_give_the_whole_stretch_they_touch() { + let square = + |x: f64| SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)], true); + let all = common_tangents(&Outline::convex(&square(0.0)).unwrap(), &Outline::convex(&square(30.0)).unwrap()).unwrap(); + let ext: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{all:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 0.0), Point::new(40.0, 0.0))), "{ext:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 10.0), Point::new(40.0, 10.0))), "{ext:?}"); + // Far apart, each diamond is still touched only at its top corner. + let diamond = + |x: f64| SubPath::polyline(&[Point::new(x - 5.0, 0.0), Point::new(x, -5.0), Point::new(x + 5.0, 0.0), Point::new(x, 5.0)], true); + let far = common_tangents(&Outline::convex(&diamond(0.0)).unwrap(), &Outline::convex(&diamond(1e9)).unwrap()).unwrap(); + let top = far.iter().find(|t| t.kind == TangentKind::External && t.from.y > 0.0).unwrap(); + assert!(ends_within(top, Point::new(0.0, 5.0), Point::new(1e9, 5.0), 1e-3), "{far:?}"); + // Far from the origin the center of area and the tangents come out as near it. + let o = 1e9; + let away = |x: f64| SubPath::polyline(&[(x, o), (x + 10.0, o), (x + 10.0, o + 10.0), (x, o + 10.0)].map(Point::from), true); + let (sa, sb) = (Outline::convex(&away(o)).unwrap(), Outline::convex(&away(o + 30.0)).unwrap()); + assert!((sa.center() - Point::new(o + 5.0, o + 5.0)).hypot() < 1e-6, "{:?}", sa.center()); + let shifted = common_tangents(&sa, &sb).unwrap(); + assert!(shifted.iter().any(|t| ends_within(t, Point::new(o, o), Point::new(o + 40.0, o), 1e-6)), "{shifted:?}"); + // The internal ones are the diagonals between the near corners. + let int: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(int.len(), 2, "{all:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 0.0), Point::new(30.0, 10.0))), "{int:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 10.0), Point::new(30.0, 0.0))), "{int:?}"); + // Squares meeting at the corner (10, 10): every line through the corner between their + // sides touches both, and the one internal line drawn is the one at the middle of those + // directions, as long as a square is wide along it. + let box_at = |x: f64, y: f64| { + SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y), Point::new(x + 10.0, y + 10.0), Point::new(x, y + 10.0)], true) + }; + let corner = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(10.0, 10.0)).unwrap()).unwrap(); + let shared: Vec<_> = corner.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{corner:?}"); + assert!(ends_within(shared[0], Point::new(5.0, 15.0), Point::new(15.0, 5.0), 1e-6), "{shared:?}"); + // Sides 1e-6 off parallel: each line ends at the corners it touches, not at the corners + // of the sides it nearly lies along. + let tilted = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(30.0, -1e-6)).unwrap()).unwrap(); + let ext: Vec<_> = tilted.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{tilted:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(10.0, 10.0), Point::new(40.0, 10.0 - 1e-6), 1e-6)), "{ext:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(0.0, 0.0), Point::new(30.0, -1e-6), 1e-6)), "{ext:?}"); + } + + /// A circle path of four curves, radius 100 about the origin, with an anchor at (100, 0). + fn circle_path() -> SubPath { + shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).subpaths[0].clone() + } + + /// The point of `sp` where `p · n` is largest. + fn peak(sp: &SubPath, n: Vec2) -> Point { + let mut best = (Point::ORIGIN, f64::MIN); + for k in 0..sp.segment_count() { + each_extreme(&sp.segment(k), n, |p, v| { + if v > best.1 { + best = (p, v); + } + }); + } + best.0 + } + + #[test] + fn a_curve_is_touched_only_at_its_peak_beside_an_anchor() { + // The line touches the circle path 5e-4 radians from its anchor at (100, 0), where the + // anchor lies about 1.25e-5 inside the line: the line still ends at the peak, not at the + // anchor 0.05 along it. + let path = circle_path(); + let n = dir(5e-4); + let away = Vec2::new(n.y, -n.x) * 300.0; + let a = Outline::convex(&path).unwrap(); + let all = common_tangents(&a, &a.shifted(away)).unwrap(); + let top = all.iter().find(|t| t.kind == TangentKind::External && (t.from.to_vec2().dot(n) - 100.0).abs() < 1e-3).unwrap(); + let p = peak(&path, n); + assert!(ends_within(top, p, p + away, 1e-6), "{top:?} {p:?}"); + // An exact circle touching the path there from outside: one shared internal line, as long + // as that circle is wide, not a stub running to the anchor. + let b = circle(p.x + 20.0 * n.x, p.y + 20.0 * n.y, 20.0); + let touch = common_tangents(&a, &b).unwrap(); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(((shared[0].to - shared[0].from).hypot() - 40.0).abs() < 1e-3, "{shared:?}"); + assert!(((shared[0].from.midpoint(shared[0].to)) - p).hypot() < 1e-3, "{shared:?}"); + } + + #[test] + fn outlines_crossing_more_often_than_the_even_samples_keep_every_tangent() { + // Two regular 400-gons about one center, one turned half a step: their outlines cross 800 + // times, and an external tangent runs across each crossing. + let gon = |turn: f64| { + let pts: Vec = (0..400).map(|k| (dir(turn + TAU * k as f64 / 400.0) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let all = common_tangents(&Outline::convex(&gon(0.0)).unwrap(), &Outline::convex(&gon(TAU / 800.0)).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 800); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 0); + // Each runs between a corner of one and the next corner of the other, about 0.785 apart. + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { + // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is + // zero, and the peak, 0.25 at t = 0.5, lies inside the segment. + let s = CubicBez::new((0.0, 0.0), (1.0, 0.25), (2.0, 0.5), (3.0, -0.25)); + let mut best = f64::MIN; + each_extreme(&s, Vec2::new(0.0, 1.0), |_, v| best = best.max(v)); + assert!((best - 0.25).abs() < 1e-12, "{best}"); + } + + #[test] + fn open_concave_empty_and_identical_outlines_are_refused() { + let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); + assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open)); + let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone(); + assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex)); + // A square traced twice around winds around twice. + let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); + let flat = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(20.0, 0.0)], true); + assert_eq!(Outline::convex(&flat).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::scale_non_uniform(10.0, 0.0)).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + let many: Vec = (0..=MAX_TANGENT_SEGMENTS).map(|k| dir(TAU * k as f64 / (MAX_TANGENT_SEGMENTS + 1) as f64).to_point()).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&many, true)).err(), Some(OutlineError::TooComplex)); + // A square 1e110 wide has a finite center. + let huge = SubPath::polyline(&[(0.0, 0.0), (1e110, 0.0), (1e110, 1e110), (0.0, 1e110)].map(Point::from), true); + let center = Outline::convex(&huge).unwrap().center(); + assert!((center - Point::new(5e109, 5e109)).hypot() < 1e98, "{center:?}"); + assert_eq!(common_tangents(&circle(1.0, 2.0, 3.0), &circle(1.0, 2.0, 3.0)), Err(Coincide)); + } +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index bfbcf0d5b3..41e8f6efed 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -30,6 +30,10 @@ pub const ID: &str = "anchorInspector"; const COUNT: &str = "anchor-inspector-count"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; +/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The kinds of tangent Common Tangents' `tangents` picks, and their labels. +pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; /// The close modes, as `addon.pathtools.close` names them, and their labels. const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; const LABEL_W: f32 = 64.0; @@ -70,6 +74,7 @@ pub fn menu() -> Vec { Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), + Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index db4b39b6fc..de01be5b7d 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -258,3 +258,73 @@ fn effect_path_effects_lists_the_live_effects_and_their_dialogs_pick_from_their_ assert!(options.iter().all(|(_, value)| doc.params.contains(&format!("\"{value}\""))), "{effect} {key}"); } } + +/// Object › Plug-ins › Path Precision Tools › Common Tangents… opens the command dialog on all +/// tangents without the centerline, Preview off. With Preview on the lines show on the canvas; +/// Cancel takes them away with no step of history, and OK keeps them as one step. Nested circles +/// change nothing and say why. +#[test] +fn common_tangents_previews_cancels_and_runs_on_ok() { + let mut app = app(); + let circle = |app: &mut VectorcraftApp, x: f64, r: f64| { + app.run("shape.ellipse", json!({"x": x - r, "y": 150.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (circle(&mut app, 60.0, 20.0), circle(&mut app, 220.0, 40.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), steps(&app), count(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::COMMON_TANGENTS.to_string(), "Common Tangents".to_string())); + assert_eq!((d.str("tangents"), d.bool("centerline"), d.bool("preview")), ("all".to_string(), false, false)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Common Tangents", "Tangents", "All", "Centerline", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + // Each kind the list offers is one the command takes. + for (_, kind) in super::TANGENT_KINDS { + assert!(vectorcraft_engine::check_params(super::COMMON_TANGENTS, &json!({"tangents": kind})).is_ok(), "{kind}"); + } + assert_eq!(count(&app), nodes, "no preview without the checkbox"); + + // Preview on: the four lines are on the canvas. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 4, "previewed"); + // External only, with the centerline: two lines and the centerline. + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "tangents".into(), json!("external")); + crate::dialogs::set_field(d, "centerline".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 3, "previewed again"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel takes the preview away"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + // OK: one step. + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(count(&app), nodes + 4); + + // A circle inside another: nothing changes, and a message says why. + let inner = circle(&mut app, 220.0, 10.0); + app.run("select.set", json!({"ids": [b, inner]})).unwrap(); + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes)); + assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 7afe37ec0b..9e918fe092 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -66,8 +66,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and -/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes. (Cancel rolls a -/// preview back whichever dialog started it.) +/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path +/// Precision Tools › Common Tangents. (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -77,7 +77,8 @@ fn previews(d: &Dialog) -> bool { | crate::addons::image::COLOR_MASK | crate::addons::cutting::WEED | crate::addons::cutting::BANNER - | crate::addons::cutting::NEST => true, + | crate::addons::cutting::NEST + | crate::addons::pathtools::COMMON_TANGENTS => true, _ => false, } } @@ -163,6 +164,7 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], + crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], _ => &[], } } @@ -179,6 +181,7 @@ fn choices(command: &str, key: &str) -> Option { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), + (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), _ => None, diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a6a69d9100..759e7dcfcd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6729,6 +6729,22 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Общи допирателни… + Common Tangents Общи допирателни + Tangents Допирателни + Centerline Централна линия + External Външни + Internal Вътрешни +@msg select two closed paths изберете два затворени пътя +@msg a selected path is open избран път е отворен +@msg a selected path is not convex избран път не е изпъкнал +@msg a selected path has no area избран път няма площ +@msg a selected path has more than 10000 segments избран път има повече от 10000 сегмента +@msg the two paths have the same outline двата пътя имат еднакъв контур +@msg One path lies inside the other, so they have no common tangents Единият път е вътре в другия, затова нямат общи допирателни +@msg The paths overlap, so they have no internal tangents Пътищата се припокриват, затова нямат вътрешни допирателни +@msg One path lies inside the other, so they have no internal tangents Единият път е вътре в другия, затова нямат вътрешни допирателни # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разширяване на тиретата в пътища @msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5da48b6cff..eefcdfe51d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6781,6 +6781,22 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Zajedničke tangente… + Common Tangents Zajedničke tangente + Tangents Tangente + Centerline Središnja linija + External Vanjske + Internal Unutrašnje +@msg select two closed paths odaberite dvije zatvorene putanje +@msg a selected path is open odabrana putanja je otvorena +@msg a selected path is not convex odabrana putanja nije konveksna +@msg a selected path has no area odabrana putanja nema površinu +@msg a selected path has more than 10000 segments odabrana putanja ima više od 10000 segmenata +@msg the two paths have the same outline obje putanje imaju isti obris +@msg One path lies inside the other, so they have no common tangents Jedna putanja leži unutar druge, pa nemaju zajedničkih tangenti +@msg The paths overlap, so they have no internal tangents Putanje se preklapaju, pa nemaju unutrašnjih tangenti +@msg One path lies inside the other, so they have no internal tangents Jedna putanja leži unutar druge, pa nemaju unutrašnjih tangenti # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Proširi crtice u putanje @msg select paths with dashed strokes to expand odaberite putanje s isprekidanim potezom za proširivanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e861e61fec..e2d6dd2c59 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7361,6 +7361,22 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangents comunes… + Common Tangents Tangents comunes + Tangents Tangents + Centerline Línia central + External Externes + Internal Internes +@msg select two closed paths seleccioneu dos camins tancats +@msg a selected path is open un camí seleccionat és obert +@msg a selected path is not convex un camí seleccionat no és convex +@msg a selected path has no area un camí seleccionat no té àrea +@msg a selected path has more than 10000 segments un camí seleccionat té més de 10000 segments +@msg the two paths have the same outline els dos camins tenen el mateix contorn +@msg One path lies inside the other, so they have no common tangents Un camí és dins de l’altre, per tant no tenen tangents comunes +@msg The paths overlap, so they have no internal tangents Els camins se superposen, per tant no tenen tangents internes +@msg One path lies inside the other, so they have no internal tangents Un camí és dins de l’altre, per tant no tenen tangents internes # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandeix els guions en camins @msg select paths with dashed strokes to expand seleccioneu camins amb traç discontinu per expandir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..a45d114226 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7365,6 +7365,22 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Společné tečny… + Common Tangents Společné tečny + Tangents Tečny + Centerline Středová čára + External Vnější + Internal Vnitřní +@msg select two closed paths vyberte dvě uzavřené cesty +@msg a selected path is open vybraná cesta je otevřená +@msg a selected path is not convex vybraná cesta není konvexní +@msg a selected path has no area vybraná cesta nemá žádnou plochu +@msg a selected path has more than 10000 segments vybraná cesta má více než 10000 segmentů +@msg the two paths have the same outline obě cesty mají stejný obrys +@msg One path lies inside the other, so they have no common tangents Jedna cesta leží uvnitř druhé, takže nemají žádné společné tečny +@msg The paths overlap, so they have no internal tangents Cesty se překrývají, takže nemají žádné vnitřní tečny +@msg One path lies inside the other, so they have no internal tangents Jedna cesta leží uvnitř druhé, takže nemají žádné vnitřní tečny # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozložit čárky na cesty @msg select paths with dashed strokes to expand vyberte cesty s čárkovaným tahem k rozložení diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..61366b0a61 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7414,6 +7414,22 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Fælles tangenter… + Common Tangents Fælles tangenter + Tangents Tangenter + Centerline Midterlinje + External Ydre + Internal Indre +@msg select two closed paths vælg to lukkede stier +@msg a selected path is open en valgt sti er åben +@msg a selected path is not convex en valgt sti er ikke konveks +@msg a selected path has no area en valgt sti har intet areal +@msg a selected path has more than 10000 segments en valgt sti har mere end 10000 segmenter +@msg the two paths have the same outline de to stier har samme omrids +@msg One path lies inside the other, so they have no common tangents Den ene sti ligger inden i den anden, så de har ingen fælles tangenter +@msg The paths overlap, so they have no internal tangents Stierne overlapper, så de har ingen indre tangenter +@msg One path lies inside the other, so they have no internal tangents Den ene sti ligger inden i den anden, så de har ingen indre tangenter # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Udvid streger til stier @msg select paths with dashed strokes to expand vælg stier med stiplet streg, der skal udvides diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..900e7a9f44 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6956,6 +6956,22 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemeinsame Tangenten… + Common Tangents Gemeinsame Tangenten + Tangents Tangenten + Centerline Mittellinie + External Äußere + Internal Innere +@msg select two closed paths wählen Sie zwei geschlossene Pfade aus +@msg a selected path is open ein ausgewählter Pfad ist offen +@msg a selected path is not convex ein ausgewählter Pfad ist nicht konvex +@msg a selected path has no area ein ausgewählter Pfad hat keine Fläche +@msg a selected path has more than 10000 segments ein ausgewählter Pfad hat mehr als 10000 Segmente +@msg the two paths have the same outline die beiden Pfade haben denselben Umriss +@msg One path lies inside the other, so they have no common tangents Ein Pfad liegt im anderen, daher haben sie keine gemeinsamen Tangenten +@msg The paths overlap, so they have no internal tangents Die Pfade überlappen sich, daher haben sie keine inneren Tangenten +@msg One path lies inside the other, so they have no internal tangents Ein Pfad liegt im anderen, daher haben sie keine inneren Tangenten # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Striche in Pfade umwandeln @msg select paths with dashed strokes to expand wählen Sie Pfade mit gestrichelter Kontur zum Umwandeln aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..473ebd370d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7334,6 +7334,22 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Κοινές εφαπτόμενες… + Common Tangents Κοινές εφαπτόμενες + Tangents Εφαπτόμενες + Centerline Κεντρική γραμμή + External Εξωτερικές + Internal Εσωτερικές +@msg select two closed paths επιλέξτε δύο κλειστές διαδρομές +@msg a selected path is open μια επιλεγμένη διαδρομή είναι ανοιχτή +@msg a selected path is not convex μια επιλεγμένη διαδρομή δεν είναι κυρτή +@msg a selected path has no area μια επιλεγμένη διαδρομή δεν έχει εμβαδόν +@msg a selected path has more than 10000 segments μια επιλεγμένη διαδρομή έχει περισσότερα από 10000 τμήματα +@msg the two paths have the same outline οι δύο διαδρομές έχουν το ίδιο περίγραμμα +@msg One path lies inside the other, so they have no common tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν κοινές εφαπτόμενες +@msg The paths overlap, so they have no internal tangents Οι διαδρομές επικαλύπτονται, επομένως δεν έχουν εσωτερικές εφαπτόμενες +@msg One path lies inside the other, so they have no internal tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν εσωτερικές εφαπτόμενες # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Επέκταση παυλών σε διαδρομές @msg select paths with dashed strokes to expand επιλέξτε διαδρομές με διακεκομμένο περίγραμμα για επέκταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..7b8d2ff82c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7322,6 +7322,22 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes comunes… + Common Tangents Tangentes comunes + Tangents Tangentes + Centerline Línea central + External Externas + Internal Internas +@msg select two closed paths seleccione dos trazados cerrados +@msg a selected path is open un trazado seleccionado está abierto +@msg a selected path is not convex un trazado seleccionado no es convexo +@msg a selected path has no area un trazado seleccionado no tiene área +@msg a selected path has more than 10000 segments un trazado seleccionado tiene más de 10000 segmentos +@msg the two paths have the same outline los dos trazados tienen el mismo contorno +@msg One path lies inside the other, so they have no common tangents Un trazado está dentro del otro, por lo que no tienen tangentes comunes +@msg The paths overlap, so they have no internal tangents Los trazados se superponen, por lo que no tienen tangentes internas +@msg One path lies inside the other, so they have no internal tangents Un trazado está dentro del otro, por lo que no tienen tangentes internas # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir guiones en trazados @msg select paths with dashed strokes to expand seleccione trazados con trazo discontinuo para expandir diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..d5f6177991 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7410,6 +7410,22 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Yhteiset tangentit… + Common Tangents Yhteiset tangentit + Tangents Tangentit + Centerline Keskilinja + External Ulkoiset + Internal Sisäiset +@msg select two closed paths valitse kaksi suljettua polkua +@msg a selected path is open valittu polku on avoin +@msg a selected path is not convex valittu polku ei ole kupera +@msg a selected path has no area valitulla polulla ei ole pinta-alaa +@msg a selected path has more than 10000 segments valitussa polussa on yli 10000 segmenttiä +@msg the two paths have the same outline kahdella polulla on sama ääriviiva +@msg One path lies inside the other, so they have no common tangents Toinen polku on toisen sisällä, joten niillä ei ole yhteisiä tangentteja +@msg The paths overlap, so they have no internal tangents Polut ovat päällekkäin, joten niillä ei ole sisäisiä tangentteja +@msg One path lies inside the other, so they have no internal tangents Toinen polku on toisen sisällä, joten niillä ei ole sisäisiä tangentteja # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Laajenna viivat poluiksi @msg select paths with dashed strokes to expand valitse laajennettavat polut, joissa on katkoviiva diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..7b94c77225 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7360,6 +7360,22 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes communes… + Common Tangents Tangentes communes + Tangents Tangentes + Centerline Ligne médiane + External Externes + Internal Internes +@msg select two closed paths sélectionnez deux tracés fermés +@msg a selected path is open un tracé sélectionné est ouvert +@msg a selected path is not convex un tracé sélectionné n’est pas convexe +@msg a selected path has no area un tracé sélectionné n’a pas de surface +@msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments +@msg the two paths have the same outline les deux tracés ont le même contour +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ff59a464c5..354922218f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2976,6 +2976,22 @@ Remove Effect ઇફેક્ટ દૂર કરો Remove Effects ઇફેક્ટ્સ દૂર કરો Remove Gaps ગેપ દૂર કરો +# Path Precision Tools add-on: Common Tangents. + Common Tangents… સામાન્ય સ્પર્શરેખાઓ… + Common Tangents સામાન્ય સ્પર્શરેખાઓ + Tangents સ્પર્શરેખાઓ + Centerline કેન્દ્ર રેખા + External બાહ્ય + Internal આંતરિક +@msg select two closed paths બે બંધ પાથ પસંદ કરો +@msg a selected path is open પસંદ કરેલો એક પાથ ખુલ્લો છે +@msg a selected path is not convex પસંદ કરેલો એક પાથ બહિર્ગોળ નથી +@msg a selected path has no area પસંદ કરેલા એક પાથનું કોઈ ક્ષેત્રફળ નથી +@msg a selected path has more than 10000 segments પસંદ કરેલા એક પાથમાં 10000 થી વધુ ખંડ છે +@msg the two paths have the same outline બંને પાથની રૂપરેખા સમાન છે +@msg One path lies inside the other, so they have no common tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ સામાન્ય સ્પર્શરેખા નથી +@msg The paths overlap, so they have no internal tangents પાથ એકબીજા પર ચઢેલા છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી +@msg One path lies inside the other, so they have no internal tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી Remove Guide ગાઇડ દૂર કરો Remove Item આઇટમ દૂર કરો Remove JavaScript File JavaScript ફાઇલ દૂર કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..46ea68f4f0 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8040,6 +8040,22 @@ antiAlias Sharp शार्प @msg select paths to join जोड़ने के लिए पाथ सिलेक्ट करें @msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें @msg select paths, or segments, to divide विभाजित करने के लिए पाथ, या खंड चुनें +# Path Precision Tools add-on: Common Tangents. + Common Tangents… उभयनिष्ठ स्पर्शरेखाएँ… + Common Tangents उभयनिष्ठ स्पर्शरेखाएँ + Tangents स्पर्शरेखाएँ + Centerline केंद्र रेखा + External बाहरी + Internal आंतरिक +@msg select two closed paths दो बंद पाथ चुनें +@msg a selected path is open चुना गया एक पाथ खुला है +@msg a selected path is not convex चुना गया एक पाथ उत्तल नहीं है +@msg a selected path has no area चुने गए एक पाथ का कोई क्षेत्रफल नहीं है +@msg a selected path has more than 10000 segments चुने गए एक पाथ में 10000 से अधिक खंड हैं +@msg the two paths have the same outline दोनों पाथ की रूपरेखा एक जैसी है +@msg One path lies inside the other, so they have no common tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई उभयनिष्ठ स्पर्शरेखा नहीं है +@msg The paths overlap, so they have no internal tangents पाथ एक-दूसरे पर चढ़े हुए हैं, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है +@msg One path lies inside the other, so they have no internal tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..a34a41098b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7350,6 +7350,22 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Közös érintők… + Common Tangents Közös érintők + Tangents Érintők + Centerline Középvonal + External Külső + Internal Belső +@msg select two closed paths jelöljön ki két zárt útvonalat +@msg a selected path is open egy kijelölt útvonal nyitott +@msg a selected path is not convex egy kijelölt útvonal nem konvex +@msg a selected path has no area egy kijelölt útvonalnak nincs területe +@msg a selected path has more than 10000 segments egy kijelölt útvonalnak több mint 10000 szakasza van +@msg the two paths have the same outline a két útvonal körvonala azonos +@msg One path lies inside the other, so they have no common tangents Az egyik útvonal a másikon belül van, így nincsenek közös érintőik +@msg The paths overlap, so they have no internal tangents Az útvonalak átfedik egymást, így nincsenek belső érintőik +@msg One path lies inside the other, so they have no internal tangents Az egyik útvonal a másikon belül van, így nincsenek belső érintőik # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Szaggatások kibontása útvonalakká @msg select paths with dashed strokes to expand jelöljön ki szaggatott körvonalú útvonalakat a kibontáshoz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf029526f7..24886713a4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6744,6 +6744,22 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Garis Singgung Persekutuan… + Common Tangents Garis Singgung Persekutuan + Tangents Garis Singgung + Centerline Garis Tengah + External Luar + Internal Dalam +@msg select two closed paths pilih dua jalur tertutup +@msg a selected path is open jalur yang dipilih terbuka +@msg a selected path is not convex jalur yang dipilih tidak cembung +@msg a selected path has no area jalur yang dipilih tidak memiliki luas +@msg a selected path has more than 10000 segments jalur yang dipilih memiliki lebih dari 10000 segmen +@msg the two paths have the same outline kedua jalur memiliki garis luar yang sama +@msg One path lies inside the other, so they have no common tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung persekutuan +@msg The paths overlap, so they have no internal tangents Jalur-jalur saling tumpang tindih, sehingga tidak ada garis singgung dalam +@msg One path lies inside the other, so they have no internal tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung dalam # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Perluas garis putus menjadi jalur @msg select paths with dashed strokes to expand pilih jalur dengan stroke putus-putus yang akan diperluas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..db96ad4a85 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6992,6 +6992,22 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangenti comuni… + Common Tangents Tangenti comuni + Tangents Tangenti + Centerline Linea centrale + External Esterne + Internal Interne +@msg select two closed paths seleziona due tracciati chiusi +@msg a selected path is open un tracciato selezionato è aperto +@msg a selected path is not convex un tracciato selezionato non è convesso +@msg a selected path has no area un tracciato selezionato non ha area +@msg a selected path has more than 10000 segments un tracciato selezionato ha più di 10000 segmenti +@msg the two paths have the same outline i due tracciati hanno lo stesso contorno +@msg One path lies inside the other, so they have no common tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti comuni +@msg The paths overlap, so they have no internal tangents I tracciati si sovrappongono, quindi non hanno tangenti interne +@msg One path lies inside the other, so they have no internal tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Espandi trattini in tracciati @msg select paths with dashed strokes to expand seleziona tracciati con traccia tratteggiata da espandere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..d65f13fbde 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8869,6 +8869,22 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 共通接線… + Common Tangents 共通接線 + Tangents 接線 + Centerline 中心線 + External 外側 + Internal 内側 +@msg select two closed paths 閉じたパスを 2 つ選択してください +@msg a selected path is open 選択したパスが開いています +@msg a selected path is not convex 選択したパスが凸形ではありません +@msg a selected path has no area 選択したパスに面積がありません +@msg a selected path has more than 10000 segments 選択したパスのセグメントが 10000 を超えています +@msg the two paths have the same outline 2 つのパスの輪郭が同じです +@msg One path lies inside the other, so they have no common tangents 一方のパスがもう一方の内側にあるため、共通接線はありません +@msg The paths overlap, so they have no internal tangents パスが重なっているため、内側の接線はありません +@msg One path lies inside the other, so they have no internal tangents 一方のパスがもう一方の内側にあるため、内側の接線はありません # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 破線をパスに拡張 @msg select paths with dashed strokes to expand 拡張する破線のパスを選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..2252de5811 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9481,6 +9481,22 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი ტრაექტორიები ან სეგმენტები +# Path Precision Tools add-on: Common Tangents. + Common Tangents… საერთო მხებები… + Common Tangents საერთო მხებები + Tangents მხებები + Centerline ცენტრალური ხაზი + External გარე + Internal შიდა +@msg select two closed paths აირჩიეთ ორი დახურული ტრაექტორია +@msg a selected path is open არჩეული ტრაექტორია ღიაა +@msg a selected path is not convex არჩეული ტრაექტორია არ არის ამოზნექილი +@msg a selected path has no area არჩეულ ტრაექტორიას ფართობი არ აქვს +@msg a selected path has more than 10000 segments არჩეულ ტრაექტორიას 10000-ზე მეტი სეგმენტი აქვს +@msg the two paths have the same outline ორივე ტრაექტორიას ერთნაირი კონტური აქვს +@msg One path lies inside the other, so they have no common tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ საერთო მხებები არ აქვთ +@msg The paths overlap, so they have no internal tangents ტრაექტორიები ერთმანეთს ფარავს, ამიტომ მათ შიდა მხებები არ აქვთ +@msg One path lies inside the other, so they have no internal tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ შიდა მხებები არ აქვთ # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths ტირეების ტრაექტორიებად გაშლა @msg select paths with dashed strokes to expand აირჩიეთ გასაშლელი ტირეებიანი ხაზის კონტურები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..ed97f43165 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6956,6 +6956,22 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 공통 접선… + Common Tangents 공통 접선 + Tangents 접선 + Centerline 중심선 + External 외부 + Internal 내부 +@msg select two closed paths 닫힌 패스 2개를 선택하십시오 +@msg a selected path is open 선택한 패스가 열려 있습니다 +@msg a selected path is not convex 선택한 패스가 볼록하지 않습니다 +@msg a selected path has no area 선택한 패스에 면적이 없습니다 +@msg a selected path has more than 10000 segments 선택한 패스의 세그먼트가 10000개를 넘습니다 +@msg the two paths have the same outline 두 패스의 윤곽선이 같습니다 +@msg One path lies inside the other, so they have no common tangents 한 패스가 다른 패스 안에 있어 공통 접선이 없습니다 +@msg The paths overlap, so they have no internal tangents 패스가 겹쳐 있어 내부 접선이 없습니다 +@msg One path lies inside the other, so they have no internal tangents 한 패스가 다른 패스 안에 있어 내부 접선이 없습니다 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 대시를 패스로 확장 @msg select paths with dashed strokes to expand 확장할 점선 획의 패스를 선택하십시오 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..d6a5e4a7d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9239,6 +9239,22 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemeenschappelijke raaklijnen… + Common Tangents Gemeenschappelijke raaklijnen + Tangents Raaklijnen + Centerline Middellijn + External Uitwendige + Internal Inwendige +@msg select two closed paths selecteer twee gesloten paden +@msg a selected path is open een geselecteerd pad is open +@msg a selected path is not convex een geselecteerd pad is niet convex +@msg a selected path has no area een geselecteerd pad heeft geen oppervlak +@msg a selected path has more than 10000 segments een geselecteerd pad heeft meer dan 10000 segmenten +@msg the two paths have the same outline de twee paden hebben dezelfde omtrek +@msg One path lies inside the other, so they have no common tangents Het ene pad ligt binnen het andere, dus ze hebben geen gemeenschappelijke raaklijnen +@msg The paths overlap, so they have no internal tangents De paden overlappen, dus ze hebben geen inwendige raaklijnen +@msg One path lies inside the other, so they have no internal tangents Het ene pad ligt binnen het andere, dus ze hebben geen inwendige raaklijnen # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Streepjes uitbreiden tot paden @msg select paths with dashed strokes to expand selecteer paden met een streepjeslijn om uit te breiden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..5ab03b8788 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7221,6 +7221,22 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Wspólne styczne… + Common Tangents Wspólne styczne + Tangents Styczne + Centerline Linia środkowa + External Zewnętrzne + Internal Wewnętrzne +@msg select two closed paths zaznacz dwie zamknięte ścieżki +@msg a selected path is open zaznaczona ścieżka jest otwarta +@msg a selected path is not convex zaznaczona ścieżka nie jest wypukła +@msg a selected path has no area zaznaczona ścieżka nie ma pola +@msg a selected path has more than 10000 segments zaznaczona ścieżka ma więcej niż 10000 segmentów +@msg the two paths have the same outline obie ścieżki mają ten sam kontur +@msg One path lies inside the other, so they have no common tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają wspólnych stycznych +@msg The paths overlap, so they have no internal tangents Ścieżki nachodzą na siebie, więc nie mają stycznych wewnętrznych +@msg One path lies inside the other, so they have no internal tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają stycznych wewnętrznych # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozszerz kreski na ścieżki @msg select paths with dashed strokes to expand zaznacz ścieżki z przerywanym konturem do rozszerzenia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..f7902bd28e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7396,6 +7396,22 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes comuns… + Common Tangents Tangentes comuns + Tangents Tangentes + Centerline Linha central + External Externas + Internal Internas +@msg select two closed paths selecione dois demarcadores fechados +@msg a selected path is open um demarcador selecionado está aberto +@msg a selected path is not convex um demarcador selecionado não é convexo +@msg a selected path has no area um demarcador selecionado não tem área +@msg a selected path has more than 10000 segments um demarcador selecionado tem mais de 10000 segmentos +@msg the two paths have the same outline os dois demarcadores têm o mesmo contorno +@msg One path lies inside the other, so they have no common tangents Um demarcador está dentro do outro, então eles não têm tangentes comuns +@msg The paths overlap, so they have no internal tangents Os demarcadores se sobrepõem, então eles não têm tangentes internas +@msg One path lies inside the other, so they have no internal tangents Um demarcador está dentro do outro, então eles não têm tangentes internas # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir traços em demarcadores @msg select paths with dashed strokes to expand selecione demarcadores com traçado tracejado para expandir diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..cfc654e280 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7355,6 +7355,22 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Общие касательные… + Common Tangents Общие касательные + Tangents Касательные + Centerline Осевая линия + External Внешние + Internal Внутренние +@msg select two closed paths выделите два замкнутых контура +@msg a selected path is open выделенный контур открыт +@msg a selected path is not convex выделенный контур не выпуклый +@msg a selected path has no area выделенный контур не имеет площади +@msg a selected path has more than 10000 segments выделенный контур содержит более 10000 сегментов +@msg the two paths have the same outline у обоих контуров одинаковая форма +@msg One path lies inside the other, so they have no common tangents Один контур лежит внутри другого, поэтому у них нет общих касательных +@msg The paths overlap, so they have no internal tangents Контуры перекрываются, поэтому у них нет внутренних касательных +@msg One path lies inside the other, so they have no internal tangents Один контур лежит внутри другого, поэтому у них нет внутренних касательных # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разобрать штрихи на контуры @msg select paths with dashed strokes to expand выделите контуры со штриховой обводкой для разбора diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..4bae8c282f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7381,6 +7381,22 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemensamma tangenter… + Common Tangents Gemensamma tangenter + Tangents Tangenter + Centerline Mittlinje + External Yttre + Internal Inre +@msg select two closed paths markera två slutna banor +@msg a selected path is open en markerad bana är öppen +@msg a selected path is not convex en markerad bana är inte konvex +@msg a selected path has no area en markerad bana har ingen yta +@msg a selected path has more than 10000 segments en markerad bana har fler än 10000 segment +@msg the two paths have the same outline de två banorna har samma kontur +@msg One path lies inside the other, so they have no common tangents Den ena banan ligger inuti den andra, så de har inga gemensamma tangenter +@msg The paths overlap, so they have no internal tangents Banorna överlappar, så de har inga inre tangenter +@msg One path lies inside the other, so they have no internal tangents Den ena banan ligger inuti den andra, så de har inga inre tangenter # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandera streck till banor @msg select paths with dashed strokes to expand markera banor med streckad kontur att expandera diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..105580e29e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9243,6 +9243,22 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Ortak Teğetler… + Common Tangents Ortak Teğetler + Tangents Teğetler + Centerline Merkez Çizgisi + External Dış + Internal İç +@msg select two closed paths iki kapalı yol seçin +@msg a selected path is open seçili bir yol açık +@msg a selected path is not convex seçili bir yol dışbükey değil +@msg a selected path has no area seçili bir yolun alanı yok +@msg a selected path has more than 10000 segments seçili bir yolun 10000'den fazla bölümü var +@msg the two paths have the same outline iki yolun ana hattı aynı +@msg One path lies inside the other, so they have no common tangents Bir yol diğerinin içinde, bu yüzden ortak teğetleri yok +@msg The paths overlap, so they have no internal tangents Yollar örtüşüyor, bu yüzden iç teğetleri yok +@msg One path lies inside the other, so they have no internal tangents Bir yol diğerinin içinde, bu yüzden iç teğetleri yok # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Tireleri Yollara Genişlet @msg select paths with dashed strokes to expand genişletilecek kesikli konturlu yolları seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..e03a5d3d67 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6974,6 +6974,22 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Спільні дотичні… + Common Tangents Спільні дотичні + Tangents Дотичні + Centerline Осьова лінія + External Зовнішні + Internal Внутрішні +@msg select two closed paths виділіть два замкнені контури +@msg a selected path is open виділений контур відкритий +@msg a selected path is not convex виділений контур не опуклий +@msg a selected path has no area виділений контур не має площі +@msg a selected path has more than 10000 segments виділений контур містить понад 10000 сегментів +@msg the two paths have the same outline обидва контури мають однакову форму +@msg One path lies inside the other, so they have no common tangents Один контур лежить усередині іншого, тому вони не мають спільних дотичних +@msg The paths overlap, so they have no internal tangents Контури перекриваються, тому вони не мають внутрішніх дотичних +@msg One path lies inside the other, so they have no internal tangents Один контур лежить усередині іншого, тому вони не мають внутрішніх дотичних # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Розібрати штрихи на контури @msg select paths with dashed strokes to expand виділіть контури зі штриховим обведенням для розбору diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..41c52ef996 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6991,6 +6991,22 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tiếp tuyến chung… + Common Tangents Tiếp tuyến chung + Tangents Tiếp tuyến + Centerline Đường tâm + External Ngoài + Internal Trong +@msg select two closed paths chọn hai đường dẫn khép kín +@msg a selected path is open một đường dẫn đã chọn đang mở +@msg a selected path is not convex một đường dẫn đã chọn không lồi +@msg a selected path has no area một đường dẫn đã chọn không có diện tích +@msg a selected path has more than 10000 segments một đường dẫn đã chọn có hơn 10000 đoạn +@msg the two paths have the same outline hai đường dẫn có cùng đường viền +@msg One path lies inside the other, so they have no common tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến chung +@msg The paths overlap, so they have no internal tangents Các đường dẫn chồng lên nhau, nên chúng không có tiếp tuyến trong +@msg One path lies inside the other, so they have no internal tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến trong # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Mở rộng nét đứt thành đường dẫn @msg select paths with dashed strokes to expand chọn các đường dẫn có nét đứt để mở rộng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..7dd53fdc00 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7206,6 +7206,22 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 公切线… + Common Tangents 公切线 + Tangents 切线 + Centerline 中心线 + External 外部 + Internal 内部 +@msg select two closed paths 请选择两条闭合路径 +@msg a selected path is open 所选路径是开放的 +@msg a selected path is not convex 所选路径不是凸形 +@msg a selected path has no area 所选路径没有面积 +@msg a selected path has more than 10000 segments 所选路径的线段超过 10000 条 +@msg the two paths have the same outline 两条路径的轮廓相同 +@msg One path lies inside the other, so they have no common tangents 一条路径位于另一条之内,因此它们没有公切线 +@msg The paths overlap, so they have no internal tangents 路径相互重叠,因此它们没有内公切线 +@msg One path lies inside the other, so they have no internal tangents 一条路径位于另一条之内,因此它们没有内公切线 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 将短划线扩展为路径 @msg select paths with dashed strokes to expand 请选择要扩展的虚线描边路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..732301f843 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7015,6 +7015,22 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 公切線… + Common Tangents 公切線 + Tangents 切線 + Centerline 中心線 + External 外部 + Internal 內部 +@msg select two closed paths 請選取兩條封閉路徑 +@msg a selected path is open 所選路徑是開放的 +@msg a selected path is not convex 所選路徑不是凸形 +@msg a selected path has no area 所選路徑沒有面積 +@msg a selected path has more than 10000 segments 所選路徑的線段超過 10000 條 +@msg the two paths have the same outline 兩條路徑的輪廓相同 +@msg One path lies inside the other, so they have no common tangents 一條路徑位於另一條之內,因此它們沒有公切線 +@msg The paths overlap, so they have no internal tangents 路徑互相重疊,因此它們沒有內公切線 +@msg One path lies inside the other, so they have no internal tangents 一條路徑位於另一條之內,因此它們沒有內公切線 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 將短破折號展開為路徑 @msg select paths with dashed strokes to expand 請選取要展開的虛線筆畫路徑 diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..fbf67e9c22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11965,6 +11965,26 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). +- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed + paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into + either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) + or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or + a path's center of area. Each tangent of paths that do not touch runs from where it touches the lower path to + where it touches the upper one; where a straight side of a path lies along the line, the line covers the whole + side. An ellipse drawn with the Ellipse tool, then moved, turned or scaled, is measured as an exact ellipse. Any + other path must be closed, have one outline, bend the same way all around and have at most 10,000 segments; an open + path, a path that bends inward, a path without area, a group, a compound path or type is refused, and so are two + paths whose outlines are the same to within the touching tolerance given below. Two separate paths have two + external and two internal tangents. Overlapping paths have external tangents only. A path inside the other has + none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point + where they touch and as long as the narrower path is wide along it. Paths that meet at a corner or along a shared + stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when + the gap between them is less than the tolerance, a billionth of the larger of their sizes and the distance between + their centers. The lines are stroked with the current stroke color and weight (black when the stroke is None), have + no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of + the kind asked for, nothing changes, and the result's `warning` says why. Common Tangents… + opens a dialog (Tangents, Centerline) with Preview. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; @@ -11978,6 +11998,7 @@ plain path from then on. {"name":"run_command","arguments":{"command":"addon.pathtools.crossings","params":{"cut":true}}} {"name":"run_command","arguments":{"command":"addon.pathtools.shape.create","params":{"kind":"star","center":[200,150],"width":120,"height":120,"count":7,"a":0.4}}} {"name":"run_command","arguments":{"command":"addon.pathtools.shape.set","params":{"id":14,"kind":"gear","count":16,"radius":2}}} +{"name":"run_command","arguments":{"command":"addon.pathtools.commonTangents","params":{"ids":[3,4],"tangents":"external","centerline":true}}} ``` ### Path Effects (live) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..c003439bb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2453,6 +2453,10 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Nest Shapes… (`addon.cutting.nest`) moves the selected objects close together onto a sheet or a roll of material ([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The rest is VectorCraft's own: the sheet is an artboard, or a set width and height from its top-left corner, and a roll is a set width with no end; a margin is kept inside the edges and a spacing between objects. Objects are packed by their bounding boxes, with or without strokes and effects (shadows, glows and blurs included), the tallest first, each where its bottom edge is highest and then furthest left; with Rotate an object may turn 90° where that places it higher or where only the turned object fits. Objects that do not fit go in a column to the right of the sheet, in stacking order. The command is one undo step, and its result gives the length of material used. The dialog has Preview. Tests: `cmd::addons::cutting::nest::tests` in `vectorcraft-engine`, `nest_shapes_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Nest Shapes. +## Path Precision Tools add-on: Common Tangents (2026-11-15) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. From 9597392c452b174d37c7a945a004f1b01edf9870 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 14:52:41 -0800 Subject: [PATCH 24/50] PSD export: slices are written, so an opened PSD's slices survive an export A PSD export now writes image resource 1050 in version 6 of the PSD file format specification's slices resource format, the form that Import Slices reads (crates/engine/src/cmd/fileio/psdslices.rs, version_6). Flat and layered exports both carry it. - The user and object slices that reach into the exported artboard are written, clipped to it in its pixels, at least one pixel each way. Auto slices are left out; opening the file lays them out again. - An object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text as HTML. Name, type, link, target, message, alternative text, cell text and background color are kept; text alignment is written as the default. - Slice IDs count from 1. - More than 10000 slices or a text longer than 65536 characters is an export error, matching the reader's limits. A slice without finite bounds, or slices that would make the resource longer than 4 GB, is also an export error; the size is checked before each text is added. --- crates/engine/src/cmd/fileio/formats.rs | 2 +- .../engine/src/cmd/fileio/tests_psdslices.rs | 72 ++++++++ crates/render/src/encode/psd.rs | 170 +++++++++++++++++- crates/render/src/encode/tests_psd.rs | 124 ++++++++++++- docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 6 files changed, 370 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 75b202c8ab..ad8f9bb5e5 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption { name: "layers", ty: "boolean", default: "true", - description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent", + description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way", }; const MAX_EDITABILITY: FormatOption = FormatOption { diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 2d8d0c951f..e504e5f6a2 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -506,3 +506,75 @@ fn damaged_slices_never_panic() { } } } + +/// The PSD file `document.export` writes from `s`, with its layers or flat. +fn export(s: &mut Session, layers: bool) -> Vec { + let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +#[test] +fn an_opened_files_slices_survive_a_psd_export() { + let link = + S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) }; + let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) }; + let html = S { kind: 0, html: true, cell: "Hi", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) }; + let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) }; + let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[])); + let (mut s, _) = open(&f, json!({})); + let opened = slices(&s); + assert_eq!(opened.len(), 3); + for layers in [true, false] { + let out = export(&mut s, layers); + let (again, r) = open(&out, json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + // The same rectangles and options; the auto slices are laid out again around them. + let mut got = slices(&again); + let mut want = opened.clone(); + let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0))); + order(&mut got); + order(&mut want); + assert_eq!(got, want); + let layout = again.doc().unwrap().doc.slice_layout(); + assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto)); + assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3)); + } +} + +#[test] +fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + let rect = r["id"].as_u64().unwrap(); + s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "x", "background": "#00ff00"})).unwrap(); + let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.slice.make", &json!({"ids": [t]})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap(); + let (again, _) = open(&export(&mut s, false), json!({})); + let got = slices(&again); + assert_eq!(got.len(), 2, "{got:?}"); + let doc = &s.doc().unwrap().doc; + let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap(); + let boxed = got.iter().find(|g| g.1.name == "box").unwrap(); + // Within a pixel of the object's bounds. + for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] { + assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0); + } + assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "x", "#00ff00")); + let text = got.iter().find(|g| g.1.name.is_empty()).unwrap(); + assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A & B")); +} + +#[test] +fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() { + let columns: Vec = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect(); + let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({})); + assert_eq!(slices(&s).len(), 20); + let (again, r) = open(&export(&mut s, true), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&again), slices(&s)); +} diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 98c031c89a..6dc3f4b98e 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -1,13 +1,14 @@ //! PSD export: a layered bitmap at 8 bits per channel, written from the format's public -//! specification. The file holds the header, the resolution and colour profile resources, the -//! layer records and their channels (PackBits row by row; groups as section dividers), then the +//! specification. The file holds the header, the resolution, colour profile and slices resources, +//! the layer records and their channels (PackBits row by row; groups as section dividers), then the //! merged image, which readers that skip layers show. RGB, CMYK (stored as 255 − ink, as the //! format keeps inks) or grayscale. +use std::collections::HashMap; use std::sync::Arc; use vectorcraft_color::{BlendMode, cms}; -use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind}; +use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource}; use vectorcraft_geom::Rect; use super::jpeg::{self, ColorModel}; @@ -289,6 +290,8 @@ struct File { records: Vec, ppi: f64, icc: Option>, + /// Image resource 1050's data, when the file has slices. + slices: Option>, } /// Refuse a size the format can't store. @@ -319,7 +322,8 @@ impl File { out.extend(mode(self.model).to_be_bytes()); // No colour mode data. out.extend(0u32.to_be_bytes()); - // Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the profile. + // Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the + // profile, the slices. let ppi = if self.ppi.is_finite() && self.ppi > 0.0 { self.ppi } else { 72.0 }; let fixed = (ppi.min(30_000.0) * 65536.0).round() as u32; let res = [fixed.to_be_bytes(), [0, 1, 0, 1], fixed.to_be_bytes(), [0, 1, 0, 1]].concat(); @@ -328,6 +332,9 @@ impl File { if let Some(icc) = &self.icc { resource(&mut resources, 1039, icc)?; } + if let Some(slices) = &self.slices { + resource(&mut resources, SLICES, slices)?; + } out.extend(len32(resources.len())?.to_be_bytes()); out.extend(resources); self.write_layers(&mut out)?; @@ -377,17 +384,20 @@ fn icc(o: &PsdOptions) -> Result>, String> { pub fn encode(img: &Rendered, ppi: f64, o: &PsdOptions) -> Result, String> { let inks = (o.color_model == ColorModel::Cmyk).then(|| jpeg::separated(img)); let merged = planes(o.color_model, &img.to_straight(), inks.as_deref(), true, false); - File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)? }.write() + File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)?, slices: None } + .write() } /// `region` of `doc` as a PSD with `opts` (see [`PsdOptions`]). The merged image is the export's /// render; with Write Layers each part is also drawn alone as its own layer, cropped to what it -/// paints, its opacity and blend mode in the layer's record. +/// paints, its opacity and blend mode in the layer's record. The user and object slices that reach +/// into `region` are written with or without layers ([`slices`]). pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &RasterExportOptions) -> Result, String> { let o = &opts.psd; let scale = opts.scale(); let (width, height) = crate::region_pixels(region, scale); check_size(width, height)?; + let slices = slices(doc, region, scale, (width, height))?; let ro = opts.render_options(RasterFormat::Psd); let (mut merged, mut alpha) = { let px = r.render_region_with(doc, region, scale, &ro).to_straight(); @@ -413,7 +423,153 @@ pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &Rast merged.pop(); alpha = false; } - File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)? }.write() + File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)?, slices }.write() +} + +/// The image resource that holds the slices. +const SLICES: u16 = 1050; + +/// The most slices one file holds (as many as `document.open` reads). +pub(crate) const MAX_SLICES: usize = 10_000; + +/// The longest text of a slice, in UTF-16 units (as long as `document.open` reads). +pub(crate) const MAX_SLICE_TEXT: usize = 65_536; + +/// Resource 1050's data for the user and object slices of `doc` that reach into `region`, in the +/// "Slices resource format" of the Photoshop File Formats Specification +/// (), version 6: the bounds of all +/// the slices, the group's name, the count, then one record per slice. `None` when no slice +/// reaches into `region`. Each rectangle is the slice as laid out ([`Document::slice_layout`]), +/// clipped to `region` and given in the `size` canvas's pixels at `scale`, at least one pixel +/// each way. Every slice is written as one the user made (origin 2): an object slice keeps its +/// rectangle and options. Auto slices aren't written; a reader lays them out again. An HTML Text +/// slice is written as No Image with its type's text as HTML. Text alignment is written as the +/// default. An error when a slice's bounds aren't finite, or there are more than [`MAX_SLICES`] +/// slices, a text longer than [`MAX_SLICE_TEXT`], or more than 4 GB of slices ([`room`]). +fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Result>, String> { + let users: HashMap = doc.slices.iter().map(|s| (s.id, &s.options)).collect(); + let mut found = vec![]; + for area in doc.slice_layout().iter().filter(|a| a.source != SliceSource::Auto) { + let Some(id) = area.id else { continue }; + let r = area.rect; + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + let number = area.number; + return Err(format!("slice {number} has no finite bounds and can't be written to PSD")); + } + let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue }; + let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max)); + let (l, t, r, b) = (edge(r.x0, region.x0, w), edge(r.y0, region.y0, h), edge(r.x1, region.x0, w), edge(r.y1, region.y0, h)); + if !(l < r && t < b) { + continue; + } + // Whole pixels, at least one each way. + let span = |a: f64, b: f64, max: u32| { + let max = i64::from(max); + let (mut a, mut b) = ((a.round() as i64).clamp(0, max), (b.round() as i64).clamp(0, max)); + if b <= a { + a = a.min(max - 1); + b = a + 1; + } + (a as i32, b as i32) + }; + let ((l, r), (t, b)) = (span(l, r, w), span(t, b, h)); + let text = match options.kind { + SliceKind::HtmlText => doc.node(id).map(html_text).unwrap_or_default(), + _ => options.text.clone(), + }; + found.push(([l, t, r, b], options, text)); + } + if found.is_empty() { + return Ok(None); + } + if found.len() > MAX_SLICES { + let count = found.len(); + return Err(format!("the document has {count} slices, more than the {MAX_SLICES} a PSD file holds")); + } + let (mut top, mut left, mut bottom, mut right) = (i32::MAX, i32::MAX, 0, 0); + for ([l, t, r, b], _, _) in &found { + (left, top, right, bottom) = (left.min(*l), top.min(*t), right.max(*r), bottom.max(*b)); + } + let mut out = 6u32.to_be_bytes().to_vec(); + for v in [top, left, bottom, right] { + out.extend(v.to_be_bytes()); + } + let stem = doc.title.rsplit_once('.').map_or(doc.title.as_str(), |(s, _)| s); + unicode(&mut out, stem)?; + out.extend((found.len() as u32).to_be_bytes()); + // IDs from 1. + for ((rect, o, text), id) in found.into_iter().zip(1u32..) { + out.extend(id.to_be_bytes()); + // Group 0; made by the user. + out.extend(0u32.to_be_bytes()); + out.extend(2u32.to_be_bytes()); + unicode(&mut out, &o.name)?; + out.extend(u32::from(o.kind == SliceKind::Image).to_be_bytes()); + for v in rect { + out.extend(v.to_be_bytes()); + } + for s in [&o.url, &o.target, &o.message, &o.alt] { + unicode(&mut out, s)?; + } + // The cell text is HTML, as a No Image slice shows it. + out.push(1); + unicode(&mut out, &text)?; + // The default horizontal and vertical alignment. + out.extend([0; 8]); + out.extend(background(o)); + } + Ok(Some(out)) +} + +/// A slice's background as alpha, red, green and blue: none (all 0), the matte (alpha 0 over a +/// colour) or an opaque `#rrggbb`. +fn background(o: &SliceOptions) -> [u8; 4] { + let bg = o.background.trim(); + if bg.eq_ignore_ascii_case("matte") { + return [0, 255, 255, 255]; + } + let hex = bg.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit())); + match hex.and_then(|h| u32::from_str_radix(h, 16).ok()) { + Some(c) => { + let [_, r, g, b] = c.to_be_bytes(); + [255, r, g, b] + } + None => [0; 4], + } +} + +/// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a +/// line break as `
`. Empty for anything but type. +fn html_text(n: &Node) -> String { + let NodeKind::Text(t) = &n.kind else { return String::new() }; + t.plain_text() + .split(['\n', '\r', '\u{2029}']) + .map(|l| l.replace('&', "&").replace('<', "<").replace('>', ">")) + .collect::>() + .join("
") +} + +/// `s` as a Unicode string: a count of UTF-16 units, then the units. An error past +/// [`MAX_SLICE_TEXT`] units, or when the string would take `out` past [`room`]. +fn unicode(out: &mut Vec, s: &str) -> Result<(), String> { + let units = s.encode_utf16().count(); + if units > MAX_SLICE_TEXT { + return Err(format!("a slice's text has more than the {MAX_SLICE_TEXT} characters a PSD file holds")); + } + room(out.len(), units)?; + out.extend((units as u32).to_be_bytes()); + out.extend(s.encode_utf16().flat_map(|u| u.to_be_bytes())); + Ok(()) +} + +/// An error when `units` UTF-16 units and their count, added to a slices resource of `len` bytes, +/// make it longer than the 4 GB a PSD resource holds. +pub(crate) fn room(len: usize, units: usize) -> Result<(), String> { + let end = units.checked_mul(2).and_then(|n| n.checked_add(4)).and_then(|n| n.checked_add(len)); + match end.map(u32::try_from) { + Some(Ok(_)) => Ok(()), + _ => Err("the slices are too large for PSD (at most 4 GB)".into()), + } } /// Draws the parts of a document as layer records, bottom first. diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index e2df72e01c..d242b3c7e5 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -1,15 +1,16 @@ //! PSD export: the header, the layer records (names, bounds, opacity, blend modes, groups, -//! hidden layers), the merged image, the colour models, and a reader's view of the file. +//! hidden layers), the merged image, the colour models, the slices, and a reader's view of the +//! file. use std::sync::Arc; use vectorcraft_color::{BlendMode, Color}; -use vectorcraft_doc::{Document, LayerColor, Node}; +use vectorcraft_doc::{Document, LayerColor, Node, NodeId, Slice, SliceKind, SliceOptions}; use vectorcraft_geom::Rect; use vectorcraft_testkit::fixtures::DocBuilder; use super::jpeg::ColorModel; -use super::psd::{MAX_SIDE, PsdOptions}; +use super::psd::{MAX_SIDE, MAX_SLICE_TEXT, MAX_SLICES, PsdOptions, room}; use super::*; /// A 100 × 60 pt document: a red square on Layer 1, and on "Top" a half-opaque blue multiply @@ -365,3 +366,120 @@ fn long_unicode_name_is_cut_on_a_character_boundary() { let file = export(&b.build(), &opts(PsdOptions::default())); assert_eq!(parse(&file).records.last().unwrap().name, "a".repeat(254)); } + +/// `doc()` with a user slice over (20, 5)–(50, 15) and the red square made an object slice. +fn sliced() -> Document { + let mut d = doc(); + let red = d.layers[0].children().unwrap()[0].id; + let user = SliceOptions { + name: "banner".into(), + url: "https://example.com/".into(), + target: "_blank".into(), + message: "Go".into(), + alt: "Banner".into(), + background: "#123456".into(), + ..SliceOptions::default() + }; + let id = d.alloc_id(); + d.slices.push(Slice { id, rect: Rect::new(20.0, 5.0, 50.0, 15.0), options: user }); + let cell = SliceOptions { kind: SliceKind::NoImage, text: "Hi".into(), background: "matte".into(), ..SliceOptions::default() }; + d.node_mut(red).unwrap().extras_mut().slice = Some(Box::new(cell)); + d +} + +/// The slices resource of `file` as an independent reader reads it. +fn slices_of(file: &[u8]) -> Option { + let psd = craft_psd::PsdFile::from_bytes(file).expect("a PSD a reader takes"); + psd.resource(1050).map(|r| craft_psd::slices::SlicesResource::from_bytes(&r.data).expect("a slices resource a reader takes")) +} + +#[test] +fn slices_are_written_with_or_without_layers() { + let d = sliced(); + for layers in [true, false] { + let file = export(&d, &opts(PsdOptions { layers, ..PsdOptions::default() })); + let res = slices_of(&file).expect("the slices resource"); + assert_eq!((res.version, res.bounds, res.group_name.as_str()), (6, [5, 10, 40, 50], "Untitled-1")); + let s = &res.slices; + assert_eq!(s.len(), 2, "{s:?}"); + // Laid out top to bottom: the user slice, then the object slice, both written as made by + // the user. + let user = &s[0]; + assert_eq!((user.id, user.origin, user.layer_id, user.kind, user.rect), (1, 2, None, 1, [20, 5, 50, 15])); + assert_eq!( + (user.name.as_str(), user.url.as_str(), user.target.as_str(), user.message.as_str(), user.alt.as_str()), + ("banner", "https://example.com/", "_blank", "Go", "Banner") + ); + assert_eq!(user.color, [255, 0x12, 0x34, 0x56]); + let cell = &s[1]; + assert_eq!((cell.id, cell.origin, cell.kind, cell.rect), (2, 2, 0, [10, 10, 40, 40])); + assert_eq!((cell.name.as_str(), cell.cell_text.as_str(), cell.cell_text_is_html), ("", "Hi", true)); + assert_eq!((cell.color[0], cell.color[1..].iter().any(|c| *c != 0)), (0, true), "the matte"); + assert_eq!((cell.horizontal_align, cell.vertical_align), (0, 0)); + } + // A document without slices has no slices resource. + assert!(slices_of(&export(&doc(), &opts(PsdOptions::default()))).is_none()); +} + +#[test] +fn slices_are_cut_to_the_exported_region_in_its_pixels() { + let doc = sliced(); + // The right part at 2 px a point: the user slice is cut at the region's left edge, and the red + // square's slice ends at that edge. + let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) }; + let file = Renderer::new().export_region(&doc, Rect::new(40.0, 0.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap(); + let res = slices_of(&file).unwrap(); + assert_eq!(res.slices.iter().map(|s| s.rect).collect::>(), [[0, 10, 20, 30]]); + assert_eq!(res.bounds, [10, 0, 30, 20]); + // A region no slice reaches has none. + let file = Renderer::new().export_region(&doc, Rect::new(60.0, 30.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap(); + assert!(slices_of(&file).is_none()); + // A slice thinner than a pixel keeps one pixel. + let mut thin = doc.clone(); + thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0); + let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap(); + assert_eq!(res.slices[0].rect, [20, 5, 21, 15]); +} + +#[test] +fn slice_ids_count_from_1_and_the_limits_are_errors() { + let mut doc = doc(); + for i in 0..20 { + let id = doc.alloc_id(); + let x = f64::from(i) * 5.0; + doc.slices.push(Slice { id, rect: Rect::new(x, 0.0, x + 5.0, 5.0), options: SliceOptions::default() }); + } + let res = slices_of(&export(&doc, &opts(PsdOptions::default()))).unwrap(); + let ids: Vec = res.slices.iter().map(|s| s.id).collect(); + assert_eq!(ids, (1..=20).collect::>()); + let export_err = |d: &Document| { + Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::Psd, &opts(PsdOptions::default())).err().unwrap_or_default() + }; + let mut long = doc.clone(); + long.slices[0].options.alt = "a".repeat(MAX_SLICE_TEXT + 1); + let e = export_err(&long); + assert!(e.contains("characters"), "{e}"); + let mut many = doc.clone(); + many.slices = (0..=MAX_SLICES as u64) + .map(|i| Slice { id: NodeId(1_000_000 + i), rect: Rect::new(0.0, 0.0, 5.0, 5.0), options: SliceOptions::default() }) + .collect(); + let e = export_err(&many); + assert!(e.contains("slices"), "{e}"); + // Not clipped to the artboard, a slice keeps bounds that aren't finite. + let mut bad = doc; + bad.slices_clip_to_artboard = false; + bad.slices[0].rect = Rect::new(f64::NAN, 0.0, 5.0, 5.0); + let e = export_err(&bad); + assert!(e.contains("finite"), "{e}"); +} + +#[test] +fn slices_past_4_gb_are_an_error_before_they_are_written() { + let max = u32::MAX as usize; + assert_eq!(room(0, MAX_SLICE_TEXT), Ok(())); + assert_eq!(room(max - 4 - 2 * 10, 10), Ok(())); + let e = room(max - 4 - 2 * 10, 11).err().unwrap_or_default(); + assert!(e.contains("4 GB"), "{e}"); + assert!(room(max, 0).is_err()); + assert!(room(0, usize::MAX).is_err()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 7bbc2f4cb7..6d3b606b22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8683,6 +8683,18 @@ appearance of their own or knockout stay one pixel layer. Hidden layers and obje `hiddenLayers: true` writes them as hidden layers. `layers: false` writes one flat image, on white where nothing is drawn. Files are at most 30000 pixels a side. +With or without layers, the file keeps the document's slices in image resource 1050, in version 6 of the slices +resource format of the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/). +`importSlices` reads that form, so the slices of an opened PSD file come back when the export is opened. The rest are +VectorCraft's own rules: + +- The user and object slices that reach into the exported artboard are written, each clipped to it, in its pixels, + at least one pixel each way. Auto slices aren't written; the document that opens the file lays them out again. +- An object slice is written as a user slice over its object's bounds. Each slice keeps its name, its type (Image + or No Image), its link, target, message, alternative text, cell text and background color. An HTML Text slice is + written as No Image with its type's text as HTML. Text alignment is written as the default. +- More than 10000 slices, a slice text longer than 65536 characters, or a slice without finite bounds is an error. + PSD files (`.psd`, and `.psb`, the large document format) place as their merged image, the flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 21b0074bbd..e7eac36226 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1899,6 +1899,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` keep the clip group, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). + - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). From 6a692299d0aab58cd455506bab1038adcaac4423 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:36:55 -0800 Subject: [PATCH 25/50] Tool overlays: long drags keep their line in shared pieces instead of rebuilding it every frame The line that a round Eraser, the Knife, the Path Eraser, the Pencil with Live preview off or a smoothing drag shows was one path of every point, copied, flattened and tessellated again each frame, and with the Eraser's Size following the pen each step was a new path each frame. - A drag of more than 64 segments now shows in pieces of 64 segments, each also holding the next piece's first segment so wide lines join as one. Pieces the drag has passed come back as the same shared path, and the canvas reuses their triangles while the view stays the same; only the last piece is built again, and only when it changed. - With Size following the pen, each step is kept as its own shared path and only a new or moved step is built. - The Knife's pieces carry where the dash pattern starts, so the dashes run on across pieces (Overlay::SharedPath gains `dash`). - The smoothing band is shared until it changes. The canvas still copies the kept triangles into each frame. Release commands (path.eraseRegion, path.knife, path.eraseSegments, path.freehand) are unchanged. --- crates/tools/src/draw2/gesture.rs | 49 ++++++-- crates/tools/src/draw2/gesture/line.rs | 149 ++++++++++++++++++++++++ crates/tools/src/draw2/gesture/tests.rs | 112 +++++++++++++++++- crates/tools/src/lib.rs | 11 +- crates/ui-egui/src/canvas/overlays.rs | 73 ++++++++++-- crates/ui-egui/src/canvas/tests.rs | 60 +++++++++- docs/target-app-parity.md | 2 +- 7 files changed, 428 insertions(+), 28 deletions(-) create mode 100644 crates/tools/src/draw2/gesture/line.rs diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 7d6f997cf9..790beaa0d6 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -27,9 +27,11 @@ //! line to 45° steps from the canvas axes. mod area; +mod line; use std::cell::Cell; use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::{Calligraphic, Variation}; @@ -41,6 +43,7 @@ use super::{FEEDBACK, blob_area, blob_tip, eraser_tip, points_json, polyline}; use crate::guides::DrawSnap; use crate::{Action, Cursor, Mods, Overlay, PenPose, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use area::{AreaKey, AreaPreview}; +use line::LinePreview; /// How far from its drag the Smooth tool smooths, in screen pixels. Alt smoothing with the /// Pencil, Paintbrush or Blob Brush uses the same radius. @@ -205,6 +208,8 @@ pub struct GestureTool { band: Cell>, /// The band last shown does not cover the whole drag yet; the next call adds to it. band_pending: Cell, + /// The pieces of a long drag's line shown so far ([`LinePreview`]). + line: Cell>, } /// The band a smoothing drag smooths, for the drag's first `used` points at `radius`, kept as its @@ -227,8 +232,8 @@ struct SmoothBand { dirty_long: BTreeSet, /// The band changed since `shown` was made. changed: bool, - /// The outline last finished. - shown: Option, + /// The outline last finished, shared with the overlays that show it until it is made again. + shown: Option>, /// The work done on long segments in the current call ([`BAND_WORK_PER_CALL`]). work: usize, } @@ -484,7 +489,7 @@ impl SmoothBand { /// The band's outline: the last one finished. While the band has changed since, the parts it /// changed are made again, until [`BAND_WORK_PER_CALL`] is spent in the call; when all are /// made, the outline is joined from them ([`SmoothBand::make_outline`]). - fn outline(&mut self) -> Option { + fn outline(&mut self) -> Option> { while self.changed { if !self.dirty_tiles.is_empty() || !self.dirty_long.is_empty() { if self.work >= BAND_WORK_PER_CALL { @@ -504,7 +509,7 @@ impl SmoothBand { } } } else { - self.shown = Some(self.make_outline()); + self.shown = Some(Arc::new(self.make_outline())); self.changed = false; } } @@ -889,6 +894,7 @@ impl GestureTool { area_pending: Cell::new(false), band: Cell::new(None), band_pending: Cell::new(false), + line: Cell::new(None), } } @@ -1076,6 +1082,7 @@ impl GestureTool { self.area_pending.set(false); self.band.set(None); self.band_pending.set(false); + self.line.set(None); } /// The outline of the band a smoothing drag smooths: every point within `radius` of the drag, @@ -1088,8 +1095,9 @@ impl GestureTool { /// outside the squares, and one whose outlines cannot be combined adds nothing. Either way the /// band goes on past it. The work on such long segments stops for the call once /// [`BAND_WORK_PER_CALL`] is spent, and the drag is added to the band only once the outline of - /// what it holds is finished. - fn smooth_band(&self, radius: f64) -> Option { + /// what it holds is finished. The outline is the same shared path from one call to the next + /// until the band changes. + fn smooth_band(&self, radius: f64) -> Option> { let pts = &self.points; let &first = pts.first()?; let mut b = self @@ -1744,7 +1752,7 @@ impl Tool for GestureTool { && has_selected_smooth_path(cx) && let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS)) { - o.push(Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: true }); + o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) }); } // A Blob Brush drag that smooths shows the Smooth tool's thin line. let width = match self.id { @@ -1777,17 +1785,34 @@ impl Tool for GestureTool { let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }]; area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j))); let paths = area.paths(&self.points); - o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 })); + o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None })); 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 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 }); + // tip the pen gives at its ends. A long drag's steps are kept from call to call + // ([`LinePreview::segments`]). + let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32; + if self.points.len() > line::PIECE_SEGMENTS + 1 { + let mut kept = self.line.take().unwrap_or_default(); + for (j, path) in kept.segments(&self.points).into_iter().enumerate() { + o.push(Overlay::SharedPath { path, color, width: width_of(j), dash: None }); + } + self.line.set(Some(kept)); + } else { + for (j, seg) in self.points.windows(2).enumerate() { + o.push(Overlay::Path { path: polyline(seg), color, width: width_of(j), dashed: false }); + } } + } else if self.points.len() > line::PIECE_SEGMENTS + 1 { + // A long drag's line shows in pieces kept from call to call ([`LinePreview::pieces`]). + let mut kept = self.line.take().unwrap_or_default(); + let dashed = self.id == "knife"; + for piece in kept.pieces(&self.points) { + o.push(Overlay::SharedPath { path: piece.path, color, width, dash: dashed.then_some(piece.along) }); + } + self.line.set(Some(kept)); } else { o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" }); } diff --git a/crates/tools/src/draw2/gesture/line.rs b/crates/tools/src/draw2/gesture/line.rs new file mode 100644 index 0000000000..60c10d538f --- /dev/null +++ b/crates/tools/src/draw2/gesture/line.rs @@ -0,0 +1,149 @@ +//! The line a drag shows while it is dragged where it does not show the area its tip covers (a +//! round Eraser tip, the Knife, the Pencil with Live preview off, a smoothing drag), kept in +//! pieces that later calls return again unchanged. +//! +//! A drag of more than [`PIECE_SEGMENTS`] segments is cut into pieces of that many segments, each +//! also holding the first segment of the next piece, so that a wide line turns at a piece's last +//! point as one line does. A piece the drag has gone past is built once and returned again as the +//! same shared path; only the last piece is built again, and only when the drag changed it. With +//! Size on a mode that follows the pen each segment shows at its own width, so each segment is +//! kept as its own path, and only a segment whose ends moved is built again. + +use std::sync::Arc; + +use vectorcraft_geom::{BezPath, Point}; + +use super::super::polyline; + +/// The most segments of a drag that one piece of its line holds besides the first segment of the +/// next piece. +pub(super) const PIECE_SEGMENTS: usize = 64; + +/// A piece of the line: the drag's points `from` to `to`. +struct Piece { + path: Arc, + from: usize, + to: usize, + /// The drag's point `to` when the piece was built. + end: Point, + /// The length of the line before `from`. + along: f64, +} + +/// A piece of the line to show ([`LinePreview::pieces`]). +pub(super) struct LinePiece { + /// The same shared path as in the call before while the piece did not change. + pub path: Arc, + /// The length of the line before the piece, where a dashed line's pattern goes on. + pub along: f64, +} + +/// The pieces of a long drag's line, as far as they are built. +#[derive(Default)] +pub(super) struct LinePreview { + /// The pieces the drag has gone past, in order. + settled: Vec, + /// The last piece, up to the drag's last point. + last: Option, + /// Each segment of the drag as its own path, with the points it runs between. + segments: Vec<(Point, Point, Arc)>, + /// The points copied into new paths by the last call. + built: usize, +} + +impl LinePreview { + /// The points copied into new paths by the last call. + #[cfg(test)] + pub(super) fn built(&self) -> usize { + self.built + } + + /// The pieces of the line through `pts`: the pieces kept from the call before while the drag + /// still runs through their points, and new ones for the rest. + pub(super) fn pieces(&mut self, pts: &[Point]) -> Vec { + self.built = 0; + // The drag no longer runs through the points of a kept piece (another drag, or a drag + // made again from its press). + let runs_through = + |p: &Piece| pts.get(p.to) == Some(&p.end) && p.path.elements().first().and_then(|e| e.end_point()) == pts.get(p.from).copied(); + if let Some(k) = self.settled.iter().position(|p| !runs_through(p)) { + self.settled.truncate(k); + self.last = None; + } + // A piece settles once the drag has gone past its last point, which can still move. + loop { + let from = self.settled.len() * PIECE_SEGMENTS; + let to = from + PIECE_SEGMENTS + 1; + if to + 1 >= pts.len() { + break; + } + let along = self.along_next(pts); + let piece = match self.last.take().filter(|p| p.from == from && p.to == to && runs_through(p)) { + Some(p) => p, + None => self.build(pts, from, to, along), + }; + self.settled.push(piece); + } + let from = self.settled.len() * PIECE_SEGMENTS; + let to = pts.len().saturating_sub(1); + if to > from { + let along = self.along_next(pts); + // The last piece's points other than its last can change only with its last one, or + // with the drag's length. + let kept = self.last.take().filter(|p| p.from == from && p.to == to && pts.get(from..=to).is_some_and(|run| same_points(&p.path, run))); + self.last = Some(match kept { + Some(p) => p, + None => self.build(pts, from, to, along), + }); + } else { + self.last = None; + } + self.settled.iter().chain(&self.last).map(|p| LinePiece { path: Arc::clone(&p.path), along: p.along }).collect() + } + + /// Each segment of the line through `pts` as its own path: the same shared path as in the + /// call before while the segment's ends did not move. + pub(super) fn segments(&mut self, pts: &[Point]) -> Vec> { + self.built = 0; + let n = pts.len().saturating_sub(1); + self.segments.truncate(n); + let mut out = Vec::with_capacity(n); + for (j, w) in pts.windows(2).enumerate() { + match self.segments.get(j) { + Some((a, b, path)) if *a == w[0] && *b == w[1] => out.push(Arc::clone(path)), + _ => { + let path = Arc::new(polyline(w)); + self.built += 2; + match self.segments.get_mut(j) { + Some(kept) => *kept = (w[0], w[1], Arc::clone(&path)), + None => self.segments.push((w[0], w[1], Arc::clone(&path))), + } + out.push(path); + } + } + } + out + } + + /// The length of the line before the piece after the settled ones. + fn along_next(&self, pts: &[Point]) -> f64 { + self.settled.last().map_or(0.0, |p| p.along + pts.get(p.from..=p.from + PIECE_SEGMENTS).map_or(0.0, length)) + } + + /// The piece through the points `from` to `to` of `pts`, `along` the line. + fn build(&mut self, pts: &[Point], from: usize, to: usize, along: f64) -> Piece { + let run = pts.get(from..=to).unwrap_or_default(); + self.built += run.len(); + Piece { path: Arc::new(polyline(run)), from, to, end: run.last().copied().unwrap_or_default(), along } + } +} + +/// The length of the line through `pts`. +fn length(pts: &[Point]) -> f64 { + pts.windows(2).map(|w| w[0].distance(w[1])).sum() +} + +/// Does `path` run through exactly the points `pts`? +fn same_points(path: &BezPath, pts: &[Point]) -> bool { + path.elements().len() == pts.len() && path.elements().iter().zip(pts).all(|(e, p)| e.end_point() == Some(*p)) +} diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 7aba70d4b6..97296c7254 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1195,7 +1195,14 @@ fn pencil_alt_smooths_within_the_smooth_tools_radius() { /// The dashed paths among the overlays. fn bands(t: &GestureTool, cx: &ToolContext) -> Vec { - t.overlays(cx).into_iter().filter_map(|o| if let Overlay::Path { path, dashed: true, .. } = o { Some(path) } else { None }).collect() + t.overlays(cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(path), + Overlay::SharedPath { path, dash: Some(_), .. } => Some((*path).clone()), + _ => None, + }) + .collect() } /// How far `q` is from the polyline through `pts`. @@ -1344,6 +1351,12 @@ fn smoothing_band_follows_a_long_drag() { assert_eq!(frames, (n - 1).div_ceil(BAND_STEP * BAND_STEPS_PER_CALL), "frames for {n} points"); check_band(&t, &cx, cx.tol(12.0)); assert!(!t.overlays_pending()); + // Once finished, the band shows as the same shared path each frame. + let band_of = |t: &GestureTool| { + t.overlays(&cx).into_iter().find_map(|o| if let Overlay::SharedPath { path, dash: Some(_), .. } = o { Some(path) } else { None }) + }; + let (a, b) = (band_of(&t), band_of(&t)); + assert!(a.zip(b).is_some_and(|(a, b)| std::sync::Arc::ptr_eq(&a, &b)), "the band is not made again"); let last = pts[pts.len() - 1]; t.pointer(&cx, &PointerEvent::new(PointerKind::Up, last.x, last.y)); // The next drag shows only its own band. @@ -1623,7 +1636,7 @@ fn smoothing_drag_shows_no_band_without_a_path_it_smooths() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 300.0)); let o = t.overlays(&cx); - assert!(!o.iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. })), "{o:?}"); + assert!(bands(&t, &cx).is_empty(), "{o:?}"); } /// An Alt smoothing drag uses the Smooth tool's Fidelity for Pencil, Paintbrush and Blob Brush. @@ -2354,7 +2367,7 @@ fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt)); let o = t.overlays(&cx); - let [Overlay::Path { dashed: true, .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") }; + let [Overlay::SharedPath { dash: Some(_), .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") }; assert_eq!(*width, 1.0); assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}"); } @@ -2514,6 +2527,99 @@ fn the_settled_outline_of_a_long_drag_is_the_same_shared_path_each_frame() { } } +/// The points the last `overlays` call copied into new paths for a drag's line. +fn line_built(t: &GestureTool) -> usize { + let line = t.line.take(); + let built = line.as_ref().map_or(0, |l| l.built()); + t.line.set(line); + built +} + +/// The line of a long round Eraser, Knife, Path Eraser or Pencil (Live preview off) drag shows in +/// pieces, and the steps of a round Eraser drag whose Size follows the pen each as its own path. +/// They come back from one call to the next, at any zoom, as the same shared paths, which the host +/// draws again without building them again; the call copies no point into a new path. A step of +/// the drag builds again only the last piece, or adds one step. The pieces run through every point +/// of the drag, each from where the one before ends and on over the next segment, and the +/// Knife's dashes go on from one piece to the next. +#[test] +fn the_line_of_a_long_drag_is_the_same_shared_pieces_each_frame() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let shared = |o: &[Overlay]| -> Vec<(std::sync::Arc, f32, Option)> { + o.iter() + .filter_map( + |o| if let Overlay::SharedPath { path, width, dash, .. } = o { Some((std::sync::Arc::clone(path), *width, *dash)) } else { None }, + ) + .collect() + }; + let points_of = |p: &BezPath| -> Vec { p.elements().iter().filter_map(|e| e.end_point()).collect() }; + let n = 3000; + for (id, pressure) in [("eraser", false), ("knife", false), ("pathEraser", false), ("pencil", false), ("eraser", true)] { + let mut t = GestureTool::new(id); + t.set_option("size", &json!(10)); + t.set_option("livePreview", &json!(false)); + if pressure { + t.set_option("sizeMode", &json!("pressure")); + t.set_option("sizeVariation", &json!(4)); + } + long_area_drag(&mut t, &cx, n, |i| if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 }); + let first = shared(&t.overlays(&cx)); + assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Path { .. })), "{id}: no path of the drag is built for the call alone"); + if pressure { + assert_eq!(first.len(), n - 1, "{id}: a path for each step"); + for (j, (path, _, dash)) in first.iter().enumerate() { + assert_eq!(points_of(path), t.points[j..=j + 1], "{id}: step {j}"); + assert_eq!(*dash, None); + } + } else { + assert!(first.len() > 1, "{id}: {} pieces", first.len()); + let mut along = 0.0; + for (k, (path, width, dash)) in first.iter().enumerate() { + let from = k * line::PIECE_SEGMENTS; + let to = (from + line::PIECE_SEGMENTS + 1).min(n - 1); + assert_eq!(points_of(path), t.points[from..=to], "{id}: piece {k}"); + assert_eq!(*width, if id == "eraser" { 10.0 } else { 1.0 }, "{id}"); + match dash { + Some(at) => assert!(id == "knife" && (at - along).abs() < 1e-6, "{id}: piece {k} dashes from {at}, not {along}"), + None => assert_ne!(id, "knife"), + } + along += t.points[from..=(from + line::PIECE_SEGMENTS).min(n - 1)].windows(2).map(|w| w[0].distance(w[1])).sum::(); + } + assert_eq!(first.len() - 1, (n - 3) / line::PIECE_SEGMENTS, "{id}: the last piece holds the points no settled piece holds"); + } + for zoom in [1.0, 4.0, 1.0] { + let again = shared(&t.overlays(&ToolContext { zoom, ..cx })); + assert_eq!(line_built(&t), 0, "{id}: at zoom {zoom}, no point is copied into a new path"); + assert_eq!(again.len(), first.len(), "{id}"); + assert!( + again.iter().zip(&first).all(|(a, b)| std::sync::Arc::ptr_eq(&a.0, &b.0)), + "{id}: at zoom {zoom}, every path is the one shown before" + ); + } + // One step more along the drag. + let s = n as f64; + let r = 150.0 + 100.0 * (s * 0.0071).sin(); + let (x, y) = (300.0 + r * (s * 0.04).cos(), 300.0 + r * (s * 0.04).sin()); + t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, x, y) }); + let after = shared(&t.overlays(&cx)); + let built = line_built(&t); + let kept = after.iter().filter(|a| first.iter().any(|f| std::sync::Arc::ptr_eq(&a.0, &f.0))).count(); + if pressure { + assert_eq!((built, after.len(), kept), (2, n, n - 1), "{id}: one step added"); + } else { + assert!(built <= line::PIECE_SEGMENTS + 2, "{id}: {built} points copied"); + assert_eq!(kept, first.len() - 1, "{id}: only the last piece is built again"); + } + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y)); + assert!(!acts.is_empty(), "{id}: the release still acts"); + assert!(t.line.take().is_none(), "{id}: the release drops the pieces"); + } +} + /// The outline a Blob Brush or Eraser drag shows does not change what its release sends: the same /// drag sends the same command whether or not its outline was drawn along the way. #[test] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 197d41aaaf..8938b156c6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -73,10 +73,13 @@ pub enum Overlay { SelectionMarquee { rect: Rect, enclosed: bool, pointer: Point }, /// A path preview (e.g. pen rubber band) in a colour (RGB). Path { path: BezPath, color: [u8; 3], width: f32, dashed: bool }, - /// A solid path preview that later calls return again, as the same shared `path`, for as long - /// as it does not change (the settled outline of a long Blob Brush or Eraser drag). The host - /// can keep what it built to draw it while `path` is the same allocation. - SharedPath { path: std::sync::Arc, color: [u8; 3], width: f32 }, + /// A path preview that later calls return again, as the same shared `path`, for as long as it + /// does not change (the settled outline of a long Blob Brush or Eraser drag, the pieces of a long + /// drag's line). The host can keep what it built to draw it while `path` is the same allocation. + /// With `dash`, it is dashed as a dashed [`Overlay::Path`] is, from `dash` document units along + /// the dash pattern: the pieces of one line, each starting where the one before it ends, dash + /// as the whole line does. + SharedPath { path: std::sync::Arc, color: [u8; 3], width: f32, dash: Option }, /// A line segment (smart guide, handle line). Line { a: Point, b: Point, color: [u8; 3], dashed: bool }, /// An anchor square: filled = selected. diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 139d0adc7d..e3612bc880 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -395,20 +395,70 @@ struct SharedKey { /// The painter's clip: the lines of the path outside it have no triangles in the mesh. clip: egui::Rect, stroke: Stroke, + /// Where the dash pattern starts along the path, in document units, when it is dashed. + dash: Option, pixels_per_point: f32, tessellation: TessellationOptions, } +/// The length of a dash of a dashed overlay, in screen pixels. +const DASH: f32 = 4.0; +/// The length of the gap after each dash of a dashed overlay, in screen pixels. +const GAP: f32 = 3.0; + +/// Add to `out` the dashes of `line` drawn with `s`, [`DASH`] pixels drawn and [`GAP`] left out, +/// with the pattern started `from` pixels along it: from 0, the dashes [`Shape::dashed_line`] gives. +pub(super) fn dashes_from(line: &[Pos2], s: Stroke, from: f64, out: &mut Vec) { + let period = f64::from(DASH + GAP); + let phase = from.rem_euclid(period); + let phase = if phase.is_finite() { phase as f32 } else { 0.0 }; + if line.len() < 2 { + return; + } + if phase >= DASH { + Shape::dashed_line_many_with_offset(line, s, &[DASH], &[GAP], DASH + GAP - phase, out); + return; + } + // The pattern starts within a dash: the rest of that dash is drawn, then the pattern goes on + // after its gap. + let mut left = DASH - phase; + for (i, w) in line.windows(2).enumerate() { + let len = (w[1] - w[0]).length(); + if len >= left { + let cut = w[0] + (w[1] - w[0]) * (left / len); + let mut dash = line[..=i].to_vec(); + dash.push(cut); + out.push(Shape::line(dash, s)); + let mut rest = vec![cut]; + rest.extend_from_slice(&line[i + 1..]); + Shape::dashed_line_many_with_offset(&rest, s, &[DASH], &[GAP], GAP, out); + return; + } + left -= len; + } + out.push(Shape::line(line.to_vec(), s)); +} + impl SharedPaths { - /// The mesh that draws `path` with `s` at the view `xf` with the painter `p`: the one kept in - /// this frame or in `last` (the last frame's) when it was built for the same, else a new one. - /// It is kept for the next frame. - fn mesh(&mut self, last: &mut HashMap, path: &Arc, xf: &Xf, s: Stroke, p: &egui::Painter) -> Arc { + /// The mesh that draws `path` with `s`, dashed from `dash` document units along the pattern + /// when that is set, at the view `xf` with the painter `p`: the one kept in this frame or in + /// `last` (the last frame's) when it was built for the same, else a new one. It is kept for + /// the next frame. + fn mesh( + &mut self, + last: &mut HashMap, + path: &Arc, + xf: &Xf, + s: Stroke, + dash: Option, + p: &egui::Painter, + ) -> Arc { let ctx = p.ctx(); let key = SharedKey { view: xf.affine().as_coeffs(), clip: p.clip_rect(), stroke: s, + dash, pixels_per_point: ctx.pixels_per_point(), tessellation: ctx.tessellation_options(|o| *o), }; @@ -425,7 +475,16 @@ impl SharedPaths { tessellator.set_clip_rect(key.clip); let mut mesh = Mesh::default(); for line in to_screen_path(path, xf) { - tessellator.tessellate_shape(Shape::line(line, s), &mut mesh); + match dash { + Some(from) => { + let mut dashes = vec![]; + dashes_from(&line, s, from * xf.zoom, &mut dashes); + for d in dashes { + tessellator.tessellate_shape(d, &mut mesh); + } + } + None => tessellator.tessellate_shape(Shape::line(line, s), &mut mesh), + } } SharedMesh { path: Arc::clone(path), key, mesh: Arc::new(mesh) } } @@ -476,8 +535,8 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: stroke_path(p, path, xf, s); } } - Overlay::SharedPath { path, color, width } => { - let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), p); + Overlay::SharedPath { path, color, width, dash } => { + let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), *dash, p); if !mesh.is_empty() { p.add(Shape::mesh(mesh)); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6803e977a1..8830edf1c7 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -99,7 +99,8 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() { path.line_to((250.0, 160.0)); let a = std::sync::Arc::new(path.clone()); let b = std::sync::Arc::new(path.clone()); - let shared_of = |p: &std::sync::Arc| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0 }; + let shared_of = + |p: &std::sync::Arc| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0, dash: None }; let first = one(frame(&[shared_of(&a)], 1.0, &mut shared)); assert!(!first.vertices.is_empty()); let again = one(frame(&[shared_of(&a)], 1.0, &mut shared)); @@ -143,6 +144,63 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() { half.line_to((5100.0, 5000.0)); let half = one(frame(&[shared_of(&std::sync::Arc::new(half))], 1.0, &mut shared)); assert_eq!(*half, *first, "the subpath off the canvas adds no triangles"); + // A dashed shared path keeps its mesh too, and the place its dashes start is part of it. + let dashed_of = |p: &std::sync::Arc, dash: f64| Overlay::SharedPath { + path: std::sync::Arc::clone(p), + color: [0x80, 0x80, 0x80], + width: 1.0, + dash: Some(dash), + }; + let dashed = one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared)); + assert!(!dashed.vertices.is_empty() && *dashed != *first, "the dashes leave out parts of the line"); + assert!(std::sync::Arc::ptr_eq(&dashed, &one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared)))); + let moved = one(frame(&[dashed_of(&a, 2.0)], 1.0, &mut shared)); + assert!(!std::sync::Arc::ptr_eq(&dashed, &moved) && *dashed != *moved, "dashes that start elsewhere build a new mesh"); +} + +/// A line drawn dashed in pieces, each piece's dashes starting as far along the pattern as the +/// pieces before it are long, shows the dashes the whole line shows dashed in one go, whether a +/// piece starts within a dash or within a gap, and a pattern started at 0 gives the dashes of +/// [`Shape::dashed_line`]. +#[test] +fn a_line_dashed_in_pieces_dashes_as_the_whole_line_does() { + // The stretches of x that dashes along the x axis cover, with touching ones joined. + let covered = |shapes: &[Shape]| -> Vec<(f32, f32)> { + let mut spans: Vec<(f32, f32)> = shapes + .iter() + .map(|s| { + let xs: Vec = match s { + Shape::LineSegment { points, .. } => points.iter().map(|p| p.x).collect(), + Shape::Path(p) => p.points.iter().map(|p| p.x).collect(), + other => panic!("{other:?}"), + }; + (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max)) + }) + .collect(); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut joined: Vec<(f32, f32)> = vec![]; + for (a, b) in spans { + match joined.last_mut() { + Some(last) if a - last.1 < 1e-3 => last.1 = last.1.max(b), + _ => joined.push((a, b)), + } + } + joined + }; + let s = Stroke::new(1.0, Color32::WHITE); + let along = |xs: &[f32]| -> Vec { xs.iter().map(|&x| pos2(x, 10.0)).collect() }; + let whole = along(&[0.0, 30.0, 61.5, 100.0]); + let mut one_go = vec![]; + overlays::dashes_from(&whole, s, 0.0, &mut one_go); + assert_eq!(covered(&one_go), covered(&Shape::dashed_line(&whole, s, 4.0, 3.0))); + // Cuts at 50 (within a dash: 50 is 1 past the dash that starts at 49) and at 75 (within a gap). + let mut pieces = vec![]; + overlays::dashes_from(&along(&[0.0, 30.0, 50.0]), s, 0.0, &mut pieces); + overlays::dashes_from(&along(&[50.0, 61.5, 75.0]), s, 50.0, &mut pieces); + overlays::dashes_from(&along(&[75.0, 100.0]), s, 75.0, &mut pieces); + let (want, got) = (covered(&one_go), covered(&pieces)); + assert_eq!(want.len(), got.len(), "{want:?} {got:?}"); + assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-3 && (w.1 - g.1).abs() < 1e-3), "{want:?} {got:?}"); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 21b0074bbd..fc76b6e5ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1183,7 +1183,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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 takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). - The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The outline of a drag with a round Eraser tip is drawn whole each frame. + The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - **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`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). From f389d644fcb24f86e08a0fcf072df78aea5b3e77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:57:06 -0800 Subject: [PATCH 26/50] Tests: the plain-label paste test changes a graph option before its undo Graph Type options that leave a graph as it is no longer record a step of history, so the test's third undo had nothing to take back. The test now turns on Add Drop Shadow, which redraws the graph and records a step. --- crates/engine/src/tests/clipboard.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 519974f33d..0e0bd500c1 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -596,8 +596,8 @@ fn a_graph_pasted_without_formatting_keeps_plain_labels_when_drawn_again() { let r = node(&s, p).extras().graph.as_deref().unwrap().rect; let off = [r.x0 - plot.x0 - 10.0, r.y0 - plot.y0 - 20.0, r.x1 - plot.x1 - 10.0, r.y1 - plot.y1 - 20.0]; assert!(off.iter().all(|d| d.abs() < 1e-6), "the plot moves by the offset and keeps its size: {plot:?} → {r:?}"); - s.execute("graph.setType", &json!({"id": p.0, "type": "column"})).unwrap(); - assert_eq!(graph_label_looks(&s, p), pasted, "a change of type draws them the same way"); + s.execute("graph.setType", &json!({"id": p.0, "type": "column", "dropShadow": true})).unwrap(); + assert_eq!(graph_label_looks(&s, p), pasted, "a change of graph type options draws them the same way"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); From be26bddb7e588d5f4e716b3b0d4db3dff7f6140e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:08:25 -0800 Subject: [PATCH 27/50] Type: Show Sample cites the help page that describes it The links to the archived help PDFs now open the page with the Show Sample step (#page=352 in the CS4 help, #page=348 in the CS6 reference) instead of an earlier page. The comments and docs/mcp.md also say which part's face gives the em box and ICF box: the part that sets the sample's first Kanji, which is a custom set when one holds that character. --- crates/ui-egui/src/dialogs/composite_fonts/sample.rs | 12 +++++++----- docs/mcp.md | 6 +++--- docs/target-app-parity.md | 2 +- docs/type-parity.md | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs index 952e88be1c..849eb63b51 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs @@ -3,7 +3,8 @@ //! ascender and x-height, each shown or hidden by its button, at the size Zoom picks. //! //! The sample text, the zoom steps, the size at 100% and what each line measures are VectorCraft's -//! own: the em box and ICF box are those of the Kanji part's face +//! own: the em box and ICF box are those of the face of the part that sets the sample's first Kanji +//! (the Kanji part, or a custom set that holds that character) //! ([`vectorcraft_text::FontFace::ideographic_centre`], [`vectorcraft_text::FontFace::icf_margins`]), //! the cap height and x-height those of the face the Roman letters are drawn in, Max Ascent/Descent //! the highest ascent and lowest descent among the faces the sample is drawn in (fallback faces @@ -11,8 +12,8 @@ //! baseline and vertical scale. //! //! Behavior reference (public documentation): -//! , -//! . +//! , +//! . use std::hash::{DefaultHasher, Hash, Hasher}; @@ -225,8 +226,9 @@ pub(super) fn measure(f: &CompositeFont, size: f64) -> (BezPath, Heights) { Some((part_face, drawn, em, shift, p.v_scale / 100.0)) }; let mut h = Heights::default(); - // The em box and ICF box are the Kanji part's, the base of the composite font, as layout - // measures that part's face for Scale at Center. + // The em box and ICF box are those of the part that sets the sample's first Kanji (the Kanji + // part, or a custom set that holds that character), as layout measures that part's face for + // Scale at Center. if let Some((face, _, em, shift, v)) = TEXT.chars().next().and_then(placed) { let tall = em * v; let mid = shift + face.ideographic_centre() * tall; diff --git a/docs/mcp.md b/docs/mcp.md index cce0bf108f..e96d89cf54 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9708,9 +9708,9 @@ Unicode adds the characters of hexadecimal codes (`3042`, `U+3042`, several sepa characters the set already lists. Delete takes the character picked out of the set. Show Sample (Hide Sample when it shows) draws the font picked in a line of sample text, with the first character of each custom set added, and a button beside it for each line it can mark: ICF Box, Em Box, Baseline, Cap Height, Max Ascent/Descent, Max Ascender and -x-height ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=300)). -The em box and ICF box are those of the Kanji part's font, the cap height and x-height those of the face the -Roman letters are drawn in (a fallback face when the part's font lacks the character), Max Ascent/Descent the highest +x-height ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). +The em box and ICF box are those of the font of the part that sets the sample's first Kanji (the Kanji part, or a +custom set that holds that character), the cap height and x-height those of the face the Roman letters are drawn in (a fallback face when the part's font lacks the character), Max Ascent/Descent the highest ascent and lowest descent of the faces the sample uses, and Max Ascender the top of its tallest glyph; each takes its part's size, baseline and vertical scale. Zoom draws it at 25% to 800% of 36 pt. The sample text, the zoom steps and the size are VectorCraft's own. OK runs `type.compositeFonts.set` with every font as one diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fce00c8fb2..8d2dfb527c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -710,7 +710,7 @@ since 2026-10-01. - **Composite fonts that two documents define differently:** when two open documents each define a composite font (Type › Composite Fonts…) by the same name with different parts, each document draws and exports its type in its own definition: in a tiled or floating window drawn while the front document draws, when it is placed in a document that defines the name differently, and in an export made while another document is in front. Evidence: `tests::composite::nested_loans_of_one_name_use_each_documents_definition` and `threads_lending_one_name_at_once_use_their_own_definitions` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` (`crates/render`). Scores unchanged (estimated). - **Composite fonts only another document defines:** a document draws, measures and exports its type only in the composite fonts it defines itself. Type naming a composite font that only another open document, or the document a placed document sits in, defines is set as in a missing font, also when the document defines no composite font: in a window, a thumbnail or an export of a document in the back, in a file being opened and in a placed document. A temporary document drawn while a document draws keeps that document's composite fonts. Evidence: `tests::composite::a_lent_document_does_not_use_another_documents_composite_font` and `a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` and `a_document_draws_type_in_another_documents_composite_font_as_missing` (`crates/render`), `a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing` (`crates/engine`). Scores unchanged (estimated). - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). -- **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=300)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). +- **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). diff --git a/docs/type-parity.md b/docs/type-parity.md index 9576d55d72..823b559a2e 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -74,7 +74,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | | CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for (in `GSUB`, or for the width forms `GSUB` or `GPOS`) is disabled, and Revert To Default Forms draws the default glyphs. A form other than the default takes away a character's glyph choice, and with a width form Proportional Metrics' `palt` is not applied and the font's pair kerning is off. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `typecmd::area_tests::a_glyph_form_takes_away_the_characters_glyph_choice`, `features::tests::width_forms_turn_off_proportional_metrics`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form`, `panels::glyphs::tests::glyph_form_items_at_a_caret_follow_all_the_text`, `panels::glyphs::tests::a_glyph_choice_lets_the_current_form_be_chosen_again` | | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | -| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=300)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | +| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Serbian: Cyrillic, Serbian: Latin and Croatian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation by it in languages other than English and the eleven Indian languages above, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | From 88d94ef78fe84367fca43d265036ddfca05475f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:14:50 -0800 Subject: [PATCH 28/50] Path Precision Tools: Common Tangents refuses a path with a short inward bend The convexity check looked at 32 points along each segment, so a cubic that bends the other way for a short stretch between two of those points was taken as convex. Each segment is now also checked whole: the cross product of its first and second derivatives, a quadratic in t, must not turn against the way the outline turns anywhere on the segment. --- .../pathops/src/addons/pathtools/tangents.rs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index c0d66e0dc1..2059932aa2 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -148,6 +148,11 @@ impl Outline { if (turning - TAU).abs() > 1e-6 { return Err(OutlineError::NotConvex); } + // A short bend the other way can lie between two of the points: each segment is checked + // whole. + if segments.iter().any(|s| bends_against(s, sign)) { + return Err(OutlineError::NotConvex); + } let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); if !center.x.is_finite() || !center.y.is_finite() { return Err(OutlineError::Empty); @@ -290,6 +295,32 @@ impl Outline { /// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where /// the curve runs square to `n`) and the value there. +/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product +/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared +/// with the segment's control polygon length squared. +fn bends_against(s: &CubicBez, sign: f64) -> bool { + let (a, b, c) = (s.p1 - s.p0, s.p2 - s.p1, s.p3 - s.p2); + let q = |t: f64| { + let u = 1.0 - t; + let d1 = a * (u * u) + b * (2.0 * u * t) + c * (t * t); + let d2 = (b - a) * u + (c - b) * t; + d1.cross(d2) * sign + }; + let (q0, half, q1) = (q(0.0), q(0.5), q(1.0)); + // q(t) = q0 + k1 t + k2 t². + let k2 = 2.0 * (q0 + q1 - 2.0 * half); + let k1 = q1 - q0 - k2; + let mut low = q0.min(q1); + if k2 > 0.0 { + let t = -k1 / (2.0 * k2); + if t > 0.0 && t < 1.0 { + low = low.min(q(t)); + } + } + let scale = (a.hypot() + b.hypot() + c.hypot()).powi(2); + low < -1e-9 * scale +} + fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); @@ -835,6 +866,17 @@ mod tests { assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open)); let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone(); assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex)); + // A half disk whose straight side is a cubic with crossed handles: it bends the other way + // for a short stretch between two of the points the outline is checked at. + let mut bp = vectorcraft_geom::BezPath::new(); + let k = 0.5523 * 50.0; + bp.move_to((0.0, 0.0)); + bp.curve_to((62.4, 43.4), (60.3, 44.2), (100.0, 0.0)); + bp.curve_to((100.0, -k), (50.0 + k, -50.0), (50.0, -50.0)); + bp.curve_to((50.0 - k, -50.0), (0.0, -k), (0.0, 0.0)); + bp.close_path(); + let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); // A square traced twice around winds around twice. let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); From dea17e54467b70578d1252ced51da017313d5eac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:14:51 -0800 Subject: [PATCH 29/50] PSD export: a slice is clipped to the region before it is rounded to pixels A region whose edge falls inside a pixel no longer drops a slice that overlaps it, and no longer writes a slice that lies past it. The overlap is found in document coordinates, and only that part is converted to pixels. --- crates/render/src/encode/psd.rs | 8 +++++--- crates/render/src/encode/tests_psd.rs | 11 +++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 6dc3f4b98e..0d568f9e04 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -457,11 +457,13 @@ fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Resul return Err(format!("slice {number} has no finite bounds and can't be written to PSD")); } let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue }; - let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max)); - let (l, t, r, b) = (edge(r.x0, region.x0, w), edge(r.y0, region.y0, h), edge(r.x1, region.x0, w), edge(r.y1, region.y0, h)); - if !(l < r && t < b) { + // The part inside `region`, found before the region is rounded to whole pixels. + let (x0, y0, x1, y1) = (r.x0.max(region.x0), r.y0.max(region.y0), r.x1.min(region.x1), r.y1.min(region.y1)); + if !(x0 < x1 && y0 < y1) { continue; } + let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max)); + let (l, t, r, b) = (edge(x0, region.x0, w), edge(y0, region.y0, h), edge(x1, region.x0, w), edge(y1, region.y0, h)); // Whole pixels, at least one each way. let span = |a: f64, b: f64, max: u32| { let max = i64::from(max); diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index d242b3c7e5..6875648df3 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -439,6 +439,17 @@ fn slices_are_cut_to_the_exported_region_in_its_pixels() { thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0); let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap(); assert_eq!(res.slices[0].rect, [20, 5, 21, 15]); + // The overlap is found before the region is rounded to whole pixels: a slice inside a region + // that ends at 10.4 keeps its last pixel, and one past a region that ends at 10.6 isn't written. + let o = opts(PsdOptions::default()); + let mut edge = doc.clone(); + edge.slices[0].rect = Rect::new(10.1, 5.0, 10.3, 15.0); + edge.node_mut(edge.layers[0].children().unwrap()[0].id).unwrap().extras_mut().slice = None; + let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.4, 60.0), RasterFormat::Psd, &o).unwrap(); + assert_eq!(slices_of(&file).unwrap().slices.iter().map(|s| s.rect).collect::>(), [[9, 5, 10, 15]]); + edge.slices[0].rect = Rect::new(10.7, 5.0, 10.9, 15.0); + let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.6, 60.0), RasterFormat::Psd, &o).unwrap(); + assert!(slices_of(&file).is_none()); } #[test] From e83f78f681e77cebcc651b7b66d2f9d7ca337038 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:16:15 -0800 Subject: [PATCH 30/50] Crop Image: the Control bar leaves room for the cropping options While the Crop Image tool is in use, the image's Control bar shows its file name, color mode and resolution only, so the tool's PPI, reference point, X, Y, W and H follow them in a wide window instead of being left out behind Unembed, Image Trace, Mask, Crop Image and Remove Background. ui.cropImage's params text now lists the ppi, reference and linked options and says Apply sends ppi with the rect. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/chrome/tests.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/place.rs | 11 ++++++++--- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8e651622af..8cd7146589 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -848,7 +848,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index d4a7c7f0e8..f1c63eafb4 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3292,7 +3292,7 @@ fn the_control_bar_s_controls_stay_inside_the_bar_in_a_narrow_window() { wide(&mut app, "an embedded image", &["Unembed…", "Image Trace", "Mask", "Crop Image", "Remove Background"]); app.select_tool(vectorcraft_tools::cropimage::ID); check(&mut app, "Crop Image"); - wide(&mut app, "Crop Image", &["X:", "Y:", "W:"]); + wide(&mut app, "Crop Image", &["PPI", "X:", "Y:", "W:", "H:"]); app.select_tool("selection"); app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); let trace = selected(&app); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4c286f1da9..fe7563b096 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -849,7 +849,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 0ad9fbc3ed..e00bf45e4a 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -741,9 +741,11 @@ pub fn image_summary(i: &Value) -> (String, String) { /// The Control bar for the one selected image: Linked File or Embedded, its file name, colour mode /// and effective resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask, -/// Crop Image and Remove Background. Whether one image is selected. A file name the row has no room -/// for is left out alone; after it, each control shows only while the row has room for it and -/// `reserve` after it, and the controls after one left out are left out too. +/// Crop Image and Remove Background. While the Crop Image tool is in use, the bar shows the file +/// name, colour mode and resolution only, and the tool's cropping options follow them. Whether one +/// image is selected. A file name the row has no room for is left out alone; after it, each control +/// shows only while the row has room for it and `reserve` after it, and the controls after one left +/// out are left out too. pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: f32) -> bool { let Some(i) = selected_image_info(app) else { return false }; let (name, details) = image_summary(i); @@ -763,6 +765,9 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: ui.label(details); } fit.separator(ui); + if app.session.tool_id() == vectorcraft_tools::cropimage::ID { + return true; + } link_buttons(app, ui, id, linked, &name, LinkButtons::Fit(&mut fit)); // The Image Trace button grows past its usual width for a longer translated label. let arrow = widgets::SPLIT_ARROW; From 6c3a092996d400aecae412934c3886f7f3cd2b16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:31:14 -0800 Subject: [PATCH 31/50] Line Segment: a line from one curve to another snaps to their common tangent With Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two. Both ends move to where the line touches the paths, the start sliding along the first path. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around that path switches between the outer tangent and the one crossing between the paths. Each end shows the "tangent" label when Anchor/Path Labels is on, and the line is drawn as a guide when Alignment Guides is on. Before this change the start of a Line Segment drag always stayed where it was pressed. It still does when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. The tangents come from the Common Tangents geometry. Each pointer move looks at the 16 nearest closed subpaths within the snapping tolerance and keeps the tangents of up to 64 pairs for the rest of the drag. --- ROADMAP.md | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/tangent_line.rs | 40 ++++ crates/tools/src/context.rs | 6 +- crates/tools/src/guides.rs | 2 + crates/tools/src/guides/bitangent.rs | 271 ++++++++++++++++++++++++ crates/tools/src/guides/snap.rs | 31 ++- crates/tools/src/guides/targets.rs | 6 +- crates/tools/src/shape.rs | 42 +++- crates/tools/src/shape/tests.rs | 253 ++++++++++++++++++++++ docs/target-app-parity.md | 1 + 11 files changed, 643 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/tests/tangent_line.rs create mode 100644 crates/tools/src/guides/bitangent.rs diff --git a/ROADMAP.md b/ROADMAP.md index 7ad95b59da..4336c13037 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -146,6 +146,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..91aea0b140 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -196,6 +196,7 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbollib; +mod tangent_line; mod targeting; mod textcombos; mod textedit; diff --git a/crates/engine/src/tests/tangent_line.rs b/crates/engine/src/tests/tangent_line.rs new file mode 100644 index 0000000000..78511d766b --- /dev/null +++ b/crates/engine/src/tests/tangent_line.rs @@ -0,0 +1,40 @@ +//! Snap to Tangent with the Line Segment tool: a line dragged from one circle to another lands on +//! their common tangent, drawn by `shape.line` as one undo step. + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::*; + +use PointerKind::{Down, Drag, Up}; + +#[test] +fn a_line_segment_drag_draws_the_common_tangent_as_one_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 210, "width": 80, "height": 80})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 240, "y": 190, "width": 120, "height": 120})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + assert_eq!(count(&s), 2); + // Circles about (100, 250), radius 40, and (300, 250), radius 60: the outer tangent above them + // has the normal (-0.1, -√0.99) and touches them at center + radius × normal. + let n = Vec2::new(-0.1, -(0.99f64).sqrt()); + let (on_a, on_b) = (Point::new(100.0, 250.0) + n * 40.0, Point::new(300.0, 250.0) + n * 60.0); + s.select_tool("lineSegment", ViewInfo::default()).unwrap(); + let to = on_b + Vec2::new(0.5, 0.7); + for (k, x, y) in [(Down, 100.0, 210.0), (Drag, 200.0, 200.0), (Drag, to.x, to.y), (Up, to.x, to.y)] { + s.pointer(&PointerEvent::new(k, x, y), ViewInfo::default()).unwrap(); + } + assert_eq!(count(&s), 3); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") }; + let ends: Vec = path.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends.len(), 2); + // Within what the drawn circles' 0.03% radius error allows. + assert!((ends[0] - on_a).hypot() < 0.15 && (ends[1] - on_b).hypot() < 0.15, "{ends:?}, want {on_a:?} {on_b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(count(&s), 2, "one undo removes the line"); +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1e8f57ffc9..8bec1ccc54 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -198,9 +198,11 @@ pub struct ToolContext<'a> { /// [`Self::snap_tolerance`]. pub snap_to_point: bool, /// View → Snapping → Snap to Tangent: with Smart Guides on, a line drawn - /// from an anchor lands where it touches a nearby curve. + /// from an anchor lands where it touches a nearby curve, and a Line Segment + /// drag from one convex curved path to another lands on their common tangent. pub snap_tangent: bool, - /// View → Snapping → Snap to Perpendicular: likewise where it meets a nearby segment square. + /// View → Snapping → Snap to Perpendicular: with Smart Guides on, a line drawn from an anchor + /// lands where it meets a nearby segment square. pub snap_perpendicular: bool, /// View → Snap to Glyph: drawn points snap to live-text glyph bounds, and on a single line of type /// to its baseline, x-height, character widths and glyph anchor points (with Smart Guides). diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index 614df68917..e9f7bf7318 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -20,9 +20,11 @@ use vectorcraft_text::{FontDb, layout as layout_text}; use crate::bbox::Handle; use crate::{GlyphSnap, Overlay, ScreenFrame, ToolContext}; +mod bitangent; mod snap; mod targets; +pub(crate) use bitangent::TangentLine; pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, diff --git a/crates/tools/src/guides/bitangent.rs b/crates/tools/src/guides/bitangent.rs new file mode 100644 index 0000000000..9d4f9fa05c --- /dev/null +++ b/crates/tools/src/guides/bitangent.rs @@ -0,0 +1,271 @@ +//! Snap to Tangent for a line drawn from one curve to another (the Line Segment tool): when the +//! press lands on a convex closed path with curves and the pointer comes near another one, both +//! ends of the line move onto a common tangent of the two, the start sliding along the first path. +//! The tangents are [`vectorcraft_pathops::addons::pathtools::common_tangents`]'s. +//! +//! The closed subpaths in the window the line may end on are listed once, at the press, by their +//! bounds, up to as many segments as Smart Guides gather. Each pointer move looks only at the +//! [`MAX_NEAR`] nearest of them whose outline lies within the snapping tolerance of the pointer. +//! The tangents of each pair are worked out once, and the last [`MAX_KEPT`] pairs' are kept for +//! the rest of the drag. + +use std::collections::HashSet; + +use vectorcraft_pathops::addons::pathtools::{Outline, Tangent, common_tangents}; + +use super::snap::visible; +use super::targets::{BUDGET, walk_but}; +use super::{Node, NodeId, NodeKind, Overlay, ParamCurveNearest, Point, Rect, SubPath, ToolContext}; +use crate::PixelOp; + +/// Most subpaths a pointer move takes tangents from: the nearest ones whose outline lies within +/// the snapping tolerance of the pointer. +const MAX_NEAR: usize = 16; +/// Most pairs whose tangents are kept during one drag. +const MAX_KEPT: usize = 64; +/// Most segments a subpath the line starts or ends on may have: the tangents of two paths take +/// time that grows with both paths' segment counts, and they are worked out during the drag. +const MAX_SEGMENTS: usize = 512; + +/// A closed subpath with a curve the line may end on: its path, its index in the path, and the +/// bounds of its control points. +#[derive(Clone, Copy)] +struct Listed { + key: (NodeId, usize), + bounds: Rect, +} + +/// The two-ended tangent snap of one Line Segment drag. +#[derive(Default)] +pub(crate) struct TangentLine { + /// The subpath the press landed on and its outline: none when the press was not on a convex + /// closed path with a curve, or the snap is off. + from: Option<((NodeId, usize), Outline)>, + /// The closed subpaths with a curve, listed at the press (none when it found no subpath to + /// start from). + listed: Vec, + /// The common tangents of the press's subpath and each subpath the pointer came near. + kept: Vec<((NodeId, usize), Vec)>, + /// The line of the last snap. + line: Option<(Point, Point)>, +} + +/// The snap applies: Smart Guides and Snap to Tangent on, and neither pixels nor the grid +/// snapping drawn points instead. +fn applies(cx: &ToolContext) -> bool { + cx.smart_guides && cx.snap_tangent && !cx.snaps_to_pixel(PixelOp::Drawing) && !cx.snap_to_grid +} + +/// The subpath `key` of the document in `cx`. +fn subpath<'a>(cx: &'a ToolContext, key: (NodeId, usize)) -> Option<&'a SubPath> { + match &cx.doc.node(key.0)?.kind { + NodeKind::Path { path, .. } => path.subpaths.get(key.1), + _ => None, + } +} + +/// The subpaths of path `id` a line may start or end on, with their indexes: closed, with at most +/// [`MAX_SEGMENTS`] segments. +fn closed_subpaths<'a>(cx: &'a ToolContext, id: NodeId) -> impl Iterator { + let subpaths = match cx.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, .. }) => path.subpaths.as_slice(), + _ => &[], + }; + subpaths.iter().enumerate().filter(|(_, sp)| sp.closed && sp.segment_count() <= MAX_SEGMENTS) +} + +/// How far `p` lies from `sp` (its segments whose control bounds come within `reach` of `p`); none +/// when no segment comes that near. +fn distance(sp: &SubPath, p: Point, reach: f64) -> Option { + let mut best: Option = None; + for k in 0..sp.segment_count() { + let c = sp.segment(k); + let b = Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2); + if !b.inflate(reach, reach).contains(p) { + continue; + } + let d = c.nearest(p, 1e-9).distance_sq.sqrt(); + if best.is_none_or(|e| d < e) { + best = Some(d); + } + } + best +} + +/// Whether `sp` has a curved segment. +fn curved(sp: &SubPath) -> bool { + (0..sp.segment_count()).any(|k| !sp.segment_is_line(k)) +} + +impl TangentLine { + /// Start a drag pressed at `start` (where the pointer went down): the subpath under it, when it + /// is a convex closed path with a curve, and then the closed subpaths with a curve in the window + /// the line may end on, by their bounds. The press looks at the segments of the paths whose + /// bounds reach it only, and lists nothing when it lands on no such subpath, or when `held` (an + /// anchor, center or crossing the press snapped to) lies off that subpath. + pub(crate) fn press(&mut self, cx: &ToolContext, start: Point, held: Option) { + *self = Self::default(); + if !applies(cx) || !start.x.is_finite() || !start.y.is_finite() { + return; + } + let tol = cx.snap_tol(); + // The paths with a closed subpath, by their finite bounds. + let closed = |n: &Node| match &n.kind { + NodeKind::Path { path, .. } if path.subpaths.iter().any(|sp| sp.closed) => { + n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) + } + _ => None, + }; + // The subpaths under the press: at most as many segments as Smart Guides gather. + let mut on: Option<(f64, (NodeId, usize))> = None; + let mut budget = BUDGET; + walk_but(&cx.doc.layers, &HashSet::new(), &mut |n| { + if budget == 0 || !closed(n).is_some_and(|b| b.inflate(tol, tol).contains(start)) { + return; + } + for (si, sp) in closed_subpaths(cx, n.id) { + let Some(left) = budget.checked_sub(sp.segment_count()) else { return }; + budget = left; + if let Some(d) = distance(sp, start, tol) + && d <= tol + && curved(sp) + && on.is_none_or(|(e, _)| d < e) + { + on = Some((d, (n.id, si))); + } + } + }); + // A path that bends inward somewhere has no tangent of this kind: the line keeps its start. + let Some(from) = on.and_then(|(_, key)| Some((key, Outline::convex(subpath(cx, key)?).ok()?))) else { return }; + // A press held by an anchor, center or crossing off that path starts the line there. + if let Some(q) = held + && !subpath(cx, from.0).and_then(|sp| distance(sp, q, tol)).is_some_and(|d| d <= 1e-6 * tol.max(1.0)) + { + return; + } + let from_key = from.0; + self.from = Some(from); + // The subpaths the line may end on: closed ones with a curve, of the paths in the window, + // at most as many segments as Smart Guides gather. + let window = visible(cx); + let listed = &mut self.listed; + let mut budget = BUDGET; + walk_but(&cx.doc.layers, &HashSet::new(), &mut |n| { + if budget == 0 || !closed(n).is_some_and(|b| window.is_none_or(|v| b.intersect(v).area() > 0.0 || v.contains(b.center()))) { + return; + } + for (si, sp) in closed_subpaths(cx, n.id) { + let Some(left) = budget.checked_sub(sp.segment_count()) else { return }; + budget = left; + let mut bounds: Option = None; + for k in 0..sp.segment_count() { + let c = sp.segment(k); + let b = Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2); + bounds = Some(bounds.map_or(b, |r| r.union(b))); + } + if let Some(bounds) = + bounds.filter(|b| curved(sp) && (n.id, si) != from_key && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) + { + listed.push(Listed { key: (n.id, si), bounds }); + } + } + }); + } + + /// The line for the pointer at `p`: on the nearest subpath whose outline lies within the + /// snapping tolerance of `p` and that has a common tangent with the press's subpath, the + /// tangent whose touch point on it is nearest `p`; none when there is none. A subpath farther + /// from `p` than `rival` (an anchor, center or crossing the pointer snaps to otherwise) gives + /// way to it; its own anchors, which lie on its outline, do not. + pub(crate) fn snap(&mut self, cx: &ToolContext, p: Point, rival: Option) -> Option<(Point, Point)> { + let line = self.find(cx, p, rival); + self.line = line; + line + } + + fn find(&mut self, cx: &ToolContext, p: Point, rival: Option) -> Option<(Point, Point)> { + if self.from.is_none() || !applies(cx) || !p.x.is_finite() || !p.y.is_finite() { + return None; + } + let tol = cx.snap_tol(); + let mut near: Vec<(f64, (NodeId, usize))> = vec![]; + for l in self.listed.iter().filter(|l| l.bounds.inflate(tol, tol).contains(p)) { + // The nearest `MAX_NEAR`, in order, kept while scanning. + if let Some(d) = subpath(cx, l.key).and_then(|sp| distance(sp, p, tol)).filter(|d| *d <= tol) { + let at = near.partition_point(|(e, _)| *e <= d); + if at < MAX_NEAR { + near.insert(at, (d, l.key)); + near.truncate(MAX_NEAR); + } + } + } + for (d, key) in near { + if rival.is_some_and(|r| r < d - 1e-6 * tol) { + return None; + } + let Some(sp) = subpath(cx, key) else { continue }; + let mut best: Option<(f64, Point, Point)> = None; + for t in self.tangents(cx, key) { + // Where the paths touch each other, the tangent's ends are not both on the paths. + let on_b = distance(sp, t.to, tol).is_some_and(|e| e <= 1e-6 * tol.max(1.0)); + if !on_b || t.from.distance(t.to) <= tol { + continue; + } + let dist = t.to.distance(p); + // On a tie the line of the last move stays, so it does not flicker. + let same = self.line == Some((t.from, t.to)); + if best.is_none_or(|(e, ..)| dist < e - 1e-9 || (same && dist <= e + 1e-9)) { + best = Some((dist, t.from, t.to)); + } + } + if let Some((_, a, b)) = best { + return Some((a, b)); + } + } + None + } + + /// The common tangents of the press's subpath and subpath `key`, worked out on first use. + fn tangents(&mut self, cx: &ToolContext, key: (NodeId, usize)) -> Vec { + if let Some((_, t)) = self.kept.iter().find(|(k, _)| *k == key) { + return t.clone(); + } + let Some((_, from)) = &self.from else { return vec![] }; + let all = subpath(cx, key).and_then(|sp| Outline::convex(sp).ok()).and_then(|o| common_tangents(from, &o).ok()).unwrap_or_default(); + if self.kept.len() >= MAX_KEPT { + self.kept.remove(0); + } + self.kept.push((key, all.clone())); + all + } + + /// The line of the last snap, if it found one. + pub(crate) fn line(&self) -> Option<(Point, Point)> { + self.line + } + + /// Forget the last snap's line for a move that does not snap this way (a modifier is held), + /// keeping the press's subpath for the moves after it. + pub(crate) fn drop_line(&mut self) { + self.line = None; + } + + /// End the drag. + pub(crate) fn clear(&mut self) { + *self = Self::default(); + } + + /// The guides of the last snap: the line, and the "tangent" label at both ends. + pub(crate) fn guides(&self, cx: &ToolContext) -> Vec { + let Some((a, b)) = self.line else { return vec![] }; + let color = cx.smart_guide_color; + let mut out = vec![]; + if cx.alignment_guides { + out.push(Overlay::Line { a, b, color, dashed: false }); + } + if cx.anchor_path_labels { + out.extend([a, b].map(|p| Overlay::Label { p, text: "tangent".into(), color })); + } + out + } +} diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index d7ee8ecdd8..4c8a0d189a 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -365,7 +365,7 @@ impl SnapKey { } /// The part of the document the window shows (none headless: all of it). -fn visible(cx: &ToolContext) -> Option { +pub(super) fn visible(cx: &ToolContext) -> Option { let s = cx.screen?; let (w, h) = s.size; Some(Rect::from_points(s.at(0.0, 0.0), s.at(w, h)).union_pt(s.at(w, 0.0)).union_pt(s.at(0.0, h))) @@ -429,6 +429,35 @@ impl DrawSnap { self.snap(cx, p, from) } + /// How far from `p` the nearest Smart Guides point (an anchor or a center) or crossing of the + /// targets lies, when one is within the snapping tolerance: none otherwise, and none while + /// pixels or the grid snap instead. + pub(crate) fn point_within_reach(&self, cx: &ToolContext, p: Point) -> Option { + let Some((_, PointSnap { targets: Some((t, tol)), .. })) = &self.targets else { return None }; + if !cx.smart_guides { + return None; + } + let tol = cx.tol(*tol); + let point = t.nearest_point(p, tol).map(|(q, _)| q.distance(p)); + let crossing = t.crossing(p, tol).map(|q| q.distance(p)); + match (point, crossing) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } + } + + /// Whether `q`, where a point at `p` snapped to, is the nearest Smart Guides point (an anchor or + /// a center) or the nearest crossing of the targets within the snapping tolerance of `p`. + pub(crate) fn snapped_to_point(&self, cx: &ToolContext, p: Point, q: Point) -> bool { + let Some((_, PointSnap { targets: Some((t, tol)), .. })) = &self.targets else { return false }; + if !cx.smart_guides { + return false; + } + let tol = cx.tol(*tol); + let at = |a: Point| a.distance(q) <= 1e-9 * tol.max(1.0); + t.nearest_point(p, tol).is_some_and(|(a, _)| at(a)) || t.crossing(p, tol).is_some_and(at) + } + /// The guides of the last snap. pub fn guides(&self) -> &[Overlay] { &self.guides diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index e3e6abeef6..c846f1a55a 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -64,7 +64,7 @@ pub struct Targets { } /// How many anchors, and how many segments, the targets gather at most. -const BUDGET: usize = 20_000; +pub(super) const BUDGET: usize = 20_000; /// What [`Targets::collect_inner`] gathers from each path besides its anchors and bounds. #[derive(Clone, Copy, PartialEq)] @@ -88,7 +88,7 @@ fn within(sorted: &[T], key: impl Fn(&T) -> f64, v: f64, tol: f64) -> &[T] { /// Visit `nodes` and everything inside them, but the nodes in `skip`, the hidden nodes and /// everything inside those: one pass, however many are skipped. A Shaper Group's original /// shapes, its first child, are not shown and are skipped too. -fn walk_but<'a>(nodes: &'a [Arc], skip: &HashSet, f: &mut impl FnMut(&'a Node)) { +pub(super) fn walk_but<'a>(nodes: &'a [Arc], skip: &HashSet, f: &mut impl FnMut(&'a Node)) { for n in nodes.iter().filter(|n| n.visible && !skip.contains(&n.id)) { f(n); if let Some(ch) = n.children() { @@ -898,7 +898,7 @@ impl Targets { /// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing /// nearest `p` within `tol` ("intersect", #1602). - fn crossing(&self, p: Point, tol: f64) -> Option { + pub(super) fn crossing(&self, p: Point, tol: f64) -> Option { self.crossing_with(p, tol, &self.rulers) } diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..67d23be463 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -5,7 +5,9 @@ //! Illustrator). ↑/↓ during a polygon/star drag change the side/point count; during a star drag, //! Ctrl/Cmd keeps the inner radius where it is while the outer one follows the pointer, and Alt //! keeps the star's shoulders straight (#812). The start point and -//! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. +//! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. With Snap +//! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a +//! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]). //! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed. //! //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, @@ -22,7 +24,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag}; -use crate::guides::{DrawSnap, Leave, PointSnap, Targets, square}; +use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square}; use crate::pie::{self, PieDrag}; use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -95,6 +97,8 @@ pub struct ShapeTool { pub line_angle: f64, pub fill_line: bool, snap: DrawSnap, + /// Snap to Tangent for a line from one curve to another: both ends on a common tangent. + tangent_line: TangentLine, /// The options a drag's keys and Ctrl/Cmd change, as they were when the drag began: Escape /// puts them back. before_drag: Option, @@ -150,6 +154,7 @@ impl ShapeTool { star_ratio: 0.5, inner: None, snap: DrawSnap::default(), + tangent_line: TangentLine::default(), line_length: 100.0, line_angle: 0.0, fill_line: false, @@ -547,6 +552,12 @@ impl Tool for ShapeTool { return out; } let p = self.snap.press(cx, ev.pos, &[], None); + if self.id == "lineSegment" { + // The pressed spot finds the curve; a press that snapped to an anchor, center + // or crossing off that curve keeps the line's start there. + let held = self.snap.snapped_to_point(cx, ev.pos, p).then_some(p); + self.tangent_line.press(cx, ev.pos, held); + } self.start = Some(p); self.last = ev.pos; self.began = false; @@ -556,6 +567,7 @@ impl Tool for ShapeTool { } PointerKind::Drag => { let Some(mut s) = self.start else { return vec![] }; + let raw = ev.pos; let pos = self.snap.drag(cx, ev.pos, self.leave(cx, s, ev.mods).as_ref()); let ev = &PointerEvent { pos, ..*ev }; // The inner radius of the star the last drag showed, with the ratio it drew with: @@ -564,6 +576,10 @@ impl Tool for ShapeTool { let ratio = if self.mods.alt { straight_ratio(self.points).unwrap_or(self.star_ratio) } else { self.star_ratio }; let shown = (self.last - s).hypot() * ratio; space_moves(&mut s, &mut self.last, ev, self.began); + if ev.mods.space && self.began { + // The start no longer lies on the pressed path. + self.tangent_line.clear(); + } self.start = Some(s); self.mods = ev.mods; if self.id == "star" { @@ -578,13 +594,25 @@ impl Tool for ShapeTool { self.before_drag = Some(self.drag_options()); out.push(Action::Begin(self.label().into())); } - let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); + // Snap to Tangent: a line pressed on one curve and ending near another moves both + // its ends onto a common tangent of the two, unless Shift, Alt or Space is held or + // an anchor or crossing nearer the pointer pulls it. + let tangent = if self.id == "lineSegment" && !(ev.mods.shift || ev.mods.alt || ev.mods.space) { + let rival = self.snap.point_within_reach(cx, raw); + self.tangent_line.snap(cx, raw, rival) + } else { + self.tangent_line.drop_line(); + None + }; + let (a, b) = tangent.unwrap_or((s, ev.pos)); + let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle); out.push(Action::Preview(c, v)); out } PointerKind::Up => { let Some(s) = self.start.take() else { return vec![] }; self.snap.clear(); + self.tangent_line.clear(); self.inner = None; self.before_drag = None; if self.began { @@ -658,6 +686,7 @@ impl Tool for ShapeTool { self.restore_drag_options(o); } self.snap.clear(); + self.tangent_line.clear(); vec![Action::Cancel] } else { vec![] @@ -706,7 +735,9 @@ impl Tool for ShapeTool { Some(WidgetDrag::Pie(d)) => return d.overlays(cx), None => {} } - let mut o = self.snap.guides().to_vec(); + // A line on a common tangent shows that snap's guides, and its length and angle. + let tangent = self.tangent_line.line().filter(|_| self.start.is_some()); + let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() }; o.extend(self.guides.iter().cloned()); if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); @@ -714,7 +745,8 @@ impl Tool for ShapeTool { if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); let text = if self.id == "lineSegment" { - cx.segment_measure_label(s, self.last) + let (a, b) = tangent.unwrap_or((s, self.last)); + cx.segment_measure_label(a, b) } else { // A box's size as drawn (from its centre with Alt, square with Shift). match self.id { diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index c76eef404e..1a72a0fbbf 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -430,6 +430,259 @@ fn line_segment_options_and_fill_line() { assert_eq!(t.command(a, b, Mods::default()).1["fill"], json!(true)); } +/// A document holding the closed paths `paths`, unselected. +fn doc_with_paths(paths: Vec) -> vectorcraft_doc::Document { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + d +} + +/// The circle of radius `r` about `c`, as the Ellipse tool draws it. +fn circle(c: Point, r: f64) -> vectorcraft_geom::PathData { + vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)) +} + +/// The ends of the line a Line Segment drag from `press` through `drag` to `to` (with `mods`) +/// previews last, and the drag's actions. +fn line_drag(c: &ToolContext, press: Point, drag: Point, to: Point, mods: Mods) -> ((Point, Point), Vec) { + let mut t = ShapeTool::new("lineSegment"); + t.pointer(c, &PointerEvent::new(PointerKind::Down, press.x, press.y).with_mods(mods)); + let mut all = t.pointer(c, &PointerEvent::new(PointerKind::Drag, drag.x, drag.y).with_mods(mods)); + all.extend(t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods))); + let Some(Action::Preview(cmd, v)) = all.last().cloned() else { panic!("a preview: {all:?}") }; + assert_eq!(cmd, "shape.line"); + let f = |k: &str| v[k].as_f64().unwrap(); + let line = (Point::new(f("x1"), f("y1")), Point::new(f("x2"), f("y2"))); + all.extend(t.pointer(c, &PointerEvent::new(PointerKind::Up, to.x, to.y).with_mods(mods))); + (line, all) +} + +/// Snap to Tangent: a line pressed on one circle and dragged near another lands on a common +/// tangent of the two, both ends moving to where it touches them. Near the second circle's top it +/// is the outer tangent, near its bottom left the one crossing between them, each against the +/// closed form (the drawn circles are within 0.03% of round). The guides show the line and a +/// "tangent" label at each end, and the length label measures the tangent line. +#[test] +fn a_line_from_one_circle_to_another_lands_on_their_common_tangent() { + let (c1, r1, c2, r2) = (Point::new(100.0, 250.0), 40.0, Point::new(300.0, 250.0), 60.0); + let d = doc_with_paths(vec![circle(c1, r1), circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + // A drawn circle's radius is off by up to 0.03%, which moves the touch points along the line by + // up to about 0.1 pt here; the line's distance from each center stays within 0.03 pt. + let near = |a: Point, b: Point| (a - b).hypot() < 0.15; + let off_by = |(a, b): (Point, Point), c: Point| ((b - a).cross(c - a) / (b - a).hypot()).abs(); + let touches = |line: (Point, Point)| (off_by(line, c1) - r1).abs() < 0.03 && (off_by(line, c2) - r2).abs() < 0.03; + // A normal n with n · (c2 - c1) / |c2 - c1| = k: the line touches the first circle at + // c1 + r1 n, and the second at c2 + r2 n (outer, k = (r1 - r2) / d) or c2 - r2 n (crossing, + // k = (r1 + r2) / d). + let normal = |k: f64, up: bool| Vec2::new(k, if up { -1.0 } else { 1.0 } * (1.0 - k * k).sqrt()); + let outer = normal((r1 - r2) / 200.0, true); + let (on_a, on_b) = (c1 + outer * r1, c2 + outer * r2); + let press = Point::new(100.0, 210.0); + let ((a, b), actions) = line_drag(&c, press, Point::new(200.0, 200.0), on_b + Vec2::new(0.5, 0.7), Mods::default()); + assert!(near(a, on_a) && near(b, on_b) && touches((a, b)), "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + // One gesture: one undo step. + assert_eq!(actions.iter().filter(|a| matches!(a, Action::Begin(_))).count(), 1, "{actions:?}"); + assert_eq!(actions.last(), Some(&Action::Commit)); + let crossing = normal((r1 + r2) / 200.0, false); + let (on_a, on_b) = (c1 + crossing * r1, c2 - crossing * r2); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 260.0), on_b + Vec2::new(-0.6, 0.4), Mods::default()); + assert!(near(a, on_a) && near(b, on_b) && touches((a, b)), "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + // The guides and the length label while dragging. + let mut t = ShapeTool::new("lineSegment"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, press.x, press.y)); + let to = on_b + Vec2::new(-0.6, 0.4); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let o = t.overlays(&c); + let tangents: Vec = o + .iter() + .filter_map(|o| match o { + Overlay::Label { p, text, .. } if text == "tangent" => Some(*p), + _ => None, + }) + .collect(); + assert_eq!(tangents.len(), 2, "{o:?}"); + assert!(near(tangents[0], on_a) && near(tangents[1], on_b), "{o:?}"); + let (a, b) = t.tangent_line.line().unwrap(); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.segment_measure_label(a, b))), "{o:?}"); + // Escape ends it. + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.tangent_line.line().is_none() && t.overlays(&c).is_empty()); +} + +/// The tangent of a turned ellipse and a circle, against the ellipse's own closed form: the +/// support value of the ellipse x = c + M u (|u| = 1) along n is c · n + |Mᵀ n|, touched at +/// c + M Mᵀ n / |Mᵀ n|; the outer tangents are the n where it equals the circle's c₂ · n + r. +#[test] +fn a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle() { + let ce = Point::new(100.0, 250.0); + let turn = Affine::rotate_about(30f64.to_radians(), ce); + let ellipse = vectorcraft_geom::shapes::ellipse(Rect::new(40.0, 220.0, 160.0, 280.0)).transformed(turn); + let (c2, r2) = (Point::new(320.0, 260.0), 40.0); + let d = doc_with_paths(vec![ellipse, circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + // M maps the unit circle onto the ellipse's axes: 60 and 30 long, turned 30°. + let (cos, sin) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let m = [[60.0 * cos, -30.0 * sin], [60.0 * sin, 30.0 * cos]]; + let mt_n = |n: Vec2| Vec2::new(m[0][0] * n.x + m[1][0] * n.y, m[0][1] * n.x + m[1][1] * n.y); + let g = |a: f64| { + let n = Vec2::new(a.cos(), a.sin()); + ce.to_vec2().dot(n) + mt_n(n).hypot() - c2.to_vec2().dot(n) - r2 + }; + // The roots of g over the angle, by sampling and bisection; the one with n pointing up. + let mut roots = vec![]; + let steps = 3600; + for k in 0..steps { + let (mut lo, mut hi) = (k as f64 * std::f64::consts::TAU / steps as f64, (k + 1) as f64 * std::f64::consts::TAU / steps as f64); + if g(lo).signum() == g(hi).signum() { + continue; + } + for _ in 0..80 { + let mid = (lo + hi) / 2.0; + if g(mid).signum() == g(lo).signum() { lo = mid } else { hi = mid } + } + roots.push(lo); + } + let n = roots.iter().map(|a| Vec2::new(a.cos(), a.sin())).find(|n| n.y < 0.0).unwrap(); + let w = mt_n(n); + let on_a = ce + Vec2::new(m[0][0] * w.x + m[0][1] * w.y, m[1][0] * w.x + m[1][1] * w.y) / w.hypot(); + let on_b = c2 + n * r2; + // The press on the ellipse's turned top anchor. + let press = turn * Point::new(100.0, 220.0); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 200.0), on_b + Vec2::new(0.4, -0.5), Mods::default()); + assert!((a - on_a).hypot() < 0.05 && (b - on_b).hypot() < 0.05, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); +} + +/// The line keeps its start where it was pressed, as before, when Snap to Tangent is off, Smart +/// Guides are off, Shift or Alt is held, or the pressed path bends inward somewhere (it has no +/// tangent of this kind). Where the tangent touches the second circle at one of its anchors, the +/// tangent still wins over that anchor. +#[test] +fn a_line_keeps_its_start_without_a_tangent_snap() { + use vectorcraft_geom::{BezPath, PathData}; + let (c1, c2, r) = (Point::new(100.0, 250.0), Point::new(300.0, 250.0), 50.0); + let d = doc_with_paths(vec![circle(c1, r), circle(c2, r)]); + let (s, p) = (Selection::default(), paint()); + let on = cx(&d, &s, &p); + // The pointer next to the second circle's top anchor, where the outer tangent touches it. + let to = Point::new(300.6, 200.4); + // A press on the first circle 30° round from its top, away from its anchors. + let pressed = c1 + Vec2::new(r * 0.5, -r * 3f64.sqrt() / 2.0); + // With Snap to Tangent on, the start moves to the first circle's top. + let ((a, b), _) = line_drag(&on, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - Point::new(100.0, 200.0)).hypot() < 0.05 && (b - Point::new(300.0, 200.0)).hypot() < 0.05, "{a:?} {b:?}"); + let off = [ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }, ToolContext { smart_guides: false, ..cx(&d, &s, &p) }]; + for c in &off { + let ((a, _), _) = line_drag(c, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - pressed).hypot() < 0.05, "{a:?}"); + } + for mods in [Mods { shift: true, ..Mods::default() }, Mods { alt: true, ..Mods::default() }] { + let ((a, b), _) = line_drag(&on, pressed, Point::new(200.0, 190.0), to, mods); + // Alt draws the line from its middle. + let start = if mods.alt { a.midpoint(b) } else { a }; + assert!((start - pressed).hypot() < 0.05, "{a:?} {b:?}"); + } + // Space moves the line being drawn, its start off the pressed circle: the snap lets go. + let mut t = ShapeTool::new("lineSegment"); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&on, &PointerEvent::new(PointerKind::Down, pressed.x, pressed.y)); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 200.0, 170.0)); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 210.0, 160.0).with_mods(space)); + let a = t.pointer(&on, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("a preview: {a:?}") }; + let start = Point::new(v["x1"].as_f64().unwrap(), v["y1"].as_f64().unwrap()); + assert!((start - (pressed + Vec2::new(10.0, -10.0))).hypot() < 1.0, "{start:?}"); + // A crescent: closed and curved, but its lower side bends inward. The press on its top + // keeps its start. + let mut bp = BezPath::new(); + bp.move_to((60.0, 250.0)); + bp.curve_to((60.0, 190.0), (140.0, 190.0), (140.0, 250.0)); + bp.curve_to((120.0, 220.0), (80.0, 220.0), (60.0, 250.0)); + bp.close_path(); + let d = doc_with_paths(vec![PathData::from_bezpath(&bp), circle(c2, r)]); + let c = cx(&d, &s, &p); + let crest = Point::new(100.0, 205.0); + let ((a, _), _) = line_drag(&c, crest, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - crest).hypot() < 1e-6, "{a:?}"); +} + +/// The upper outer common tangent of the circles about `c1` and `c2` with radii `r1` and `r2` +/// (`c2` to the right): where it touches each. +fn upper_outer_tangent(c1: Point, r1: f64, c2: Point, r2: f64) -> (Point, Point) { + let d = c2 - c1; + let u = d / d.hypot(); + let k = (r1 - r2) / d.hypot(); + // n · u = k, with n pointing up (y down). + let n = u * k + Vec2::new(u.y, -u.x) * (1.0 - k * k).sqrt(); + (c1 + n * r1, c2 + n * r2) +} + +/// The pointer only has to come near the second path's outline: anywhere along it, the line takes +/// the tangent whose touch point is nearest the pointer, here one about 30 pt away. A press on a +/// straight side of a convex path with curves (a rounded rectangle's top edge) moves the start +/// onto the corner the tangent touches. +#[test] +fn a_line_near_the_second_path_takes_the_tangent_touching_it_nearest() { + let (c1, r1, c2, r2) = (Point::new(100.0, 250.0), 40.0, Point::new(300.0, 250.0), 60.0); + let d = doc_with_paths(vec![circle(c1, r1), circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (on_a, on_b) = upper_outer_tangent(c1, r1, c2, r2); + // On the second circle's outline, 25° round from its top. + let to = c2 + Vec2::new(r2 * 25f64.to_radians().sin(), -r2 * 25f64.to_radians().cos()); + assert!((to - on_b).hypot() > 25.0); + let ((a, b), _) = line_drag(&c, Point::new(100.0, 210.0), Point::new(200.0, 200.0), to, Mods::default()); + assert!((a - on_a).hypot() < 0.15 && (b - on_b).hypot() < 0.15, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + + // A rounded rectangle whose top right corner is a quarter circle of radius 20 about (140, 220). + let rounded = vectorcraft_geom::shapes::rounded_rectangle(Rect::new(40.0, 200.0, 160.0, 300.0), 20.0); + let (c2, r2) = (Point::new(320.0, 260.0), 40.0); + let d = doc_with_paths(vec![rounded, circle(c2, r2)]); + let c = cx(&d, &s, &p); + let (on_a, on_b) = upper_outer_tangent(Point::new(140.0, 220.0), 20.0, c2, r2); + let press = Point::new(90.0, 200.0); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 200.0), Point::new(320.0, 220.5), Mods::default()); + assert!((a - on_a).hypot() < 0.15 && (b - on_b).hypot() < 0.15, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); +} + +/// No tangent snap when the second path bends inward somewhere (a crescent), or when the press +/// snapped to an anchor of other art lying beside the first circle: the start stays where the +/// press put it. +#[test] +fn a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start() { + use vectorcraft_geom::{BezPath, PathData}; + let (c1, r) = (Point::new(100.0, 250.0), 50.0); + let mut bp = BezPath::new(); + bp.move_to((260.0, 250.0)); + bp.curve_to((260.0, 190.0), (340.0, 190.0), (340.0, 250.0)); + bp.curve_to((320.0, 220.0), (280.0, 220.0), (260.0, 250.0)); + bp.close_path(); + let d = doc_with_paths(vec![circle(c1, r), PathData::from_bezpath(&bp)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let pressed = c1 + Vec2::new(r * 0.5, -r * 3f64.sqrt() / 2.0); + // Beside the crescent's top, which lies at (300, 205). + let to = Point::new(300.4, 205.3); + let ((a, b), _) = line_drag(&c, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - pressed).hypot() < 0.05 && (b - to).hypot() < 1.0, "{a:?} {b:?}"); + + // A square whose corner (99, 199) lies about 1 pt outside the first circle's top; a second + // circle to the right. The press snaps to that corner and the line starts there. + let (c2, r2) = (Point::new(300.0, 250.0), 50.0); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(80.0, 180.0, 99.0, 199.0)); + let d = doc_with_paths(vec![circle(c1, r), square, circle(c2, r2)]); + let c = cx(&d, &s, &p); + let corner = Point::new(99.0, 199.0); + let ((a, _), _) = line_drag(&c, Point::new(99.3, 199.3), Point::new(200.0, 190.0), Point::new(300.6, 200.4), Mods::default()); + assert!((a - corner).hypot() < 1e-6, "{a:?}"); +} + /// #5477: with a shape tool, a drag on a selected live rectangle's corner widget rounds its /// corners (one undo step) and a drag on a live ellipse's pie widget sets its pie angle, as with /// the Selection tool; the pointer over a widget is the Selection tool's. A press anywhere else, or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c003439bb4..8499f23a5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -611,6 +611,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. From ca822f41f792045b1d049969d11d819844056b98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:51:00 -0800 Subject: [PATCH 32/50] Check Spelling: Ignore and Change All reach every word past the check limit text.spelling.check listed at most 10,000 words and always started each type object at its first byte, so the dialog could not go on inside an object. With 10,001 unknown words in one object, Ignore ended the check after the first 10,000. Change All stopped when a round changed nothing, so a target after 10,000 other unknown words was never reached. Follow-up to #7744; part of #4936. - text.spelling.check takes from {id, byte}, which goes on from that byte of that type object and then the objects after it, and max (1 to 10,000). The paragraphs before the one that holds from are not checked again. - The dialog keeps the words a check lists after the one shown, and Ignore and Ignore All take the next word from them. A new check goes on from the last word listed once they run out. Every word is reached, in a selected group's type too. - text.spelling.change {to, words} replaces every listed word in one undo step and lays each object out once. Change All finds every occurrence with one check after another, then changes them with it. - Change and Change All to the word shown make no edit and no undo step. - When another command changes the document or the custom dictionary while the dialog is open, the next step checks the scope again from its start. An ignored occurrence stays skipped while the same word is at the same bytes. --- crates/engine/src/cmd/spelling.rs | 137 ++- crates/engine/src/tests/spelling.rs | 107 +++ crates/ui-egui/src/dialogs/check_spelling.rs | 935 ++++++++++++++----- docs/mcp.md | 17 +- 4 files changed, 935 insertions(+), 261 deletions(-) diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 35d1a12774..03f52d2e19 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -7,17 +7,20 @@ //! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All //! (`text.spelling.ignoreAll`) skips a word in the active document only. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use std::sync::atomic::{AtomicU64, Ordering}; use craft_proof::{IssueKind, Options, ProofLang}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject}; +use vectorcraft_text::edit; use super::menucmds::whole_or; +use super::textedit::text_mut; +use super::typecmd::refresh_bounds; use super::typemenu::{all_texts, text_ids}; -use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; /// Most unknown words one check lists; past it the result says `more`. pub const MAX_WORDS: usize = 10_000; @@ -36,10 +39,19 @@ pub fn specs() -> Vec { "Check Spelling", [], None, - "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one", + "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one", has_doc, check ), + cmd!( + "text.spelling.change", + "Change All", + [], + None, + "{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count}", + has_doc, + change_words + ), cmd!( query "text.spelling.suggest", "Spelling Suggestions", @@ -107,22 +119,42 @@ pub fn specs() -> Vec { } /// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked -/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them. +/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at +/// `from` when it is given. fn check(s: &mut Session, p: &Value) -> Result { const C: &str = "text.spelling.check"; // Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than // a check of the whole document. - let ids = match p.get("ids").filter(|v| !v.is_null()) { + let mut ids = match p.get("ids").filter(|v| !v.is_null()) { Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)), None => all_texts(&s.doc()?.doc), }; + let max = whole_or(p, "max", MAX_WORDS as u64, C)?; + let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?; let st = s.doc()?; + // Where the last check stopped: the objects before it are skipped, and the bytes of its object + // before `byte`. + let mut from_byte = 0; + if let Some(from) = p.get("from").filter(|v| !v.is_null()) { + let (id, byte) = from_param(from, C)?; + let Some(pos) = ids.iter().position(|i| i.0 == id) else { + return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked"))); + }; + let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else { + return Err(bad(C, format!("`from.id` {id} is not a type object"))); + }; + let len = t.plain_text().len(); + from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?; + ids.drain(..pos); + } let mut words = vec![]; let mut more = false; for id in ids { let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue }; let text = t.plain_text(); - let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len()); + // Only the first object listed starts part way. + let from = std::mem::take(&mut from_byte); + let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len()); for m in found { let Some(word) = text.get(m.range.clone()) else { continue }; words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() })); @@ -135,6 +167,84 @@ fn check(s: &mut Session, p: &Value) -> Result { Ok(json!({ "words": words, "more": more })) } +/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers. +fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> { + let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) { + return Err(bad(command, format!("`from` takes id and byte, not `{k}`"))); + } + let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?; + let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?; + Ok((id, byte)) +} + +/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words +/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out +/// once at the end rather than once for each word. +fn change_words(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.change"; + let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string(); + let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?; + let mut by_id: BTreeMap> = BTreeMap::new(); + for w in list { + let (id, start, end) = word_param_range(w, C)?; + by_id.entry(NodeId(id)).or_default().push((start, end)); + } + // Every word checked against its object before anything changes. + let st = s.doc()?; + for (id, ranges) in &mut by_id { + let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { + return Err(bad(C, format!("{} is not a type object", id.0))); + }; + let text = t.plain_text(); + ranges.sort_unstable(); + let mut last_end = 0; + for &(a, b) in ranges.iter() { + if a >= b || text.get(a..b).is_none() { + return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0))); + } + if a < last_end { + return Err(bad(C, format!("words of {} overlap at byte {a}", id.0))); + } + last_end = b; + } + } + let changed: usize = by_id.values().map(Vec::len).sum(); + if changed == 0 { + return Ok(json!({ "changed": 0 })); + } + s.edit("Change All", |d, _| { + for (id, ranges) in &by_id { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + for &(a, b) in ranges.iter().rev() { + // Paragraph styles and ruby follow each edit, as in `text.editRange`. + t.splice_paras(a, b, &to); + edit::replace_range(&mut t.runs, a, b, &to); + t.ruby_after_replace(a, b, to.len()); + } + refresh_bounds(t); + } + Ok(()) + })?; + Ok(json!({ "changed": changed })) +} + +/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers. +fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> { + let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) { + return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`"))); + } + let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?; + let byte = |k: &str| { + o.get(k) + .and_then(Value::as_u64) + .and_then(|b| usize::try_from(b).ok()) + .ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number"))) + }; + Ok((id, byte("start")?, byte("end")?)) +} + /// One word of a type object its dictionaries don't know ([`misspellings`]). #[derive(Clone, Debug, PartialEq)] pub struct Misspelling { @@ -149,6 +259,13 @@ pub struct Misspelling { /// All words). At most `max` of them; the flag says the list was cut short there. What /// `text.spelling.check` lists for one object, and what Auto Spell Check underlines. pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> (Vec, bool) { + misspellings_from(t, ignored, 0, max) +} + +/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at +/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since +/// craft-proof reads a paragraph's language from all of it. +pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet, from: usize, max: usize) -> (Vec, bool) { let text = t.plain_text(); // Each run in its own language, at its bytes of the plain text. let mut spans: Vec<(Range, ProofLang)> = Vec::with_capacity(t.runs.len()); @@ -166,6 +283,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> ( let mut para_start = 0; for para in text.split('\n') { let para_end = para_start + para.len(); + // No word of a paragraph that ends at `from` starts there or later. + if para_end <= from { + para_start = para_end + 1; + continue; + } let para_spans: Vec<(Range, ProofLang)> = spans .iter() .filter_map(|(r, lang)| { @@ -178,6 +300,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> ( continue; } let (start, end) = (para_start + issue.start, para_start + issue.end); + if start < from { + continue; + } let Some(word) = text.get(start..end) else { continue }; if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) { continue; diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index dd10df1597..6142939a33 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -345,6 +345,113 @@ fn misspellings_of_one_object_are_what_the_check_lists() { assert_eq!(found.iter().map(|m| m.range.clone()).collect::>(), [listed[0].clone(), listed[2].clone()]); } +/// The (id, start, word) of each word a check lists, and its `more`. +fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) { + let r = run(s, "text.spelling.check", p); + let words = r["words"] + .as_array() + .unwrap() + .iter() + .map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string())) + .collect(); + (words, r["more"].as_bool().unwrap()) +} + +/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of +/// that type object first, then the objects after it, and nothing listed twice. +#[test] +fn a_check_goes_on_from_where_the_last_one_stopped() { + let mut s = session(); + let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx"); + let b = text(&mut s, 100.0, "zzqqx"); + let (first, more) = listed(&mut s, json!({"max": 2})); + assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true)); + // From the end of the second word: the third, in the next paragraph of the same object, not + // the start of the next object. + let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2})); + assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false)); + // A byte inside a word starts from the next word. + let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}})); + assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string()))); + // `from` follows the ids given, groups' type included. + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1})); + assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true)); + let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1})); + assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false)); + let bad = [ + json!({"from": {"id": a.0}}), + json!({"from": {"id": a.0, "byte": -1}}), + json!({"from": {"id": a.0, "byte": 1000}}), + json!({"from": {"id": a.0, "byte": 0, "x": 1}}), + json!({"from": a.0}), + json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}), + json!({"max": 0}), + json!({"max": 10_001}), + json!({"max": "2"}), + ]; + for p in bad { + assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused"); + } +} + +/// One type object with one unknown word more than a check lists: going on from the last word +/// listed reaches the last one. +#[test] +fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() { + use crate::cmd::spelling::MAX_WORDS; + let mut s = session(); + let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" ")); + let r = run(&mut s, "text.spelling.check", json!({})); + let words = r["words"].as_array().unwrap(); + assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true))); + let end = words.last().unwrap()["end"].as_u64().unwrap(); + let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}})); + assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false)); +} + +/// The plain text of type object `id`. +fn plain(s: &Session, id: NodeId) -> String { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not type"), + } +} + +/// Change All's command replaces every word listed, in several objects, as one undo step, and +/// refuses a list with any word not in its object's text, changing nothing. +#[test] +fn change_all_replaces_every_word_listed_in_one_undo_step() { + let mut s = session(); + let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw"); + let b = text(&mut s, 100.0, "é qzxvw"); + let depth = s.doc().unwrap().history.undo.len(); + let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]); + let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words})); + assert_eq!(r["changed"], 4); + assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string())); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string())); + let bad = [ + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}), + json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}), + json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}), + json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}), + json!({"to": "x", "words": {"id": a.0}}), + json!({"words": []}), + ]; + for p in bad { + assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused"); + } + assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list"); + assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0); +} + /// Each change to the custom dictionary moves its generation on, whether it is saved or not, so /// what Auto Spell Check found before is checked again. #[test] diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs index 5f0bb8693e..21eae512b0 100644 --- a/crates/ui-egui/src/dialogs/check_spelling.rs +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -11,10 +11,20 @@ //! - `change_to`: the replacement word (from suggestions or typed) //! - `node_id`, `start`, `end`, `lang`: location of the current misspelling //! - `ids`: object IDs checked (None: entire document) -//! - `skipped`: list of `[node_id, start]` skipped by Ignore +//! - `skipped`: list of `[node_id, start, word]` skipped by Ignore, which Change All leaves alone +//! - `queue`: the words the last check listed after the one shown, last first; `queue_more` +//! whether that check had more, and `queue_from` (`[node_id, byte]`) where the next check goes +//! on from +//! - `revision`: `[document revision, custom dictionary generation]` as of the word shown; when +//! either has moved, the next step checks the scope again from its start //! - `done`: whether spell checking has finished (or no unrecognized words found) +//! +//! Ignore and Ignore All take the next word from `queue`, and a new check (`text.spelling.check`'s +//! `from`) goes on from `queue_from` once it is empty, through the rest of that type object and +//! then the objects after it, so every word is reached however many come before it. Change All +//! looks through the whole scope, one check after another, before it changes anything. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use serde_json::{Value, json}; @@ -56,30 +66,22 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if app.session.active().is_none() { return Err("no document".into()); } - let doc_uid = app.session.doc().map_err(|e| e.to_string())?.uid; - let (ids, remaining_ids): (Option>, Vec) = { + let (doc_uid, ids) = { let st = app.session.doc().map_err(|e| e.to_string())?; - let selected = &st.selection.objects; - if !selected.is_empty() { - let selected_ids: Vec = selected.iter().map(|n| n.0).collect(); - (Some(selected_ids.clone()), selected_ids) - } else { - let mut all_ordered = Vec::new(); - st.doc.walk(|n| { - if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { - all_ordered.push(n.id.0); - } - }); - (None, all_ordered) - } + // The selection (groups too: the check goes through the type inside them), or, with + // nothing selected, every visible, unlocked type object (the check's default). + let selected: Vec = st.selection.objects.iter().map(|n| n.0).collect(); + (st.uid, (!selected.is_empty()).then_some(selected)) }; let mut d = Dialog::new( KIND, json!({ "doc_uid": doc_uid, "ids": ids, - "remaining_ids": remaining_ids, "skipped": [], + "queue": [], + "queue_more": false, + "queue_from": null, "not_in_dictionary": "", "context": "", "context_before": "", @@ -95,31 +97,69 @@ pub fn open(app: &mut VectorcraftApp) -> Result { "done": false, }), ); - advance(app, &mut d)?; + advance(app, &mut d, None, 1)?; app.ui.dialog = Some(d); Ok(Value::Null) } -fn get_skipped(d: &Dialog) -> Vec<(u64, u64)> { +/// An occurrence Ignore skipped: (id, start, word). The word is kept with its bytes, so after +/// another command moves the text, a different word that now starts there is not skipped. +type Skip = (u64, u64, String); + +fn get_skipped(d: &Dialog) -> BTreeSet { d.fields .get("skipped") .and_then(Value::as_array) .map(|arr| { arr.iter() - .filter_map(|pair| { - let a = pair.as_array()?; - if a.len() == 2 { Some((a[0].as_u64()?, a[1].as_u64()?)) } else { None } + .filter_map(|s| match s.as_array().map(Vec::as_slice) { + Some([id, start, word]) => Some((id.as_u64()?, start.as_u64()?, word.as_str()?.to_string())), + _ => None, }) .collect() }) .unwrap_or_default() } -fn set_skipped(d: &mut Dialog, skipped: &[(u64, u64)]) { - let arr: Vec = skipped.iter().map(|&(id, start)| json!([id, start])).collect(); +fn set_skipped(d: &mut Dialog, skipped: &BTreeSet) { + let arr: Vec = skipped.iter().map(|(id, start, word)| json!([id, start, word])).collect(); d.fields.insert("skipped".into(), json!(arr)); } +/// Whether Ignore skipped this occurrence of a word. +fn is_skipped(skipped: &BTreeSet, w: &Word) -> bool { + skipped.contains(&(w.0, w.1 as u64, w.3.clone())) +} + +/// Moves the Ignore positions in `id` that come after edits there by what each edit changed in +/// length: `edits` are the (start, end) bytes each replaced with `new_len` bytes. +fn shift_skipped(d: &mut Dialog, id: u64, edits: &[(usize, usize)], new_len: usize) { + let skipped = get_skipped(d) + .into_iter() + .map(|(sid, start, word)| if sid == id { (sid, shifted(start as usize, edits, new_len) as u64, word) } else { (sid, start, word) }) + .collect(); + set_skipped(d, &skipped); +} + +/// Where byte `at` of a text ends up after `edits` ((start, end) bytes, none of them overlapping +/// `at`) are each replaced with `new_len` bytes. +fn shifted(at: usize, edits: &[(usize, usize)], new_len: usize) -> usize { + edits.iter().filter(|(_, end)| *end <= at).fold(at, |at, (start, end)| (at + new_len).saturating_sub(end - start)) +} + +/// Most unknown words one check lists when the dialog reads on through the scope (Ignore once +/// the queue is empty, a check started again, Change All): the check's own limit, or a smaller +/// one in tests. +#[cfg(not(test))] +fn page() -> usize { + vectorcraft_engine::cmd::spelling::MAX_WORDS +} + +#[cfg(test)] +fn page() -> usize { + tests::PAGE.with(std::cell::Cell::get) +} + /// Extracts the sentence containing `range` within `text`, returning (before, word, after). pub fn extract_sentence_context(text: &str, range: Range) -> (String, String, String) { let empty = (String::new(), String::new(), String::new()); @@ -210,105 +250,203 @@ fn set_done(d: &mut Dialog) { d.fields.insert("lang".into(), Value::Null); } -/// Advance to the next unrecognized word or complete the spell check. -pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - let mut remaining_ids: Vec = - d.fields.get("remaining_ids").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); +/// One unknown word: (id, start, end, word, lang). +type Word = (u64, usize, usize, String, String); - if remaining_ids.is_empty() && d.fields.get("ids").is_none_or(Value::is_null) { - let st = app.session.doc().map_err(|e| e.to_string())?; - st.doc.walk(|n| { - if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { - remaining_ids.push(n.id.0); - } - }); - d.fields.insert("remaining_ids".into(), json!(remaining_ids)); +/// One word of a `text.spelling.check` result. +fn word_at(w: &Value) -> Option { + let id = w.get("id")?.as_u64()?; + let start = usize::try_from(w.get("start")?.as_u64()?).ok()?; + let end = usize::try_from(w.get("end")?.as_u64()?).ok()?; + let word = w.get("word")?.as_str()?.to_string(); + let lang = w.get("lang").and_then(Value::as_str).unwrap_or("en").to_string(); + Some((id, start, end, word, lang)) +} + +/// One word of `queue`, kept as `[id, start, end, word, lang]`. +fn queued_word(w: &Value) -> Option { + match w.as_array().map(Vec::as_slice) { + Some([id, start, end, word, lang]) => Some(( + id.as_u64()?, + usize::try_from(start.as_u64()?).ok()?, + usize::try_from(end.as_u64()?).ok()?, + word.as_str()?.to_string(), + lang.as_str()?.to_string(), + )), + _ => None, } +} +/// The check's params for the dialog's scope, going on from `from` ((id, byte)) when given. +fn check_params(d: &Dialog, from: Option<(u64, usize)>, max: usize) -> Value { + let ids = d.fields.get("ids").cloned().unwrap_or(Value::Null); + match from { + Some((id, byte)) => json!({ "ids": ids, "from": { "id": id, "byte": byte }, "max": max }), + None => json!({ "ids": ids, "max": max }), + } +} + +/// Checks from `from` ((id, byte); the start of the scope when None), listing at most `max` +/// words, and shows the first one Ignore did not skip, keeping the rest in `queue`; completes the +/// spell check when there is none. Past a check whose words were all skipped it lists [`page`] +/// words at a time. +pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog, mut from: Option<(u64, usize)>, mut max: usize) -> Result<(), String> { let skipped = get_skipped(d); - loop { - if remaining_ids.is_empty() { - set_done(d); - return Ok(()); - } - - let check_res = app.run("text.spelling.check", json!({ "ids": remaining_ids })).map_err(|e| e.to_string())?; - let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); + let check_res = match app.run("text.spelling.check", check_params(d, from, max)) { + Ok(r) => r, + // The object `from` names left the scope (another command hid, locked or deleted + // it): start the scope again, where every word before is now right or skipped. + Err(_) if from.is_some() => { + from = None; + max = page(); + continue; + } + Err(e) => return Err(e.to_string()), + }; + let words: Vec = check_res.get("words").and_then(Value::as_array).map(|a| a.iter().filter_map(word_at).collect()).unwrap_or_default(); let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); - - let next_word = words - .iter() - .find(|w| { - let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); - let start = w.get("start").and_then(Value::as_u64).unwrap_or(0); - !skipped.contains(&(id, start)) - }) - .cloned(); - - if let Some(w) = next_word { - let id = w["id"].as_u64().unwrap_or(0); - let start = w["start"].as_u64().unwrap_or(0) as usize; - let end = w["end"].as_u64().unwrap_or(0) as usize; - let word = w["word"].as_str().unwrap_or("").to_string(); - let lang = w["lang"].as_str().unwrap_or("en").to_string(); - - let (before, target, after) = { - let st = app.session.doc().map_err(|e| e.to_string())?; - if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { - extract_sentence_context(&t.plain_text(), start..end) - } else { - (String::new(), word.clone(), String::new()) - } - }; - - let sugg_res = app.run("text.spelling.suggest", json!({ "word": word, "lang": lang, "max": 10 })).map_err(|e| e.to_string())?; - let suggestions: Vec = sugg_res - .get("suggestions") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) - .unwrap_or_default(); - - let change_to = suggestions.first().cloned().unwrap_or_else(|| word.clone()); - let full_context = format!("{before}{target}{after}"); - - d.fields.insert("not_in_dictionary".into(), json!(word)); - d.fields.insert("context".into(), json!(full_context)); - d.fields.insert("context_before".into(), json!(before)); - d.fields.insert("context_word".into(), json!(target)); - d.fields.insert("context_after".into(), json!(after)); - d.fields.insert("suggestions".into(), json!(suggestions)); - d.fields.insert("selected_suggestion".into(), json!(suggestions.first().cloned())); - d.fields.insert("change_to".into(), json!(change_to)); - d.fields.insert("node_id".into(), json!(id)); - d.fields.insert("start".into(), json!(start)); - d.fields.insert("end".into(), json!(end)); - d.fields.insert("lang".into(), json!(lang)); - d.fields.insert("done".into(), json!(false)); - return Ok(()); + let next_from = words.last().map(|w| (w.0, w.2)); + let mut rest = words.into_iter().filter(|w| !is_skipped(&skipped, w)); + if let Some(w) = rest.next() { + let mut queue: Vec = rest.map(|(id, start, end, word, lang)| json!([id, start, end, word, lang])).collect(); + queue.reverse(); + d.fields.insert("queue".into(), Value::Array(queue)); + d.fields.insert("queue_more".into(), json!(more)); + d.fields.insert("queue_from".into(), json!(next_from.map(|(id, byte)| [id, byte as u64]))); + return show(app, d, w); } - - if more && !words.is_empty() { - let last_id = words.last().and_then(|w| w.get("id")).and_then(Value::as_u64).unwrap_or(0); - if let Some(pos) = remaining_ids.iter().position(|&id| id == last_id) - && pos > 0 - { - remaining_ids.drain(0..pos); - d.fields.insert("remaining_ids".into(), json!(remaining_ids)); - continue; + match next_from { + Some(f) if more => { + from = Some(f); + max = page(); } - if remaining_ids.len() > 1 { - remaining_ids.remove(0); - d.fields.insert("remaining_ids".into(), json!(remaining_ids)); - continue; + _ => { + set_done(d); + return Ok(()); } } - - set_done(d); - return Ok(()); } } +/// Shows the next word of `queue` that Ignore did not skip and Ignore All did not add, or goes on +/// with a new check from `queue_from` when the queue runs out. The queue holds what a check listed +/// at the document revision of the word shown, so callers use it only while [`resume_at`] gives +/// Some. +fn step(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let skipped = get_skipped(d); + loop { + let next = d.fields.get_mut("queue").and_then(Value::as_array_mut).and_then(Vec::pop); + let Some(next) = next else { break }; + let Some(w) = queued_word(&next) else { continue }; + if is_skipped(&skipped, &w) || ignored_all(app, &w.3) { + continue; + } + return show(app, d, w); + } + let from = d.fields.get("queue_from").and_then(Value::as_array).and_then(|a| match a.as_slice() { + [id, byte] => Some((id.as_u64()?, usize::try_from(byte.as_u64()?).ok()?)), + _ => None, + }); + match from { + Some(from) if d.bool("queue_more") => advance(app, d, Some(from), page()), + _ => { + set_done(d); + Ok(()) + } + } +} + +/// Whether the active document's check skips `word` (Ignore All). +fn ignored_all(app: &VectorcraftApp, word: &str) -> bool { + let Some(w) = vectorcraft_engine::cmd::spelling::custom_word(word) else { return false }; + app.session.doc().is_ok_and(|st| st.spelling_ignored.contains(&w)) +} + +/// Shows `w` with its sentence and suggestions. +fn show(app: &mut VectorcraftApp, d: &mut Dialog, w: Word) -> Result<(), String> { + let (id, start, end, word, lang) = w; + let (before, target, after) = { + let st = app.session.doc().map_err(|e| e.to_string())?; + if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { + extract_sentence_context(&t.plain_text(), start..end) + } else { + (String::new(), word.clone(), String::new()) + } + }; + + let sugg_res = app.run("text.spelling.suggest", json!({ "word": word, "lang": lang, "max": 10 })).map_err(|e| e.to_string())?; + let suggestions: Vec = sugg_res + .get("suggestions") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) + .unwrap_or_default(); + + let change_to = suggestions.first().cloned().unwrap_or_else(|| word.clone()); + let full_context = format!("{before}{target}{after}"); + + d.fields.insert("not_in_dictionary".into(), json!(word)); + d.fields.insert("context".into(), json!(full_context)); + d.fields.insert("context_before".into(), json!(before)); + d.fields.insert("context_word".into(), json!(target)); + d.fields.insert("context_after".into(), json!(after)); + d.fields.insert("suggestions".into(), json!(suggestions)); + d.fields.insert("selected_suggestion".into(), json!(suggestions.first().cloned())); + d.fields.insert("change_to".into(), json!(change_to)); + d.fields.insert("node_id".into(), json!(id)); + d.fields.insert("start".into(), json!(start)); + d.fields.insert("end".into(), json!(end)); + d.fields.insert("lang".into(), json!(lang)); + d.fields.insert("done".into(), json!(false)); + remember_revision(app, d); + Ok(()) +} + +/// Notes the document's revision and the custom dictionary's generation as of the word shown, +/// which [`resume_at`] compares. +fn remember_revision(app: &VectorcraftApp, d: &mut Dialog) { + d.fields.insert("revision".into(), json!(revision(app))); +} + +/// The document's revision and the custom dictionary's generation: when either moves, the words +/// before the one shown may have changed. +fn revision(app: &VectorcraftApp) -> Option<[u64; 2]> { + let doc = app.session.doc().map(|st| st.revision).ok()?; + Some([doc, vectorcraft_engine::cmd::spelling::dictionary_generation()]) +} + +/// The word shown: (id, start, end). +fn current(d: &Dialog) -> Option<(u64, usize, usize)> { + let id = d.fields.get("node_id").and_then(Value::as_u64)?; + let start = usize::try_from(d.fields.get("start").and_then(Value::as_u64)?).ok()?; + let end = usize::try_from(d.fields.get("end").and_then(Value::as_u64)?).ok()?; + Some((id, start, end)) +} + +/// Where the next check goes on from: the start of the word shown. When another command changed +/// the document or the custom dictionary since the word was shown, the text before the word may +/// hold new unknown words, and `queue` may be out of date, so the check starts the scope again +/// (None); [`advance`] still skips the occurrences Ignore skipped. +fn resume_at(app: &VectorcraftApp, d: &Dialog) -> Option<(u64, usize)> { + let now = revision(app)?; + if d.fields.get("revision") != Some(&json!(now)) { + return None; + } + let (id, start, _, true) = shown_word(app, d)? else { return None }; + Some((id, start)) +} + +/// The word shown, (id, start, end), and whether its object still holds it at those bytes; None +/// when there is none or its object is no longer type. +fn shown_word(app: &VectorcraftApp, d: &Dialog) -> Option<(u64, usize, usize, bool)> { + let (id, start, end) = current(d)?; + let st = app.session.doc().ok()?; + let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) else { return None }; + let word = d.str("not_in_dictionary"); + let still_there = !word.is_empty() && t.plain_text().get(start..end).is_some_and(|w| w == word); + Some((id, start, end, still_there)) +} + fn check_doc_uid(app: &VectorcraftApp, d: &Dialog) -> Result<(), String> { let doc_uid = d.fields.get("doc_uid").and_then(Value::as_u64); let active_uid = app.session.active().map(|st| st.uid); @@ -323,12 +461,19 @@ fn ignore(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if d.bool("done") { return Ok(()); } - let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); - let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0); - let mut skipped = get_skipped(d); - skipped.push((id, start)); - set_skipped(d, &skipped); - advance(app, d) + let unchanged = resume_at(app, d).is_some(); + if let Some((id, start, _, true)) = shown_word(app, d) { + let mut skipped = get_skipped(d); + skipped.insert((id, start as u64, d.str("not_in_dictionary"))); + set_skipped(d, &skipped); + } + go_on(app, d, unchanged) +} + +/// On past the word shown: the next word of the queue while nothing changed since it was shown, +/// otherwise the scope checked again from its start. +fn go_on(app: &mut VectorcraftApp, d: &mut Dialog, unchanged: bool) -> Result<(), String> { + if unchanged { step(app, d) } else { advance(app, d, None, page()) } } fn ignore_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -336,11 +481,13 @@ fn ignore_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if d.bool("done") { return Ok(()); } + let unchanged = resume_at(app, d).is_some(); let word = d.str("not_in_dictionary"); if !word.is_empty() { app.run("text.spelling.ignoreAll", json!({ "word": word })).map_err(|e| e.to_string())?; } - advance(app, d) + // The queue's other occurrences of the word are passed over too. + go_on(app, d, unchanged) } fn change(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -348,29 +495,31 @@ fn change(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if d.bool("done") { return Ok(()); } - let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); - let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; - let end = d.fields.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; - let expected_word = d.str("not_in_dictionary"); + let from = resume_at(app, d); let change_to = d.str("change_to"); - if !change_to.trim().is_empty() && id > 0 { - let text_matches = { - let st = app.session.doc().map_err(|e| e.to_string())?; - if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { - let plain = t.plain_text(); - plain.get(start..end).map(|s| s == expected_word).unwrap_or(false) - } else { - false - } - }; + // Changed only while the word is still at the bytes shown. + let Some((id, start, end, true)) = shown_word(app, d) else { return advance(app, d, None, page()) }; + if change_to.trim().is_empty() { + return recheck(app, d, from); + } + if change_to == d.str("not_in_dictionary") { + // Nothing to change, so no undo step: on past the word. + return go_on(app, d, from.is_some()); + } + app.run("text.editRange", json!({ "id": id, "start": start, "end": end, "insert": change_to })).map_err(|e| e.to_string())?; + shift_skipped(d, id, &[(start, end)], change_to.len()); + // On from the replacement, which is shown when the dictionaries don't know it either (or + // from the start of the scope, when the document changed under the dialog). + recheck(app, d, from) +} - if text_matches { - app.run("text.editRange", json!({ "id": id, "start": start, "end": end, "insert": change_to })).map_err(|e| e.to_string())?; - } else { - return advance(app, d); - } +/// A new check after a change: on from `from` until the next unknown word, or the scope from its +/// start when `from` is None. +fn recheck(app: &mut VectorcraftApp, d: &mut Dialog, from: Option<(u64, usize)>) -> Result<(), String> { + match from { + Some(from) => advance(app, d, Some(from), 1), + None => advance(app, d, None, page()), } - advance(app, d) } fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -380,120 +529,47 @@ fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { } let word = d.str("not_in_dictionary"); let change_to = d.str("change_to"); + let here = resume_at(app, d); if word.is_empty() || change_to.trim().is_empty() { - return advance(app, d); + return recheck(app, d, here); } - let initial_ids = d.fields.get("ids").cloned().unwrap_or(Value::Null); let skipped = get_skipped(d); - let mut undo_group_started = false; - let mut execute_changes = || -> Result<(), String> { - let mut replaced_spans: Vec<(u64, usize, usize)> = Vec::new(); - let mut all_commands = Vec::new(); - loop { - let check_res = app.run("text.spelling.check", json!({ "ids": initial_ids })).map_err(|e| e.to_string())?; - let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); - let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); - - let mut by_node: BTreeMap> = BTreeMap::new(); - let mut new_edits = 0; - for w in &words { - let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); - let start = w.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; - let end = w.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; - let w_str = w.get("word").and_then(Value::as_str).unwrap_or(""); - if skipped.contains(&(id, start as u64)) { - continue; - } - if replaced_spans.iter().any(|&(r_id, r_start, r_end)| r_id == id && start >= r_start && start < r_end) { - continue; - } - if w_str.eq_ignore_ascii_case(&word) { - by_node.entry(id).or_default().push((start, end)); - new_edits += 1; - } - } - - if new_edits == 0 { - break; - } - - let new_len = change_to.len() as isize; - for (r_id, r_start, r_end) in &mut replaced_spans { - if let Some(ranges) = by_node.get(r_id) { - let delta: isize = ranges.iter().filter(|(_, end)| *end <= *r_start).map(|(start, end)| new_len - (*end - *start) as isize).sum(); - *r_start = (*r_start as isize + delta).max(0) as usize; - *r_end = (*r_end as isize + delta).max(0) as usize; - } - } - for (&id, ranges) in &by_node { - for &(start, _) in ranges { - let delta: isize = ranges - .iter() - .filter(|(_, other_end)| *other_end <= start) - .map(|(other_start, other_end)| new_len - (*other_end - *other_start) as isize) - .sum(); - let post_start = (start as isize + delta).max(0) as usize; - let post_end = post_start + change_to.len(); - replaced_spans.push((id, post_start, post_end)); - } - } - - let mut batch_commands = Vec::new(); - for (id, mut ranges) in by_node { - ranges.sort_by_key(|a| std::cmp::Reverse(a.0)); - for (start, end) in ranges { - batch_commands.push(json!({ - "command": "text.editRange", - "params": { - "id": id, - "start": start, - "end": end, - "insert": change_to, - } - })); - } - } - - if !batch_commands.is_empty() { - if batch_commands.len() == 1 && !more && all_commands.is_empty() && !undo_group_started { - let cmd = &batch_commands[0]; - app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; - break; - } else if more { - if !undo_group_started { - app.run("edit.undoGroup.begin", json!({ "label": "Change All" })).map_err(|e| e.to_string())?; - undo_group_started = true; - } - app.run("command.batch", json!({ "label": "Change All", "commands": batch_commands })).map_err(|e| e.to_string())?; - continue; - } else { - all_commands.extend(batch_commands); - break; - } - } - - break; - } - - if !all_commands.is_empty() { - if all_commands.len() == 1 && !undo_group_started { - let cmd = &all_commands[0]; - app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; - } else { - app.run("command.batch", json!({ "label": "Change All", "commands": all_commands })).map_err(|e| e.to_string())?; + // Every occurrence in the scope, found before anything changes, so the bytes each check gives + // stay true: one check after another, each going on from the end of the last word listed, + // until none says `more`. + let mut by_node: BTreeMap> = BTreeMap::new(); + let mut from = None; + loop { + let check_res = app.run("text.spelling.check", check_params(d, from, page())).map_err(|e| e.to_string())?; + let words: Vec = check_res.get("words").and_then(Value::as_array).map(|a| a.iter().filter_map(word_at).collect()).unwrap_or_default(); + let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); + for w in &words { + // An occurrence that already reads as the replacement is left alone: no edit, no undo step. + if w.3.eq_ignore_ascii_case(&word) && w.3 != change_to && !is_skipped(&skipped, w) { + by_node.entry(w.0).or_default().push((w.1, w.2)); } } - Ok(()) - }; - - let res = execute_changes(); - if undo_group_started { - let cancel = res.is_err(); - let _ = app.run("edit.undoGroup.end", json!({ "cancel": cancel })); + match words.last() { + Some((id, _, end, _, _)) if more => from = Some((*id, *end)), + _ => break, + } } - res?; - advance(app, d) + + if by_node.is_empty() { + // Nothing to change: on past the word shown, as Change does. + return go_on(app, d, here.is_some()); + } + // Every edit in one command: one undo step, each object laid out once. + let words: Vec = + by_node.iter().flat_map(|(&id, ranges)| ranges.iter().map(move |&(start, end)| json!({ "id": id, "start": start, "end": end }))).collect(); + app.run("text.spelling.change", json!({ "to": change_to, "words": words })).map_err(|e| e.to_string())?; + for (&id, ranges) in &by_node { + shift_skipped(d, id, ranges, change_to.len()); + } + // On from the shown word's replacement, where it moved to. + let from = here.map(|(id, start)| (id, by_node.get(&id).map_or(start, |ranges| shifted(start, ranges, change_to.len())))); + recheck(app, d, from) } fn add_to_dictionary(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -501,11 +577,13 @@ fn add_to_dictionary(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), Str if d.bool("done") { return Ok(()); } + // The check takes the word as right from now on, so it goes on from where the word starts. + let from = resume_at(app, d); let word = d.str("not_in_dictionary"); if !word.is_empty() { app.run("text.spelling.addWord", json!({ "word": word })).map_err(|e| e.to_string())?; } - advance(app, d) + recheck(app, d, from) } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { @@ -690,6 +768,360 @@ mod tests { const WORD_A: &str = "zqvspella"; const WORD_B: &str = "zqvspellb"; const WORD_C: &str = "zqvspellc"; + /// Never added to the custom dictionary, which the whole process shares (unlike WORD_C). + const WORD_D: &str = "zqvspelld"; + + thread_local! { + /// The most words one Change All check lists in this test thread ([`super::change_all_page`]). + pub(super) static PAGE: std::cell::Cell = const { std::cell::Cell::new(vectorcraft_engine::cmd::spelling::MAX_WORDS) }; + } + + fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + } + + /// The word the dialog shows: (id, start, word). + fn shown(app: &VectorcraftApp) -> (u64, u64, String) { + let d = app.ui.dialog.as_ref().unwrap(); + (d.fields["node_id"].as_u64().unwrap(), d.fields["start"].as_u64().unwrap(), d.str("not_in_dictionary")) + } + + fn act(app: &mut VectorcraftApp, f: fn(&mut VectorcraftApp, &mut crate::state::Dialog) -> Result<(), String>) { + let mut d = app.ui.dialog.take().unwrap(); + f(app, &mut d).unwrap(); + app.ui.dialog = Some(d); + } + + #[test] + fn ignore_goes_on_through_the_rest_of_the_same_type_object() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_B} one {WORD_B} two {WORD_B}")); + let other = text(&mut app, 100.0, &format!("then {WORD_A}")); + app.run("select.none", json!({})).unwrap(); + super::open(&mut app).unwrap(); + // Each step asks for one word on from the last, so every occurrence in the object is shown + // in turn before the next object's. + let mut seen = vec![shown(&app)]; + for _ in 0..4 { + act(&mut app, super::ignore); + if !app.ui.dialog.as_ref().unwrap().bool("done") { + seen.push(shown(&app)); + } + } + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + let b = WORD_B.len() as u64; + let want = + vec![(id, 0, WORD_B.to_string()), (id, b + 5, WORD_B.to_string()), (id, 2 * b + 10, WORD_B.to_string()), (other, 5, WORD_A.to_string())]; + assert_eq!(seen, want); + } + + #[test] + fn ignore_and_change_all_reach_every_word_of_a_selected_groups_type() { + let mut app = app(); + let a = text(&mut app, 50.0, &format!("{WORD_B} {WORD_D} {WORD_B}")); + let b = text(&mut app, 100.0, &format!("{WORD_D} {WORD_B}")); + let outside = text(&mut app, 150.0, &format!("{WORD_B} outside")); + app.run("select.set", json!({ "ids": [a, b] })).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [group] })).unwrap(); + PAGE.with(|p| p.set(1)); + + super::open(&mut app).unwrap(); + let mut seen = vec![shown(&app)]; + for _ in 0..5 { + act(&mut app, super::ignore); + if !app.ui.dialog.as_ref().unwrap().bool("done") { + seen.push(shown(&app)); + } + } + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + let ids: Vec<(u64, String)> = seen.into_iter().map(|(id, _, w)| (id, w)).collect(); + let want = [(a, WORD_B), (a, WORD_D), (a, WORD_B), (b, WORD_D), (b, WORD_B)].map(|(id, w)| (id, w.to_string())); + assert_eq!(ids, want, "the group's descendants, one word at a time; not the object outside it"); + + // Change All goes through the group one listed word at a time too. + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert_eq!(plain(&app, a), format!("fixed {WORD_D} fixed")); + assert_eq!(plain(&app, b), format!("{WORD_D} fixed")); + assert_eq!(plain(&app, outside), format!("{WORD_B} outside"), "outside the selection"); + } + + #[test] + fn change_all_reaches_a_target_past_a_full_check_of_other_words() { + let mut app = app(); + // The second WORD_A comes after a whole check's worth of other unknown words. + PAGE.with(|p| p.set(2)); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_D} {WORD_A} {WORD_B} {WORD_A}")); + super::open(&mut app).unwrap(); + // Ignore the first WORD_A, then change all from the second. + act(&mut app, super::ignore); + act(&mut app, super::ignore); + act(&mut app, super::ignore); + assert_eq!(shown(&app).2, WORD_A); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert_eq!(plain(&app, id), format!("{WORD_A} {WORD_B} {WORD_D} fixed {WORD_B} fixed"), "the ignored one stays"); + // On from the replacement: the WORD_B after it. + assert_eq!(shown(&app).2, WORD_B); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(plain(&app, id), format!("{WORD_A} {WORD_B} {WORD_D} {WORD_A} {WORD_B} {WORD_A}"), "one undo step"); + } + + #[test] + fn change_all_reaches_a_target_past_the_checks_limit_in_one_object() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + // A target, then the most other words one check lists, then a second target, all in one + // type object. + let others = vec![WORD_B; MAX_WORDS].join(" "); + let id = text(&mut app, 50.0, &format!("{WORD_A} {others} {WORD_A}")); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (id, 0, WORD_A.to_string())); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert_eq!(plain(&app, id), format!("fixed {others} fixed")); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(plain(&app, id), format!("{WORD_A} {others} {WORD_A}"), "one undo step"); + } + + #[test] + fn text_changed_under_the_dialog_is_checked_again_from_its_start() { + // A word of its own: Add to Dictionary puts it in the custom dictionary the process shares. + const STALE: &str = "zqvstaleword"; + for f in [super::ignore, super::ignore_all, super::change, super::change_all, super::add_to_dictionary] { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("hello {STALE}")); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (id, 6, STALE.to_string())); + // Another command replaces the text with a shorter one: the shown bytes are gone. + app.run("text.editRange", json!({ "id": id, "start": 0, "end": 6 + STALE.len(), "insert": WORD_D })).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, f); + forget(&mut app, &[STALE]); + assert_eq!(plain(&app, id), WORD_D, "nothing is changed at stale bytes"); + assert_eq!(shown(&app), (id, 0, WORD_D.to_string()), "the object is checked again from its start"); + } + } + + #[test] + fn a_restarted_check_still_skips_the_ignored_occurrences() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_A}")); + super::open(&mut app).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 10, WORD_B.to_string())); + // Another command changes the word shown, so the next step checks the object from its start. + app.run("text.editRange", json!({ "id": id, "start": 10, "end": 10 + WORD_B.len(), "insert": WORD_D })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 10, WORD_D.to_string()), "the ignored first word is not shown again"); + } + + #[test] + fn an_unknown_word_brought_back_before_the_shown_one_is_shown_again() { + // Words of their own: Add to Dictionary puts one in the custom dictionary the process shares. + // FIRST has as many bytes as "different", so the second word stays at the bytes shown. + const FIRST: &str = "zqvbckone"; + const SECOND: &str = "zqvbacktwo"; + for f in [super::ignore, super::ignore_all, super::change, super::change_all, super::add_to_dictionary] { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{FIRST} {SECOND}")); + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("different")); + act(&mut app, super::change); + // Drawing the dialog leaves the document's revision alone, so the next step goes on + // from the word shown rather than starting again. + let ctx = context(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["revision"][0], json!(app.session.doc().unwrap().revision)); + assert_eq!(shown(&app), (id, 10, SECOND.to_string())); + // Another command (Undo) brings the first word back before the one shown. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(plain(&app, id), format!("{FIRST} {SECOND}")); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, f); + forget(&mut app, &[SECOND]); + assert_eq!(shown(&app), (id, 0, FIRST.to_string()), "the check starts again and finds it"); + } + } + + #[test] + fn a_word_taken_out_of_the_custom_dictionary_is_shown_again() { + // Words of their own: the custom dictionary is shared by the whole process. + const FIRST: &str = "zqvdictone"; + const SECOND: &str = "zqvdicttwo"; + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{FIRST} {SECOND}")); + super::open(&mut app).unwrap(); + act(&mut app, super::add_to_dictionary); + assert_eq!(shown(&app), (id, 11, SECOND.to_string())); + // Another command takes the first word out of the dictionary again. + app.run("text.spelling.removeWord", json!({ "word": FIRST })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 0, FIRST.to_string()), "the check starts again and finds it"); + } + + #[test] + fn a_shown_object_that_leaves_the_scope_starts_the_scope_again() { + let mut app = app(); + let first = text(&mut app, 50.0, &format!("{WORD_A} here")); + let second = text(&mut app, 100.0, &format!("{WORD_B} there")); + app.run("select.none", json!({})).unwrap(); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app).0, first); + app.run("object.lock", json!({ "ids": [first] })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (second, 0, WORD_B.to_string()), "on to the type still in the scope"); + } + + /// Marks the first `n` occurrences of WORD_B in `id` (each WORD_B and a space) as skipped by + /// Ignore, with the last of them shown. + fn ignored_b_words(app: &mut VectorcraftApp, id: u64, n: usize) { + let step = WORD_B.len() + 1; + let d = app.ui.dialog.as_mut().unwrap(); + let skipped: Vec<_> = (0..n).map(|i| json!([id, i * step, WORD_B])).collect(); + d.fields.insert("skipped".into(), json!(skipped)); + let last = (n - 1) * step; + for (k, v) in [("node_id", json!(id)), ("start", json!(last)), ("end", json!(last + WORD_B.len())), ("not_in_dictionary", json!(WORD_B))] { + d.fields.insert(k.into(), v); + } + } + + #[test] + fn ignore_reaches_the_last_of_more_unknown_words_than_one_check_lists() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + let id = text(&mut app, 50.0, &vec![WORD_B; MAX_WORDS + 1].join(" ")); + super::open(&mut app).unwrap(); + ignored_b_words(&mut app, id, MAX_WORDS); + // Another command changes the document, so the next step checks the scope from its start, + // where every word one check lists was skipped. + text(&mut app, 100.0, "hello"); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, (MAX_WORDS * (WORD_B.len() + 1)) as u64, WORD_B.to_string()), "the last occurrence"); + act(&mut app, super::ignore); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + } + + #[test] + fn ignore_and_change_all_reach_a_selected_groups_type_past_the_checks_limit() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + let a = text(&mut app, 50.0, &vec![WORD_B; MAX_WORDS].join(" ")); + let b = text(&mut app, 100.0, &format!("{WORD_A} end")); + let outside = text(&mut app, 150.0, &format!("{WORD_D} outside")); + app.run("select.set", json!({ "ids": [a, b] })).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [group] })).unwrap(); + super::open(&mut app).unwrap(); + ignored_b_words(&mut app, a, MAX_WORDS); + // An edit outside the group moves the document's revision: the group is checked again. + app.run("text.editRange", json!({ "id": outside, "start": 0, "end": 0, "insert": "the " })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (b, 0, WORD_A.to_string()), "the next object in the group"); + act(&mut app, super::ignore); + assert!(app.ui.dialog.as_ref().unwrap().bool("done"), "not the object outside the group"); + + // Change All: a target, then the most words one check lists, then a target in the next object. + app.run("text.editRange", json!({ "id": a, "start": 0, "end": 0, "insert": format!("{WORD_A} ") })).unwrap(); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (a, 0, WORD_A.to_string())); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert!(plain(&app, a).starts_with(&format!("fixed {WORD_B} "))); + assert_eq!(plain(&app, b), "fixed end"); + } + + #[test] + fn ignore_all_and_add_to_dictionary_go_on_past_each_check() { + PAGE.with(|p| p.set(2)); + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_A} {WORD_D} {WORD_A}")); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (id, 0, WORD_A.to_string())); + act(&mut app, super::ignore_all); + let mut seen = vec![shown(&app)]; + act(&mut app, super::ignore); + seen.push(shown(&app)); + act(&mut app, super::ignore); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + assert_eq!(seen, vec![(id, 10, WORD_B.to_string()), (id, 30, WORD_D.to_string())], "no WORD_A after Ignore All"); + + // Words of their own: the custom dictionary is shared by the whole process. + const ADDED: &str = "zqvaddone"; + const OTHER: &str = "zqvaddtwo"; + PAGE.with(|p| p.set(1)); + let mut app = super::tests::app(); + let id = text(&mut app, 50.0, &format!("{ADDED} {OTHER} {ADDED} {OTHER}")); + super::open(&mut app).unwrap(); + act(&mut app, super::add_to_dictionary); + let mut seen = vec![shown(&app)]; + act(&mut app, super::ignore); + seen.push(shown(&app)); + act(&mut app, super::ignore); + let done = app.ui.dialog.as_ref().unwrap().bool("done"); + forget(&mut app, &[ADDED]); + assert!(done); + assert_eq!(seen, vec![(id, 10, OTHER.to_string()), (id, 30, OTHER.to_string())]); + } + + #[test] + fn change_to_the_same_word_changes_nothing_and_goes_on() { + for f in [super::change, super::change_all] { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_D} and {WORD_D} {WORD_A}")); + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!(WORD_D)); + let depth = app.session.doc().unwrap().history.undo.len(); + act(&mut app, f); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth, "no undo step"); + assert_eq!(plain(&app, id), format!("{WORD_D} and {WORD_D} {WORD_A}")); + let d = WORD_D.len() as u64; + assert_eq!(shown(&app), (id, d + 5, WORD_D.to_string()), "on past the word shown"); + } + } + + #[test] + fn a_word_moved_by_another_command_is_not_taken_for_an_ignored_one() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_A}")); + super::open(&mut app).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 10, WORD_B.to_string())); + // Another command puts a different unknown word where the ignored one was. + let len = plain(&app, id).len(); + app.run("text.editRange", json!({ "id": id, "start": 0, "end": len, "insert": format!("{WORD_D} {WORD_A} {WORD_B}") })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 0, WORD_D.to_string()), "the word now at the ignored bytes is shown"); + } + + #[test] + fn change_all_changes_a_whole_checks_worth_of_occurrences_in_one_edit() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + let id = text(&mut app, 50.0, &vec![WORD_A; MAX_WORDS + 1].join(" ")); + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + let depth = app.session.doc().unwrap().history.undo.len(); + act(&mut app, super::change_all); + assert_eq!(plain(&app, id), vec!["fixed"; MAX_WORDS + 1].join(" ")); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + } + + #[test] + fn ignore_positions_move_with_the_edits_before_them() { + // "ab cd ef": cd (3..5) replaced with "wxyz" moves byte 6 to 8; byte 0 stays. + assert_eq!(super::shifted(6, &[(3, 5)], 4), 8); + assert_eq!(super::shifted(0, &[(3, 5)], 4), 0); + assert_eq!(super::shifted(9, &[(0, 2), (3, 5)], 1), 7); + } fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); @@ -1066,12 +1498,13 @@ mod tests { app.run("select.set", json!({ "ids": [] })).unwrap(); super::open(&mut app).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("not_in_dictionary"), WORD_A); + let ctx = context(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_A); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["node_id"], json!(editable_id)); - let rem = d.fields.get("remaining_ids").and_then(serde_json::Value::as_array).unwrap(); - assert!(rem.iter().any(|v| v.as_u64() == Some(editable_id))); - assert!(!rem.iter().any(|v| v.as_u64() == Some(locked_id))); + // The locked object's word is never shown. + click(&mut app, &ctx, "Ignore"); + assert!(app.ui.dialog.as_ref().unwrap().bool("done"), "locked type {locked_id} is left out"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..252e90fbfd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9302,13 +9302,22 @@ a spelling dictionary marks nothing. English words come from the first dictionar dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof. Words in capitals, words with digits and web addresses are taken as correct. The result is `{words: [{id, start, end, word, lang}], more}`: `start` and `end` are byte offsets in the type object's text, the -ones `text.editRange` takes, so `text.editRange {id, start, end, insert}` changes a word as one undo step. At most -10,000 words are listed; `more` is `true` when there were more. `text.spelling.suggest {word, max?, lang?}` gives -the words the dictionary of `lang` (default English) suggests instead of `word`, best first, at most `max` (1 to 20, -default 5). Both only read the document. +ones `text.editRange` takes, so `text.editRange {id, start, end, insert}` changes a word as one undo step, and +`text.spelling.change {to, words: [{id, start, end}…]}` changes every listed word to `to` as one undo step (Check +Spelling's Change All; an error, with nothing changed, when a word's bytes are not in its object's text or two words +overlap). At most +`max` words are listed (1 to 10,000, default 10,000); `more` is `true` when there were more. To get the rest, check +again with `from: {id, byte}` set to the last word's `id` and `end`: that check lists the words of that type object +that start at `byte` or later, then those of the objects after it, so a type object with more unknown words than one +check lists is read to its end. `from.id` must be one of the objects checked. The paragraphs before the one that +holds `from.byte` are not checked again; that paragraph is checked whole. `text.spelling.suggest {word, max?, lang?}` +gives the words the dictionary of `lang` (default English) suggests instead of `word`, best first, at most `max` (1 to +20, default 5). `text.spelling.check` and `text.spelling.suggest` only read the document. ```json {"name":"run_command","arguments":{"command":"text.spelling.check","params":{}}} +{"name":"run_command","arguments":{"command":"text.spelling.check","params":{"from":{"id":12,"byte":340},"max":100}}} +{"name":"run_command","arguments":{"command":"text.spelling.change","params":{"to":"drawing","words":[{"id":12,"start":4,"end":10}]}}} {"name":"run_command","arguments":{"command":"text.spelling.suggest","params":{"word":"drawng","lang":"en"}}} ``` From 669d98fab14b86fe4484c23cfb04da147757c89c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:36:58 -0800 Subject: [PATCH 33/50] Tests: Show Similar Fonts' limit check tolerates fonts that other tests add Other tests add and remove composite fonts in the shared font database, which can change the list between the two text.similarFonts calls. The limited answer is compared whole with the first families of the full one when FontDb::generation is the same before and after both calls, and by the installed families when the fonts changed during each of 20 tries. --- crates/engine/src/tests/fontlist.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 4a17bf734a..f7bf95b514 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -51,8 +51,28 @@ fn similar_fonts_lists_every_family_by_likeness() { // Other tests running at the same time add and remove composite fonts; the installed families are compared. let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); - let two = s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap(); - assert_eq!(names(&two["families"]), order[..2]); + // The two answers are compared whole when the available fonts did not change while both were + // made (the same `FontDb::generation`), and by their installed families when they changed + // during every try. + let mut answers = (vec![], vec![], false); + for _ in 0..20 { + let generation = db.generation(); + let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); + let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); + let unchanged = db.generation() == generation; + answers = (all, two, unchanged); + if unchanged { + break; + } + } + let (all, two, unchanged) = answers; + assert_eq!(two.len(), 2); + if unchanged { + assert_eq!(two, all[..2], "the first families, in order"); + } else { + let (two, all) = (installed_only(&two), installed_only(&all)); + assert_eq!(two[..], all[..two.len()], "the first installed families, in order"); + } for (params, error) in [ (json!({}), "`family` is required"), (json!({"family": " "}), "`family` is required"), From 578b26cc7c6dd7ad55659f834f67be7a09d6284c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:50:35 -0800 Subject: [PATCH 34/50] Tool overlays: draw every dash of a dashed piece as line segments dashes_from drew the cut first dash and a line shorter than the rest of a dash as one path. The tessellator snaps horizontal and vertical line segments to pixels but not paths, so those dashes could look softer than the rest. Each line of them is now its own line segment, as Shape::dashed_line draws a dash, and a line of no length is skipped. --- crates/ui-egui/src/canvas/overlays.rs | 10 ++++++++-- crates/ui-egui/src/canvas/tests.rs | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index e3612bc880..613b0fae9c 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -428,7 +428,7 @@ pub(super) fn dashes_from(line: &[Pos2], s: Stroke, from: f64, out: &mut Vec) { + out.extend(line.windows(2).filter(|w| w[0] != w[1]).map(|w| Shape::line_segment([w[0], w[1]], s))); } impl SharedPaths { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8830edf1c7..5d5a5aa3d8 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -201,6 +201,14 @@ fn a_line_dashed_in_pieces_dashes_as_the_whole_line_does() { let (want, got) = (covered(&one_go), covered(&pieces)); assert_eq!(want.len(), got.len(), "{want:?} {got:?}"); assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-3 && (w.1 - g.1).abs() < 1e-3), "{want:?} {got:?}"); + // Every dash is drawn as line segments with a length, as `Shape::dashed_line` draws them: the + // cut first dash, a dash cut on a vertex (at 4) and a line shorter than the rest of a dash too. + let mut ends = vec![]; + overlays::dashes_from(&along(&[0.0, 4.0, 10.0]), s, 0.0, &mut ends); + overlays::dashes_from(&along(&[0.0, 1.0, 2.0]), s, 1.0, &mut ends); + for shape in one_go.iter().chain(&pieces).chain(&ends) { + assert!(matches!(shape, Shape::LineSegment { points: [a, b], .. } if a != b), "{shape:?}"); + } } #[test] From 41651e1f72505ad4649c4e6ed3320b31bf1d5b26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:57:10 -0800 Subject: [PATCH 35/50] Crop Image: refuse a resample too large for the raster allowance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit object.cropImage with ppi now checks that the source, its 16-bit weighted copy, the resampler's intermediate rows and the results fit in the raster allowance (2 GB, 512 MB in the web app) before it resamples, and refuses with "an image of {w} × {h} pixels is too large to resample" otherwise. A crop that is drawn first frees the drawing's PNG before its pixels are resampled. --- crates/engine/src/cmd/menucmds.rs | 28 ++++++++++++++++++++++------ crates/engine/src/tests/menucmds.rs | 16 ++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 7930c3bc90..c3a4f02ba7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1031,8 +1031,10 @@ fn check_crop_size(w: f64, h: f64) -> Result<()> { /// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully /// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in -/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. -fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> image::RgbaImage { +/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when +/// the working copies would not fit ([`check_resample_size`]). +fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result { + check_resample_size(img.width(), img.height(), w, h)?; let mut pre = image::ImageBuffer::, Vec>::new(img.width(), img.height()); for (d, s) in pre.pixels_mut().zip(img.pixels()) { let a = u32::from(s[3]); @@ -1052,7 +1054,19 @@ fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> image::RgbaIm } d.0[3] = ((a + 128) / 257).min(255) as u8; } - res + Ok(res) +} + +/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and +/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes +/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`). +pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> { + let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h)); + let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12)); + if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC { + return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample"))); + } + Ok(()) } /// `img` as PNG bytes. @@ -1118,7 +1132,7 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { Some(t) => { let (cw, ch) = cut.dimensions(); let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); - let resized = resize_premultiplied(&cut, w, h); + let resized = resize_premultiplied(&cut, w, h)?; (resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h))) } None => (cut, xf), @@ -1167,9 +1181,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { // fitted to the box, so the image keeps its size. let (png, w, h, xf) = match target { Some(t) => { - let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.to_rgba8(); + let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8(); + // Only the decoded pixels are held while they are resampled. + drop(png); let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); - let resized = resize_premultiplied(&drawn, tw, th); + let resized = resize_premultiplied(&drawn, tw, th)?; let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th)); (encode_png(&resized)?, tw, th, xf) } diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ec35fd36bc..688e1f7804 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -5541,6 +5541,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() { assert!(within.contains("the image's pixels can't be read"), "{within}"); } +#[test] +fn crop_image_resampling_is_held_to_the_raster_allowance() { + use crate::cmd::menucmds::check_resample_size; + let max = crate::cmd::fileio::MAX_RASTER_ALLOC; + // 40 bytes a pixel resampled to the same size (12 + 16 + 12). + let side = ((max / 40) as f64).sqrt() as u32; + assert!(check_resample_size(side, side, side, side).is_ok()); + let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string(); + assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}"); + // A large source counts even when the result is small. + let wide = ((max / 12) as f64).sqrt() as u32 + 1; + assert!(check_resample_size(wide, wide, 1, 1).is_err()); + assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err()); + assert!(check_resample_size(100, 100, 50, 50).is_ok()); +} + #[test] fn crop_image_trim_leaves_a_cmyk_image_alone() { // CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error. diff --git a/docs/mcp.md b/docs/mcp.md index 95349d08ec..d691dc7948 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1925,7 +1925,9 @@ An image scaled differently across and down is resampled on both sides, so its p The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or 300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with -`ppi must be a positive number, not {ppi}`. A null `ppi` keeps the image's own, as a missing one does, and `ppi` with +`ppi must be a positive number, not {ppi}`. A resample whose working copies would pass the raster allowance (2 GB, +512 MB in the web app) is refused with `an image of {w} × {h} pixels is too large to resample`, naming the size +of the pixels being resampled. A null `ppi` keeps the image's own, as a missing one does, and `ppi` with `trim` is refused. While the Crop Image tool is chosen, `tool.setOption` sets `ppi` (the resolution Apply sends), `reference` (0 to 8, left to right and top to bottom: the point of the box that the Control bar's X and Y name and that its W and H resize about; 4, the center, by default) and `linked` (W and H keep the box's proportions; false by From 65feca6ba8bf49bf4b687ac0777708c47ef5e7c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:07:34 -0800 Subject: [PATCH 36/50] Plug-ins: text.similarFonts is not callable from a plug-in text.similarFonts lists every family text.fontList lists, the fonts installed on the system included, so it joins the commands a plug-in may not call, as text.fontList is. every_command_is_reviewed failed because the command was in neither reviewed list. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6c7be12540..4582f0dcc3 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -703,8 +703,9 @@ pub(super) const ALLOWED: &[&str] = &[ ]; /// Commands a plug-in may not call although no rule refuses them, in order: they change the -/// preferences, a tool's options, a drag's state or the font names the whole app knows, run -/// plug-ins again, or read a file and report where it is on disk. +/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the +/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and +/// report where it is on disk. pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", @@ -717,5 +718,6 @@ pub(super) const DENIED: &[&str] = &[ "object.pathfinder.options", "stroke.arrowheads.edit", "stroke.arrowheads.list", + "text.similarFonts", "type.compositeFonts.set", ]; From 56d0feddf9d630a813e4dfb05c90092bb5d13fb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:10:18 -0800 Subject: [PATCH 37/50] Tool overlays: pieces of a long drag's line meet halfway along a segment Each piece of a long drag's line also held the first segment of the next piece, so that segment was drawn twice, once by each piece. Where the line is thin or partly covered at its edges, the doubled coverage drew a darker stretch every 64 segments. A piece now ends halfway along the segment after its last point, and the next piece starts there, so a wide line still turns at the piece's last point as one line does. --- crates/tools/src/draw2/gesture/line.rs | 75 +++++++++++++++---------- crates/tools/src/draw2/gesture/tests.rs | 25 +++++++-- 2 files changed, 64 insertions(+), 36 deletions(-) diff --git a/crates/tools/src/draw2/gesture/line.rs b/crates/tools/src/draw2/gesture/line.rs index 60c10d538f..a2ed4beb4b 100644 --- a/crates/tools/src/draw2/gesture/line.rs +++ b/crates/tools/src/draw2/gesture/line.rs @@ -2,9 +2,10 @@ //! round Eraser tip, the Knife, the Pencil with Live preview off, a smoothing drag), kept in //! pieces that later calls return again unchanged. //! -//! A drag of more than [`PIECE_SEGMENTS`] segments is cut into pieces of that many segments, each -//! also holding the first segment of the next piece, so that a wide line turns at a piece's last -//! point as one line does. A piece the drag has gone past is built once and returned again as the +//! A drag of more than [`PIECE_SEGMENTS`] segments is cut into pieces of that many segments. A +//! piece ends halfway along the segment after its last point, where the next piece starts, so that +//! a wide line turns at a piece's last point as one line does and no part of the line is drawn +//! twice. A piece the drag has gone past is built once and returned again as the //! same shared path; only the last piece is built again, and only when the drag changed it. With //! Size on a mode that follows the pen each segment shows at its own width, so each segment is //! kept as its own path, and only a segment whose ends moved is built again. @@ -15,19 +16,23 @@ use vectorcraft_geom::{BezPath, Point}; use super::super::polyline; -/// The most segments of a drag that one piece of its line holds besides the first segment of the -/// next piece. +/// The segments of a drag from the first point of one piece of its line to the first point of the +/// next. pub(super) const PIECE_SEGMENTS: usize = 64; -/// A piece of the line: the drag's points `from` to `to`. +/// A piece of the line along the drag's points `from` to `to`: from point `from`, or halfway to the +/// point after it in a piece other than the first, and up to point `to`, or halfway to it in a +/// piece the drag has gone past. struct Piece { path: Arc, from: usize, to: usize, /// The drag's point `to` when the piece was built. end: Point, - /// The length of the line before `from`. + /// The length of the line before the piece's first point. along: f64, + /// The length of the piece. + length: f64, } /// A piece of the line to show ([`LinePreview::pieces`]). @@ -64,36 +69,34 @@ impl LinePreview { self.built = 0; // The drag no longer runs through the points of a kept piece (another drag, or a drag // made again from its press). - let runs_through = - |p: &Piece| pts.get(p.to) == Some(&p.end) && p.path.elements().first().and_then(|e| e.end_point()) == pts.get(p.from).copied(); + let runs_through = |p: &Piece| pts.get(p.to) == Some(&p.end) && p.path.elements().first().and_then(|e| e.end_point()) == start(pts, p.from); if let Some(k) = self.settled.iter().position(|p| !runs_through(p)) { self.settled.truncate(k); self.last = None; } - // A piece settles once the drag has gone past its last point, which can still move. + // A piece settles once the drag has gone past its last point, which can still move. It + // then ends halfway along the segment after that point, so it is built again. loop { let from = self.settled.len() * PIECE_SEGMENTS; let to = from + PIECE_SEGMENTS + 1; if to + 1 >= pts.len() { break; } - let along = self.along_next(pts); - let piece = match self.last.take().filter(|p| p.from == from && p.to == to && runs_through(p)) { - Some(p) => p, - None => self.build(pts, from, to, along), - }; + let along = self.along_next(); + let piece = self.build(pts, from, to, true, along); self.settled.push(piece); } let from = self.settled.len() * PIECE_SEGMENTS; let to = pts.len().saturating_sub(1); if to > from { - let along = self.along_next(pts); + let along = self.along_next(); // The last piece's points other than its last can change only with its last one, or // with the drag's length. - let kept = self.last.take().filter(|p| p.from == from && p.to == to && pts.get(from..=to).is_some_and(|run| same_points(&p.path, run))); + let kept = + self.last.take().filter(|p| p.from == from && p.to == to && run(pts, from, to, false).is_some_and(|run| same_points(&p.path, run))); self.last = Some(match kept { Some(p) => p, - None => self.build(pts, from, to, along), + None => self.build(pts, from, to, false, along), }); } else { self.last = None; @@ -126,24 +129,36 @@ impl LinePreview { } /// The length of the line before the piece after the settled ones. - fn along_next(&self, pts: &[Point]) -> f64 { - self.settled.last().map_or(0.0, |p| p.along + pts.get(p.from..=p.from + PIECE_SEGMENTS).map_or(0.0, length)) + fn along_next(&self) -> f64 { + self.settled.last().map_or(0.0, |p| p.along + p.length) } - /// The piece through the points `from` to `to` of `pts`, `along` the line. - fn build(&mut self, pts: &[Point], from: usize, to: usize, along: f64) -> Piece { - let run = pts.get(from..=to).unwrap_or_default(); - self.built += run.len(); - Piece { path: Arc::new(polyline(run)), from, to, end: run.last().copied().unwrap_or_default(), along } + /// The piece along the points `from` to `to` of `pts` ([`run`]), `along` the line. + fn build(&mut self, pts: &[Point], from: usize, to: usize, settled: bool, along: f64) -> Piece { + let points: Vec = run(pts, from, to, settled).map(Iterator::collect).unwrap_or_default(); + self.built += points.len(); + let length = points.windows(2).map(|w| w[0].distance(w[1])).sum(); + Piece { path: Arc::new(polyline(&points)), from, to, end: pts.get(to).copied().unwrap_or_default(), along, length } } } -/// The length of the line through `pts`. -fn length(pts: &[Point]) -> f64 { - pts.windows(2).map(|w| w[0].distance(w[1])).sum() +/// Where a piece from the point `from` of `pts` starts: at the point in the first piece, else +/// halfway to the point after it, where the piece before ends. +fn start(pts: &[Point], from: usize) -> Option { + if from == 0 { pts.first().copied() } else { Some(pts.get(from)?.midpoint(*pts.get(from + 1)?)) } +} + +/// The points of the piece along the points `from` to `to` of `pts`: from its [`start`], through +/// the points after `from`, to point `to`, or, in a piece the drag has gone past (`settled`), to +/// halfway between the point before `to` and point `to`. +fn run(pts: &[Point], from: usize, to: usize, settled: bool) -> Option + '_> { + let first = start(pts, from)?; + let inner = pts.get(from + 1..if settled { to } else { to + 1 })?; + let last = if settled { Some(pts.get(to.checked_sub(1)?)?.midpoint(*pts.get(to)?)) } else { None }; + Some(std::iter::once(first).chain(inner.iter().copied()).chain(last)) } /// Does `path` run through exactly the points `pts`? -fn same_points(path: &BezPath, pts: &[Point]) -> bool { - path.elements().len() == pts.len() && path.elements().iter().zip(pts).all(|(e, p)| e.end_point() == Some(*p)) +fn same_points(path: &BezPath, mut pts: impl Iterator) -> bool { + path.elements().iter().all(|e| e.end_point().is_some() && e.end_point() == pts.next()) && pts.next().is_none() } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 97296c7254..e1318f2958 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2535,13 +2535,27 @@ fn line_built(t: &GestureTool) -> usize { built } +/// The points of piece `k` of the line of a drag through `pts`. A piece other than the first starts +/// halfway along the segment after its first point, and a piece other than the last (`settled`) +/// ends halfway along the segment after its last point, where the next piece starts. +fn piece_points(pts: &[Point], k: usize, settled: bool) -> Vec { + let from = k * line::PIECE_SEGMENTS; + let to = if settled { from + line::PIECE_SEGMENTS } else { pts.len() - 1 }; + let mut want = vec![if k == 0 { pts[0] } else { pts[from].midpoint(pts[from + 1]) }]; + want.extend_from_slice(&pts[from + 1..=to]); + if settled { + want.push(pts[to].midpoint(pts[to + 1])); + } + want +} + /// The line of a long round Eraser, Knife, Path Eraser or Pencil (Live preview off) drag shows in /// pieces, and the steps of a round Eraser drag whose Size follows the pen each as its own path. /// They come back from one call to the next, at any zoom, as the same shared paths, which the host /// draws again without building them again; the call copies no point into a new path. A step of /// the drag builds again only the last piece, or adds one step. The pieces run through every point -/// of the drag, each from where the one before ends and on over the next segment, and the -/// Knife's dashes go on from one piece to the next. +/// of the drag, each from where the one before ends, halfway along a segment, so no part of the +/// line is drawn twice, and the Knife's dashes go on from one piece to the next. #[test] fn the_line_of_a_long_drag_is_the_same_shared_pieces_each_frame() { let (d, id) = doc_with_rect(); @@ -2579,15 +2593,14 @@ fn the_line_of_a_long_drag_is_the_same_shared_pieces_each_frame() { assert!(first.len() > 1, "{id}: {} pieces", first.len()); let mut along = 0.0; for (k, (path, width, dash)) in first.iter().enumerate() { - let from = k * line::PIECE_SEGMENTS; - let to = (from + line::PIECE_SEGMENTS + 1).min(n - 1); - assert_eq!(points_of(path), t.points[from..=to], "{id}: piece {k}"); + let got = points_of(path); + assert_eq!(got, piece_points(&t.points, k, k + 1 < first.len()), "{id}: piece {k}"); assert_eq!(*width, if id == "eraser" { 10.0 } else { 1.0 }, "{id}"); match dash { Some(at) => assert!(id == "knife" && (at - along).abs() < 1e-6, "{id}: piece {k} dashes from {at}, not {along}"), None => assert_ne!(id, "knife"), } - along += t.points[from..=(from + line::PIECE_SEGMENTS).min(n - 1)].windows(2).map(|w| w[0].distance(w[1])).sum::(); + along += got.windows(2).map(|w| w[0].distance(w[1])).sum::(); } assert_eq!(first.len() - 1, (n - 3) / line::PIECE_SEGMENTS, "{id}: the last piece holds the points no settled piece holds"); } From a5a282792405f43b0fa7ae876e9f5bc62636777e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:08:24 -0800 Subject: [PATCH 38/50] i18n: translate the reworded symbol.options error in every catalog The error that asks for at least one Symbol Options field now also names alignToPixelGrid. Each catalog's row for the old wording is replaced with a row for the new one, so the message is translated again. --- 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/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 +- 27 files changed, 27 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index c18df53992..819a6488e5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6805,7 +6805,7 @@ breakText Glyphs Глифи @msg stroke cannot be set on a symbol instance stroke не може да се задава за екземпляр на символ @msg fill on a symbol instance must be a solid color or none fill на екземпляр на символ трябва да е плътен цвят или none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} не може да се задава за изображение без ефект „Конвертиране в фигура“ или „Преобразуване на обекта в контур“ -@msg pass newName, registration, exportType, nineSlice and/or type задайте newName, registration, exportType, nineSlice и/или type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid задайте newName, registration, exportType, nineSlice, type и/или alignToPixelGrid Text Flow Поток на текста By Rows По редове By Columns По колони diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3484e06bdf..419701f804 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6857,7 +6857,7 @@ shape Open Otvoren @msg stroke cannot be set on a symbol instance stroke se ne može postaviti na instancu simbola @msg fill on a symbol instance must be a solid color or none fill instance simbola mora biti puna boja ili none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} se ne može postaviti na sliku bez efekta „Pretvori u oblik“ ili „Objekat u obrisu“ -@msg pass newName, registration, exportType, nineSlice and/or type navedite newName, registration, exportType, nineSlice i/ili type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid navedite newName, registration, exportType, nineSlice, type i/ili alignToPixelGrid Text Flow Tok teksta By Rows Po redovima By Columns Po kolonama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5970f572d8..5ddc80126e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7468,7 +7468,7 @@ breakText Glyphs Glifs @msg stroke cannot be set on a symbol instance stroke no es pot definir en una instància de símbol @msg fill on a symbol instance must be a solid color or none el fill d’una instància de símbol ha de ser un color sòlid o none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} no es pot definir en una imatge sense l’efecte Converteix en forma o Contorneja l’objecte -@msg pass newName, registration, exportType, nineSlice and/or type indiqueu newName, registration, exportType, nineSlice i/o type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indiqueu newName, registration, exportType, nineSlice, type i/o alignToPixelGrid Text Flow Flux del text By Rows Per files By Columns Per columnes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3aecd729a9..b9d782b8a1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7472,7 +7472,7 @@ breakText Glyphs Glyfy @msg stroke cannot be set on a symbol instance stroke nelze nastavit u instance symbolu @msg fill on a symbol instance must be a solid color or none fill instance symbolu musí být plná barva nebo none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} nelze nastavit u obrazu bez efektu Převést na tvar nebo Převést objekt na obrys -@msg pass newName, registration, exportType, nineSlice and/or type zadejte newName, registration, exportType, nineSlice a/nebo type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid zadejte newName, registration, exportType, nineSlice, type a/nebo alignToPixelGrid Text Flow Tok textu By Rows Po řádcích By Columns Po sloupcích diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59a09bca8b..0788b34379 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9510,7 +9510,7 @@ breakText Glyphs Glyffer @msg stroke cannot be set on a symbol instance stroke kan ikke angives for en symbolforekomst @msg fill on a symbol instance must be a solid color or none fill på en symbolforekomst skal være en ensfarvet farve eller none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan ikke angives for et billede uden effekten Konvertér til form eller Objekt til kontur -@msg pass newName, registration, exportType, nineSlice and/or type angiv newName, registration, exportType, nineSlice og/eller type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid angiv newName, registration, exportType, nineSlice, type og/eller alignToPixelGrid Text Flow Tekstflow By Rows Efter rækker By Columns Efter kolonner diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index afa0451e48..5a7f79a9c2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7063,7 +7063,7 @@ breakText Glyphs Glyphen @msg stroke cannot be set on a symbol instance stroke kann nicht für eine Symbolinstanz gesetzt werden @msg fill on a symbol instance must be a solid color or none fill einer Symbolinstanz muss eine Vollfarbe oder none sein @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kann nicht für ein Bild ohne den Effekt „In Form umwandeln“ oder „Objekt in Pfade umwandeln“ gesetzt werden -@msg pass newName, registration, exportType, nineSlice and/or type geben Sie newName, registration, exportType, nineSlice und/oder type an +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid geben Sie newName, registration, exportType, nineSlice, type und/oder alignToPixelGrid an Text Flow Textfluss By Rows Nach Zeilen By Columns Nach Spalten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 726e0630a0..cd9277bf96 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7441,7 +7441,7 @@ breakText Glyphs Γλύφοι @msg stroke cannot be set on a symbol instance το stroke δεν μπορεί να οριστεί σε στιγμιότυπο συμβόλου @msg fill on a symbol instance must be a solid color or none το fill ενός στιγμιότυπου συμβόλου πρέπει να είναι συμπαγές χρώμα ή none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it το {key} δεν μπορεί να οριστεί σε εικόνα χωρίς το εφέ «Μετατροπή σε σχήμα» ή «Μετατροπή αντικειμένου σε περιγράμματα» -@msg pass newName, registration, exportType, nineSlice and/or type δώστε newName, registration, exportType, nineSlice ή/και type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid δώστε newName, registration, exportType, nineSlice, type ή/και alignToPixelGrid Text Flow Ροή κειμένου By Rows Κατά γραμμές By Columns Κατά στήλες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c668971d37..fb81283e20 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7429,7 +7429,7 @@ breakText Glyphs Glifos @msg stroke cannot be set on a symbol instance stroke no se puede definir en una instancia de símbolo @msg fill on a symbol instance must be a solid color or none el fill de una instancia de símbolo debe ser un color sólido o none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} no se puede definir en una imagen sin el efecto Convertir en forma o Contornear objeto -@msg pass newName, registration, exportType, nineSlice and/or type indique newName, registration, exportType, nineSlice y/o type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indique newName, registration, exportType, nineSlice, type y/o alignToPixelGrid Text Flow Flujo de texto By Rows Por filas By Columns Por columnas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 08a84268a7..5c30a92099 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7517,7 +7517,7 @@ breakText Glyphs Merkit @msg stroke cannot be set on a symbol instance stroke-arvoa ei voi asettaa symbolin ilmentymälle @msg fill on a symbol instance must be a solid color or none symbolin ilmentymän fill-arvon on oltava tasainen väri tai none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key}-arvoa ei voi asettaa kuvalle, jolla ei ole tehostetta Muunna muodoksi tai Muunna objekti ääriviivoiksi -@msg pass newName, registration, exportType, nineSlice and/or type anna newName, registration, exportType, nineSlice ja/tai type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid anna newName, registration, exportType, nineSlice, type ja/tai alignToPixelGrid Text Flow Tekstin kulku By Rows Riveittäin By Columns Sarakkeittain diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 197e20565c..e76a0b0ce5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7467,7 +7467,7 @@ breakText Glyphs Glyphes @msg stroke cannot be set on a symbol instance stroke ne peut pas être défini sur une instance de symbole @msg fill on a symbol instance must be a solid color or none le fill d’une instance de symbole doit être une couleur unie ou none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} ne peut pas être défini sur une image sans l’effet Convertir en forme ou Vectoriser l’objet -@msg pass newName, registration, exportType, nineSlice and/or type indiquez newName, registration, exportType, nineSlice et/ou type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indiquez newName, registration, exportType, nineSlice, type et/ou alignToPixelGrid Text Flow Flux du texte By Rows Par lignes By Columns Par colonnes diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2014f66fdc..8d71e16c69 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7868,7 +7868,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg parameters must be an object parameters एक ऑब्जेक्ट होना चाहिए @msg params must be an object params एक ऑब्जेक्ट होना चाहिए @msg part of the program isn't valid PostScript text कार्यक्रम का हिस्सा मान्य नहीं है PostScript टेक्स्ट -@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice और/या type दें +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type और/या alignToPixelGrid दें @msg passwords can have up to {MAX_PASSWORD} bytes पासवर्ड {MAX_PASSWORD} बाइट्स तक हो सकता है @msg paste unavailable पेस्ट करें अनुपलब्ध @msg Pasting चिपकाना diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9b536ed556..8226922371 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7457,7 +7457,7 @@ breakText Glyphs Glifák @msg stroke cannot be set on a symbol instance a stroke nem állítható be szimbólumpéldányon @msg fill on a symbol instance must be a solid color or none a szimbólumpéldány fill értéke csak egyszínű szín vagy none lehet @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it a {key} nem állítható be olyan képen, amelyen nincs Átalakítás alakzattá vagy Objektum útvonallá alakítása effektus -@msg pass newName, registration, exportType, nineSlice and/or type adja meg a newName, registration, exportType, nineSlice és/vagy type értékét +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid adja meg a newName, registration, exportType, nineSlice, type és/vagy alignToPixelGrid értékét Text Flow Szövegfolyás By Rows Soronként By Columns Oszloponként diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 760f0b591a..35fd9cc3ad 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6820,7 +6820,7 @@ breakText Glyphs Glif @msg stroke cannot be set on a symbol instance stroke tidak dapat diatur pada instans simbol @msg fill on a symbol instance must be a solid color or none fill pada instans simbol harus berupa warna solid atau none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} tidak dapat diatur pada gambar tanpa efek Konversi ke bentuk atau Kerangka objek -@msg pass newName, registration, exportType, nineSlice and/or type berikan newName, registration, exportType, nineSlice dan/atau type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid berikan newName, registration, exportType, nineSlice, type dan/atau alignToPixelGrid Text Flow Alur teks By Rows Per baris By Columns Per kolom diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2540830b01..6e8752b0fd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7099,7 +7099,7 @@ breakText Glyphs Glifi @msg stroke cannot be set on a symbol instance stroke non può essere impostato su un’istanza di simbolo @msg fill on a symbol instance must be a solid color or none il fill di un’istanza di simbolo deve essere un colore pieno o none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} non può essere impostato su un’immagine senza l’effetto Converti in forma o Contorna oggetto -@msg pass newName, registration, exportType, nineSlice and/or type specifica newName, registration, exportType, nineSlice e/o type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid specifica newName, registration, exportType, nineSlice, type e/o alignToPixelGrid Text Flow Flusso del testo By Rows Per righe By Columns Per colonne diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 084c59e9a0..516e2c318b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8976,7 +8976,7 @@ breakText Glyphs 字形 @msg stroke cannot be set on a symbol instance シンボルインスタンスには stroke を設定できません @msg fill on a symbol instance must be a solid color or none シンボルインスタンスの fill は単色または none にしてください @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 「シェイプに変換」または「オブジェクトのアウトライン」効果のない画像には {key} を設定できません -@msg pass newName, registration, exportType, nineSlice and/or type newName、registration、exportType、nineSlice、type のいずれかを指定してください +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName、registration、exportType、nineSlice、type、alignToPixelGrid のいずれかを指定してください Text Flow テキストの流れ By Rows 行方向 By Columns 列方向 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index bd069f4b9b..aed4c10348 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9607,7 +9607,7 @@ breakText Glyphs გლიფები @msg stroke cannot be set on a symbol instance stroke ვერ დაყენდება სიმბოლოს ეგზემპლარზე @msg fill on a symbol instance must be a solid color or none სიმბოლოს ეგზემპლარის fill უნდა იყოს ერთფეროვანი ფერი ან none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} ვერ დაყენდება გამოსახულებაზე „ფიგურად გარდაქმნის“ ან „ობიექტის კონტურებად გარდაქმნის“ ეფექტის გარეშე -@msg pass newName, registration, exportType, nineSlice and/or type მიუთითეთ newName, registration, exportType, nineSlice და/ან type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid მიუთითეთ newName, registration, exportType, nineSlice, type და/ან alignToPixelGrid Text Flow ტექსტის დინება By Rows სტრიქონების მიხედვით By Columns სვეტების მიხედვით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 239a805465..c7e040e4f5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7063,7 +7063,7 @@ breakText Glyphs 글리프 @msg stroke cannot be set on a symbol instance 심볼 인스턴스에는 stroke를 설정할 수 없습니다 @msg fill on a symbol instance must be a solid color or none 심볼 인스턴스의 fill은 단색 또는 none이어야 합니다 @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 모양으로 변환 또는 개체 윤곽선화 효과가 없는 이미지에는 {key}을(를) 설정할 수 없습니다 -@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice 및/또는 type을 지정하세요 +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type 및/또는 alignToPixelGrid을 지정하세요 Text Flow 텍스트 흐름 By Rows 행 방향 By Columns 열 방향 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2f98ee84fe..b289bd15d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9346,7 +9346,7 @@ breakText Glyphs Glyphs @msg stroke cannot be set on a symbol instance stroke kan niet worden ingesteld op een symboolinstantie @msg fill on a symbol instance must be a solid color or none fill van een symboolinstantie moet een egale kleur of none zijn @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan niet worden ingesteld op een afbeelding zonder het effect Converteren naar vorm of Object omtrekken -@msg pass newName, registration, exportType, nineSlice and/or type geef newName, registration, exportType, nineSlice en/of type op +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid geef newName, registration, exportType, nineSlice, type en/of alignToPixelGrid op Text Flow Tekstdoorloop By Rows Per rij By Columns Per kolom diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index bf8c7593a1..6293ddf5f9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7328,7 +7328,7 @@ breakText Glyphs Glify @msg stroke cannot be set on a symbol instance nie można ustawić stroke dla wystąpienia symbolu @msg fill on a symbol instance must be a solid color or none fill wystąpienia symbolu musi być jednolitym kolorem lub none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it nie można ustawić {key} dla obrazu bez efektu Konwertuj na kształt lub Kontur obiektu -@msg pass newName, registration, exportType, nineSlice and/or type podaj newName, registration, exportType, nineSlice i/lub type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid podaj newName, registration, exportType, nineSlice, type i/lub alignToPixelGrid Text Flow Przepływ tekstu By Rows Wierszami By Columns Kolumnami diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 03b9998eb2..ac622720ed 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7503,7 +7503,7 @@ breakText Glyphs Glifos @msg stroke cannot be set on a symbol instance stroke não pode ser definido em uma instância de símbolo @msg fill on a symbol instance must be a solid color or none o fill de uma instância de símbolo deve ser uma cor sólida ou none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} não pode ser definido em uma imagem sem o efeito Converter em Forma ou Contornar Objeto -@msg pass newName, registration, exportType, nineSlice and/or type informe newName, registration, exportType, nineSlice e/ou type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid informe newName, registration, exportType, nineSlice, type e/ou alignToPixelGrid # Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). on the canvas to create one na tela para criar um 1 Layer 1 camada diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a729b05460..71af9c062b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7462,7 +7462,7 @@ breakText Glyphs Глифы @msg stroke cannot be set on a symbol instance stroke нельзя задать для экземпляра символа @msg fill on a symbol instance must be a solid color or none fill экземпляра символа должен быть сплошным цветом или none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} нельзя задать для изображения без эффекта «Преобразовать в фигуру» или «Обвести объект» -@msg pass newName, registration, exportType, nineSlice and/or type укажите newName, registration, exportType, nineSlice и/или type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid укажите newName, registration, exportType, nineSlice, type и/или alignToPixelGrid Text Flow Поток текста By Rows По строкам By Columns По столбцам diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d4c923d87d..31bd152ac4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7488,7 +7488,7 @@ breakText Glyphs Glyfer @msg stroke cannot be set on a symbol instance stroke kan inte anges för en symbolinstans @msg fill on a symbol instance must be a solid color or none fill för en symbolinstans måste vara en enfärgad färg eller none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan inte anges för en bild utan effekten Konvertera till form eller Konvertera objekt till konturer -@msg pass newName, registration, exportType, nineSlice and/or type ange newName, registration, exportType, nineSlice och/eller type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid ange newName, registration, exportType, nineSlice, type och/eller alignToPixelGrid Text Flow Textflöde By Rows Radvis By Columns Kolumnvis diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2017637952..f536115ef3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9350,7 +9350,7 @@ breakText Glyphs Glifler @msg stroke cannot be set on a symbol instance stroke bir sembol örneğinde ayarlanamaz @msg fill on a symbol instance must be a solid color or none bir sembol örneğinin fill değeri düz renk veya none olmalıdır @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key}, Şekle Dönüştür veya Anahat Nesnesi efekti olmayan bir görüntüde ayarlanamaz -@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice ve/veya type verin +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type ve/veya alignToPixelGrid verin Text Flow Metin Akışı By Rows Satırlara Göre By Columns Sütunlara Göre diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 53ca6b8a43..cfea3031e8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7081,7 +7081,7 @@ breakText Glyphs Гліфи @msg stroke cannot be set on a symbol instance stroke не можна задати для екземпляра символу @msg fill on a symbol instance must be a solid color or none fill екземпляра символу має бути суцільним кольором або none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} не можна задати для зображення без ефекту «Перетворити на фігуру» або «Обвести об’єкт» -@msg pass newName, registration, exportType, nineSlice and/or type вкажіть newName, registration, exportType, nineSlice та/або type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid вкажіть newName, registration, exportType, nineSlice, type та/або alignToPixelGrid Text Flow Потік тексту By Rows За рядками By Columns За стовпцями diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7dcf6219fd..d599ffb419 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7098,7 +7098,7 @@ breakText Glyphs Glyph @msg stroke cannot be set on a symbol instance không thể đặt stroke cho thực thể ký hiệu @msg fill on a symbol instance must be a solid color or none fill của thực thể ký hiệu phải là màu đặc hoặc none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it không thể đặt {key} cho hình ảnh không có hiệu ứng Chuyển thành hình dạng hoặc Đường bao đối tượng -@msg pass newName, registration, exportType, nineSlice and/or type hãy cung cấp newName, registration, exportType, nineSlice và/hoặc type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid hãy cung cấp newName, registration, exportType, nineSlice, type và/hoặc alignToPixelGrid Text Flow Luồng văn bản By Rows Theo hàng By Columns Theo cột diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5c8ea12be7..18cb41974d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7313,7 +7313,7 @@ breakText Glyphs 字形 @msg stroke cannot be set on a symbol instance 无法为符号实例设置 stroke @msg fill on a symbol instance must be a solid color or none 符号实例的 fill 必须是纯色或 none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 无法为没有“转换为形状”或“轮廓化对象”效果的图像设置 {key} -@msg pass newName, registration, exportType, nineSlice and/or type 请提供 newName、registration、exportType、nineSlice 和/或 type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid 请提供 newName、registration、exportType、nineSlice、type 和/或 alignToPixelGrid Text Flow 文本流向 By Rows 按行 By Columns 按列 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2134e31d7f..6bffbba9bf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7122,7 +7122,7 @@ breakText Glyphs 字符 @msg stroke cannot be set on a symbol instance 無法為符號範例設定 stroke @msg fill on a symbol instance must be a solid color or none 符號範例的 fill 必須是純色或 none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 無法為沒有「轉換為形狀」或「外框物件」效果的影像設定 {key} -@msg pass newName, registration, exportType, nineSlice and/or type 請提供 newName、registration、exportType、nineSlice 和/或 type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid 請提供 newName、registration、exportType、nineSlice、type 和/或 alignToPixelGrid Text Flow 文字流向 By Rows 依列 By Columns 依欄 From 3d0900bd77f207e4354458f2a3949a6237a466d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:39:20 -0800 Subject: [PATCH 39/50] Symbols: a symbol instance snapped to the pixel grid takes its linked mask along Snapping an instance of a pixel-aligned symbol to whole points set its transform directly, so the art of a linked opacity mask stayed at the old fractional position and shifted against the artwork. The instance now moves as any move moves it, and the art of an unlinked mask stays where it is. --- crates/engine/src/cmd/object/pixelgrid.rs | 12 ++++++-- crates/engine/src/tests/pixelalign.rs | 34 +++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index a8bb12b429..ba95db0d69 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -358,9 +358,10 @@ fn snap_mask(n: &mut Node) -> bool { /// Move symbol instance `n` to whole points when its transform places its symbol's art at the /// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled, -/// rotated (a half turn included) or sheared instance stays where it is. +/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any +/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it. fn snap_instance(n: &mut Node, natural: &HashMap) { - let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return }; + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return }; let Some(nat) = natural.get(symbol.as_str()) else { return }; let [a, b, c, d, e, f] = xf.as_coeffs(); let [na, _, _, nd, _, _] = nat.as_coeffs(); @@ -373,7 +374,12 @@ fn snap_instance(n: &mut Node, natural: &HashMap) { return; } let (x, y) = (e.round(), f.round()); - if x != e || y != f { + if x == e && y == f { + return; + } + n.transform(Affine::translate((x - e, y - f)), Scaling::default()); + // Whole points exactly, which adding the offset to the old position need not give. + if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind { *xf = Affine::new([a, b, c, d, x, y]); } } diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index b70098d9c9..1258ae58da 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -1436,6 +1436,40 @@ fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() { assert!(whole(&[(e, f)]), "{e} {f}"); } +/// An instance snapped to whole points takes the art of its linked opacity mask along by the same +/// amount, as a move does; the art of an unlinked mask stays where it is. +#[test] +fn an_instance_snapped_to_the_grid_moves_its_linked_mask() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + s.execute("symbol.new", &json!({"name": "Px"})).unwrap(); + let place = |s: &mut Session, x: f64, linked: bool| { + let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) }; + d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask)); + inst + }; + let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false)); + let mask_points = |s: &Session, inst: u64| { + let d = &s.doc().unwrap().doc; + let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap(); + mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::>() + }; + let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked)); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let [.., e0, f0] = xf_before.as_coeffs(); + let [.., e, f] = instance_xf(&s, linked).as_coeffs(); + assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}"); + let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect(); + let after = mask_points(&s, linked); + assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}"); + assert!(whole(&placed_points(&s, unlinked))); + assert_eq!(mask_points(&s, unlinked), unlinked_before); +} + /// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored /// on the pixel grid, so its instances stay on it. #[test] From fa42ea6dc8bff86d70d7179c357a00d3f8e67a2c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:49:19 -0800 Subject: [PATCH 40/50] Symbols: snap a pixel-aligned symbol's instances again only when its editing mode ends While a pixel-aligned symbol was open in symbol editing mode, every edit snapped its art and walked the whole document for its instances, even when the art did not change. That pass now runs when editing mode for the symbol ends; edits that change the art still snap it and its instances. --- crates/engine/src/cmd/object/pixelgrid.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index ba95db0d69..5cfc22b7f8 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -174,7 +174,10 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { return; } let was = before.pixel_aligned_symbols(); + // The symbol whose editing mode this edit ended, if any. let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned); let mut every = false; for name in &aligned { let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); @@ -184,7 +187,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { _ => true, }; let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name); - if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed { + if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed { snap_symbol_art(doc, name); every = true; } From 2a973becbc8723d2fa7253e5dcbf35d30bfc10ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:15:50 -0800 Subject: [PATCH 41/50] Symbols: Align to Pixel Grid leaves symbol editing layers to their symbol - An instance of a pixel-aligned symbol on another symbol's editing layer is part of that symbol's art, so it is no longer snapped and written into that art. - Turning Align to Pixel Grid on for the symbol being edited now writes its art back and shows it snapped on the editing layer at once, instead of after the next edit. --- crates/engine/src/cmd/object/pixelgrid.rs | 15 ++++++-- crates/engine/src/cmd/symboledit.rs | 3 +- crates/engine/src/tests/pixelalign.rs | 46 +++++++++++++++++++++++ 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 5cfc22b7f8..8d2a344ffe 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -166,8 +166,8 @@ const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9; /// (while it is edited, the art snaps as the editing layer is written back to it). Every instance /// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a /// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included. -/// An instance in another symbol's art is placed by that symbol's instances and is left as it is. -/// A document without pixel-aligned symbols is not walked. +/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by +/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked. fn refresh_symbols(before: &Document, doc: &mut Document) { let aligned = doc.pixel_aligned_symbols(); if aligned.is_empty() { @@ -193,16 +193,23 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { } } let natural: HashMap = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + // The symbol editing layer holds another symbol's art. + let editing = doc.symbol_edit.as_ref().map(|e| e.layer); if every { for layer in doc.layers.iter_mut() { - if holds_instance(layer, &natural) { + if Some(layer.id) != editing && holds_instance(layer, &natural) { snap_instances_in(Arc::make_mut(layer), &natural); } } return; } let (mut ids, mut masked) = (vec![], vec![]); - changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + if let Some(layer) = editing { + let outside = |layers: &[Arc]| layers.iter().filter(|l| l.id != layer).cloned().collect::>(); + changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked); + } else { + changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + } for id in ids { if let Some(n) = doc.node_mut(id) { snap_instance(n, &natural); diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index c3fc9a4392..77266b5aaa 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) { None => return Ok(()), Some(b) => match art_of(before) { - Some(old) if same(&old) => return Ok(()), + // Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped. + Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()), old => (old.unwrap_or_default(), b.group), }, }; diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 1258ae58da..00b4cce694 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -1493,3 +1493,49 @@ fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() { let pts = placed_points(&s, inst); assert!(whole(&pts), "{pts:?}"); } + +/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid +/// on the editing layer at once, and its instance stays on it after editing ends. +#[test] +fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + let before = points(&s, part); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let xf = d.symbol_edit.as_ref().unwrap().xf; + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect(); + let shown = points(&s, part); + assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); +} + +/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that +/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are. +#[test] +fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [b]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone(); + let shown = instance_xf(&s, inner); + assert!(!whole(&placed_points(&s, inner))); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(instance_xf(&s, inner), shown); + let d = &s.doc().unwrap().doc; + assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art)); +} From 6e2cad713a8a5b13525cc7b8235508532bf9a3fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:23:44 -0800 Subject: [PATCH 42/50] Check Spelling: a deleted selected object leaves the dialog's scope When another command deleted one of the objects the dialog was opened on, the next check named that object in its ids and was refused, so the rest of the selection was never reached. The check now leaves deleted objects out; with every one deleted it checks nothing rather than the whole document. --- crates/ui-egui/src/dialogs/check_spelling.rs | 40 +++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs index 21eae512b0..efba47da86 100644 --- a/crates/ui-egui/src/dialogs/check_spelling.rs +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -277,9 +277,19 @@ fn queued_word(w: &Value) -> Option { } } -/// The check's params for the dialog's scope, going on from `from` ((id, byte)) when given. -fn check_params(d: &Dialog, from: Option<(u64, usize)>, max: usize) -> Value { - let ids = d.fields.get("ids").cloned().unwrap_or(Value::Null); +/// The check's params for the dialog's scope, going on from `from` ((id, byte)) when given. A +/// selected object that another command deleted is left out, so the rest of the selection is still +/// checked; with every one deleted, the list is empty and the check finds nothing (not the whole +/// document, which `ids` left out would check). +fn check_params(app: &VectorcraftApp, d: &Dialog, from: Option<(u64, usize)>, max: usize) -> Value { + let ids = match d.fields.get("ids") { + Some(Value::Array(ids)) => { + let exists = + |id: &Value| id.as_u64().is_some_and(|id| app.session.doc().is_ok_and(|st| st.doc.node(vectorcraft_doc::NodeId(id)).is_some())); + Value::Array(ids.iter().filter(|id| exists(id)).cloned().collect()) + } + _ => Value::Null, + }; match from { Some((id, byte)) => json!({ "ids": ids, "from": { "id": id, "byte": byte }, "max": max }), None => json!({ "ids": ids, "max": max }), @@ -293,7 +303,8 @@ fn check_params(d: &Dialog, from: Option<(u64, usize)>, max: usize) -> Value { pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog, mut from: Option<(u64, usize)>, mut max: usize) -> Result<(), String> { let skipped = get_skipped(d); loop { - let check_res = match app.run("text.spelling.check", check_params(d, from, max)) { + let params = check_params(app, d, from, max); + let check_res = match app.run("text.spelling.check", params) { Ok(r) => r, // The object `from` names left the scope (another command hid, locked or deleted // it): start the scope again, where every word before is now right or skipped. @@ -541,7 +552,8 @@ fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { let mut by_node: BTreeMap> = BTreeMap::new(); let mut from = None; loop { - let check_res = app.run("text.spelling.check", check_params(d, from, page())).map_err(|e| e.to_string())?; + let params = check_params(app, d, from, page()); + let check_res = app.run("text.spelling.check", params).map_err(|e| e.to_string())?; let words: Vec = check_res.get("words").and_then(Value::as_array).map(|a| a.iter().filter_map(word_at).collect()).unwrap_or_default(); let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); for w in &words { @@ -980,6 +992,24 @@ mod tests { assert_eq!(shown(&app), (second, 0, WORD_B.to_string()), "on to the type still in the scope"); } + #[test] + fn a_selected_object_deleted_under_the_dialog_leaves_the_scope() { + let mut app = app(); + let first = text(&mut app, 50.0, &format!("{WORD_A} here")); + let second = text(&mut app, 100.0, &format!("{WORD_B} there")); + let outside = text(&mut app, 150.0, &format!("{WORD_C} elsewhere")); + app.run("select.set", json!({ "ids": [first, second] })).unwrap(); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app).0, first); + app.run("edit.clear", json!({ "ids": [first] })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (second, 0, WORD_B.to_string()), "on to the selected type that is left"); + app.run("edit.clear", json!({ "ids": [second] })).unwrap(); + act(&mut app, super::ignore); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.bool("done"), "nothing left in the selection: not the rest of the document ({outside})"); + } + /// Marks the first `n` occurrences of WORD_B in `id` (each WORD_B and a space) as skipped by /// Ignore, with the last of them shown. fn ignored_b_words(app: &mut VectorcraftApp, id: u64, n: usize) { From af67af91f6078af9f3630194974fde186111d6bc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:24:30 -0800 Subject: [PATCH 43/50] Type: Show Similar Fonts reads the loaded faces once for the whole list similar_families looked up each listed family's traits on its own, and each look scanned every loaded face, so ordering the font menu took time in the square of the families loaded. It now gathers the loaded faces' traits in one pass and reads the scan's catalog once, and family_traits uses the same helpers, so both give the same traits. --- crates/text/src/fontdb/lookup.rs | 95 ++++++++++++++++++++++---------- 1 file changed, 65 insertions(+), 30 deletions(-) diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index f27c5fbc44..597e8bbc6c 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -18,6 +18,45 @@ use super::{ /// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads. const MAX_POSTSCRIPT_FACES: usize = 16; +/// Keeps `other`'s variable flag in `traits`, and its likeness when it is nearer an upright +/// Regular. +fn merge_traits(traits: &mut FontTraits, other: &FontTraits) { + traits.variable |= other.variable; + if regular_rank(&other.likeness) < regular_rank(&traits.likeness) { + traits.likeness = other.likeness; + } +} + +/// The traits of the loaded faces of each family, or of `only` that family, keyed by the family's +/// name in ASCII lowercase: the first face's, with the other faces merged in ([`merge_traits`]). +fn loaded_traits(faces: &[Arc], only: Option<&str>) -> std::collections::HashMap { + let mut found = std::collections::HashMap::::new(); + for f in faces.iter().filter(|f| only.is_none_or(|o| f.family.eq_ignore_ascii_case(o))) { + match found.entry(f.family.to_ascii_lowercase()) { + std::collections::hash_map::Entry::Vacant(e) => { + e.insert(f.traits); + } + std::collections::hash_map::Entry::Occupied(mut e) => merge_traits(e.get_mut(), &f.traits), + } + } + found +} + +/// A family's traits from its `loaded` faces with what the scan in `catalog` found for `key` (its +/// name in ASCII lowercase) merged in, or the scan's alone when none is loaded. +fn scanned_traits(loaded: Option, catalog: &Catalog, key: &str) -> FontTraits { + let scanned = catalog.get(key).and_then(|c| c.traits); + match loaded { + None => scanned.unwrap_or_default(), + Some(mut traits) => { + if let Some(found) = scanned { + merge_traits(&mut traits, &found); + } + traits + } + } +} + impl FontDb { /// The family's own name and the style for a name given in a document: any of a family's /// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its @@ -91,35 +130,21 @@ impl FontDb { if let Some((base, _)) = self.composite_base(family) { return self.family_traits(&base); } - let loaded = { - let faces = self.read_faces(); - let mut found: Option = None; - for f in faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)) { - match &mut found { - None => found = Some(f.traits), - Some(traits) => { - traits.variable |= f.traits.variable; - if regular_rank(&f.traits.likeness) < regular_rank(&traits.likeness) { - traits.likeness = f.traits.likeness; - } - } - } - } - found - }; - let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits); + let key = family.to_ascii_lowercase(); + let loaded = loaded_traits(&self.read_faces(), Some(family)).remove(&key); match loaded { - None => scanned(&self.read_catalog()).unwrap_or_default(), - Some(mut traits) => { - // What the scan found so far, without starting it. - if let Some(found) = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)) { - traits.variable |= found.variable; - if regular_rank(&found.likeness) < regular_rank(&traits.likeness) { - traits.likeness = found.likeness; - } - } - traits - } + None => scanned_traits(None, &self.read_catalog(), &key), + // What the scan found so far, without starting it. + Some(_) => scanned_traits(loaded, &self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner), &key), + } + } + + /// The name [`family_traits`](Self::family_traits) takes `family`'s traits by, in ASCII + /// lowercase: a composite font's base font's. + fn traits_key(&self, family: &str) -> String { + match self.composite_base(family) { + Some((base, _)) => self.traits_key(&base), + None => family.to_ascii_lowercase(), } } @@ -141,10 +166,20 @@ impl FontDb { 2 } }; + // Every family's traits from one pass over the loaded faces and one look at the scan, as + // `family_traits` finds them; composite fonts are resolved before any lock is held. + let keys: Vec = families.iter().map(|f| self.traits_key(f)).collect(); + let loaded = loaded_traits(&self.read_faces(), None); + let catalog = if keys.iter().all(|k| loaded.contains_key(k)) { + self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner) + } else { + self.read_catalog() + }; let mut keyed: Vec<(bool, f32, &String)> = families .iter() - .map(|f| { - let traits = self.family_traits(f); + .zip(&keys) + .map(|(f, key)| { + let traits = scanned_traits(loaded.get(key).copied(), &catalog, key); let d = if f.eq_ignore_ascii_case(family) { -1.0 } else { From aac0a8b2a7d8aa8d0fc456a946ea218195b29383 Mon Sep 17 00:00:00 2001 From: makesomethingshit Date: Mon, 16 Nov 2026 10:33:31 +0900 Subject: [PATCH 44/50] Fix #8005: Grow the spectrum with the Color panel --- crates/ui-egui/src/dock.rs | 1 + crates/ui-egui/src/panels/color.rs | 12 +++++- crates/ui-egui/src/panels/color/tests.rs | 54 ++++++++++++++++++++++++ docs/roadmap.md | 5 ++- docs/target-app-parity.md | 6 ++- docs/ui-parity.md | 3 +- 6 files changed, 74 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index c5070d67f2..412eddac98 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -31,6 +31,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width: ui.set_max_height(tall); panels::libraries(app, ui); } + None if id == "color" && widgets::panel_footer_bottom(ui).is_some() => panels::color::show_sized(app, ui, tall), None => panels::show_icon_panel(app, ui, id), } }); diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 0ad9c369fd..b156185ff3 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -674,6 +674,12 @@ fn spectrum(ui: &mut Ui, mode: Mode, size: egui::Vec2) -> Option { /// Draw numeric paint controls, retaining live components while the color and settings match. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + show_sized(app, ui, 0.0); +} + +/// Draw the Color panel in a sized dock body; compact mixers use [`show`]. +pub(crate) fn show_sized(app: &mut VectorcraftApp, ui: &mut Ui, height: f32) { + let top = ui.next_widget_position().y; let t = Tokens::get(ui.ctx()); let tgt = target(app, ui); let color = tgt.color(); @@ -684,7 +690,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let hit = ui .horizontal(|ui| { super::proxy(app, ui, 40.0); - spectrum(ui, mode, vec2(ui.available_width(), 40.0)) + spectrum(ui, mode, vec2(ui.available_width(), height.max(40.0))) }) .inner; match hit { @@ -851,7 +857,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); ui.add_space(4.0); - match spectrum(ui, mode, vec2(ui.available_width(), 46.0)) { + // Measure from the content origin so scrolling moves the ramp without stretching it. + let remaining = height - (ui.next_widget_position().y - top); + match spectrum(ui, mode, vec2(ui.available_width(), remaining.max(46.0))) { Some(SpectrumHit::Pick(c, phase)) => pick(c, phase, &mut new), Some(SpectrumHit::Cycle) => set_mode(app, &tgt, mode.next()), Some(SpectrumHit::Recolor { invert }) => recolor(app, ui, &tgt, invert, alt), diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index bd605eef01..07295dc256 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -8,6 +8,60 @@ fn app() -> VectorcraftApp { app } +fn painted_spectrum(shape: &egui::Shape) -> Option { + match shape { + egui::Shape::Mesh(mesh) if mesh.vertices.len() > 500 => Some(mesh.calc_bounds()), + egui::Shape::Vec(shapes) => shapes.iter().find_map(painted_spectrum), + _ => None, + } +} + +/// #8005: enlarging the Color panel gives the spectrum the added vertical space. +#[test] +fn the_spectrum_grows_with_the_color_panel() { + for hidden in [false, true] { + let mut app = app(); + app.ui.color_hide_options = hidden; + let ctx = egui::Context::default(); + let mut rects = Vec::new(); + for height in [300.0, 480.0] { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, height))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, Some(ui.max_rect().bottom())); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { + crate::dock::panel_body(&mut app, ui, "color", 300.0, height - 20.0); + }); + }); + rects.push(out.shapes.iter().find_map(|shape| painted_spectrum(&shape.shape)).expect("the spectrum is painted")); + out.textures_delta.clear(); + } + assert!((rects[1].top() - rects[0].top()).abs() < 1.0, "resizing keeps the ramp's top stable"); + assert!((rects[1].height() - rects[0].height() - 180.0).abs() < 1.0, "options hidden={hidden}: {rects:?}"); + } +} + +#[test] +fn a_short_color_panel_scrolls_without_stretching_the_spectrum() { + let mut app = app(); + let ctx = egui::Context::default(); + for offset in [0.0, 100.0] { + for _ in 0..3 { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 120.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, Some(ui.max_rect().bottom())); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { + widgets::panel_scroll(ui, egui::ScrollArea::vertical().vertical_scroll_offset(offset), |ui| { + crate::dock::panel_body(&mut app, ui, "color", 300.0, 100.0); + }); + }); + }); + let r = out.shapes.iter().find_map(|shape| painted_spectrum(&shape.shape)).expect("the spectrum is painted"); + assert!((r.height() - 46.0).abs() < 1.0, "offset={offset}: {r:?}"); + out.textures_delta.clear(); + } + } +} + /// Run the panel for one frame with `events` and `modifiers`; returns the spectrum's rect (when /// the options are shown) and the panel's height. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: egui::Modifiers) -> (Option, f32) { diff --git a/docs/roadmap.md b/docs/roadmap.md index da1645efb2..fae091f647 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -159,7 +159,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | @@ -208,6 +208,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimates unchanged | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7ab675f44e..23915b5ce1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -381,7 +381,7 @@ Depth here is "does the basic use work", not the area's full score. | Shape tools (rectangle, ellipse, polygon, star, line) | 9 | 95% | all shape tools, Live Corners | | Selection, move, scale, rotate | 9 | 92% | bounding box, smart guides, transform tools | | Pen and Pencil, basic use | 7 | 88% | [ui-parity.md](ui-parity.md); a few Pencil and Curvature options missing | -| Fill, stroke, colour, swatches | 9 | 95% | M3 done; transform-aware Eyedropper character dimensions (#6404); highlighted-text Eyedropper font/paint and source/target transparency refusal regression-tested; scores and hours unchanged | +| Fill, stroke, colour, swatches | 9 | 95% | M3 done; Color spectrum fills a resized panel (#8005); transform-aware Eyedropper character dimensions (#6404); highlighted-text Eyedropper font/paint and source/target transparency refusal regression-tested; scores and hours unchanged | | Gradients, basic | 4 | 90% | Gradient panel and on-canvas annotator | | Type: point and area text, font, size | 8 | 88% | font menu with previews; Hyphenation… and Justification… options per paragraph (#2310, #2755) | | Align, group, arrange | 6 | 95% | | @@ -1643,6 +1643,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Swatches panel's menu has its own Show Recent Colors item: unchecking it hides the panel's Recent Colors row and checking it shows the row again ([Color Enhancements in Illustrator](https://community.adobe.com/announcements-651/color-enhancements-in-illustrator-816797) puts recent colors in the Color and Swatches panels; [Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html) hides them with Show Recent Colors in the panel menu; a [community thread](https://community.adobe.com/questions-652/swatches-disappear-in-swatches-panel-when-switching-between-documents-in-29-7-1-on-macos-816823) turns it off from the Swatches panel). In VectorCraft it is checked by default, kept between sessions apart from the Color panel's, and applied colors still join the list while the row is hidden (#6617). Tests: `show_recent_colors_hides_and_shows_the_swatches_row` in `crates/ui-egui/src/panels/swatches/tests.rs`. A Recent Colors chip in the Color or Swatches panel drags into the Swatches panel's list to become a swatch of its color, in its color model, as one undo step ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). In VectorCraft a chip dropped on a color group or one of its swatches joins that group, anywhere else in the list it joins the ungrouped swatches at the end, a color that is already a swatch is added again under another name, and dragging a chip does not paint the selected art (`swatch.new`). Tests: `a_recent_color_dragged_onto_the_list_becomes_a_swatch` and `a_recent_color_dragged_from_the_color_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/swatches/tests.rs`. A Cmd/Ctrl-click on the Color panel's spectrum applies Complement and a Cmd/Ctrl+Shift-click applies Invert to the active Fill or Stroke (`paint.complement`, `paint.invert`); with Alt also held, the click recolors the inactive one, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) list them. + The Color panel spectrum grows into the vertical space of a resized panel, with Show Options or Hide Options (#8005); compact auto-fit flyouts and embedded mixers retain their previous height. Regression: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). @@ -2612,6 +2613,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 293a7cf179..213ca723f2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -552,6 +552,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | From 0d4d4399fcae1e666529e90ffed23618e5755804 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:51:22 -0800 Subject: [PATCH 45/50] Check Spelling: text.spelling.change leaves words that already read as the replacement A listed word whose text already equals `to` is now left out of the edit. When every listed word does, the command makes no edit and no undo step, so the redo history is kept, and `changed` is 0. --- crates/engine/src/cmd/spelling.rs | 5 ++++- crates/engine/src/tests/spelling.rs | 21 +++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 03f52d2e19..cd8b4890f2 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Change All", [], None, - "{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count}", + "{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}", has_doc, change_words ), @@ -208,7 +208,10 @@ fn change_words(s: &mut Session, p: &Value) -> Result { } last_end = b; } + // A word that already reads as `to` is left alone, so a list of only those makes no edit. + ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str())); } + by_id.retain(|_, ranges| !ranges.is_empty()); let changed: usize = by_id.values().map(Vec::len).sum(); if changed == 0 { return Ok(json!({ "changed": 0 })); diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index 6142939a33..107c8b0418 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -452,6 +452,27 @@ fn change_all_replaces_every_word_listed_in_one_undo_step() { assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0); } +/// A listed word that already reads as `to` is left alone: with no other word, no edit and no +/// undo step, so the redo history stays. +#[test] +fn change_all_skips_words_that_already_read_as_the_replacement() { + let mut s = session(); + let a = text(&mut s, 50.0, "fixed qzxvw"); + run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"})); + run(&mut s, "edit.undo", json!({})); + let (undo, redo) = { + let h = &s.doc().unwrap().history; + (h.undo.len(), h.redo.len()) + }; + let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]})); + assert_eq!(r["changed"], 0); + let h = &s.doc().unwrap().history; + assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept"); + let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]); + assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1); + assert_eq!(plain(&s, a), "fixed fixed"); +} + /// Each change to the custom dictionary moves its generation on, whether it is saved or not, so /// what Auto Spell Check found before is checked again. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 252e90fbfd..ed7ecd0413 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9305,7 +9305,8 @@ system Hunspell dictionary, and last the public-domain Moby word list built into ones `text.editRange` takes, so `text.editRange {id, start, end, insert}` changes a word as one undo step, and `text.spelling.change {to, words: [{id, start, end}…]}` changes every listed word to `to` as one undo step (Check Spelling's Change All; an error, with nothing changed, when a word's bytes are not in its object's text or two words -overlap). At most +overlap). A listed word that already reads as `to` is left alone; when every one does, the command makes no edit and +no undo step, and `changed` is 0. At most `max` words are listed (1 to 10,000, default 10,000); `more` is `true` when there were more. To get the rest, check again with `from: {id, byte}` set to the last word's `id` and `end`: that check lists the words of that type object that start at `byte` or later, then those of the objects after it, so a type object with more unknown words than one From 2559d09158806ae28d6afe25325e4a6d5a1441ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:51:37 -0800 Subject: [PATCH 46/50] Crop Image: a turned image is cropped at the resolution asked for object.cropImage with ppi draws a turned or skewed image at that ppi even when it is the image's own, instead of at the lower density of the box around it, and a ppi over that whole box makes the new image too. The raster size limit applies only when the crop is drawn or resampled, so a straight cut at the image's own ppi is not refused. The Crop Image tool's Apply sends a turned image's own resolution when no other is set and it is within 1 to 2400 ppi, and crops over the whole box when a resolution is chosen. --- crates/engine/src/cmd/menucmds.rs | 26 +++++++++++---- crates/engine/src/tests/menucmds.rs | 19 +++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/cropimage.rs | 43 +++++++++++++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 5 ++- 6 files changed, 85 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index c3a4f02ba7..ae07e1c860 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -999,10 +999,11 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) } -/// Crop Image's `ppi`: the resolution the cropped image is resampled to, in pixels per point, or `None` to keep -/// the image's own. Refuses a resolution that isn't a positive number or is above what the image allows: its own, -/// or 300 ppi for a linked image, within 1 to 2400 ppi as Rasterize's. -fn crop_resolution(p: &Value, im: &ImageObject) -> Result> { +/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as +/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive +/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as +/// Rasterize's. +fn crop_resolution(p: &Value, im: &ImageObject) -> Result> { const C: &str = "object.cropImage"; let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) }; let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?; @@ -1015,7 +1016,7 @@ fn crop_resolution(p: &Value, im: &ImageObject) -> Result> { return Err(bad(C, format!("ppi can't be more than {max} for this image"))); } // An image whose pixels are not square is resampled on both sides, even at its denser side's resolution. - Ok((!vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)).then_some(ppi / 72.0)) + Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)))) } /// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and @@ -1095,7 +1096,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { return trim_image(s, id, (**im).clone()); } let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; - let target = crop_resolution(p, im)?; + let asked = crop_resolution(p, im)?; + // The resolution the image's pixels are resampled to when they are cut straight. + let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t)); let rect = match p.get("rect").filter(|v| !v.is_null()) { Some(Value::Array(a)) if a.len() == 4 => { let v: Vec = a.iter().filter_map(Value::as_f64).collect(); @@ -1119,7 +1122,10 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { } // A box over the whole image still resamples it to a new resolution. let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6; - if whole && target.is_none() { + // A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image. + let [_, xb, xc, _, _, _] = im.xf.as_coeffs(); + let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9; + if whole && target.is_none() && (asked.is_none() || !turned) { return Err(bad(C, "nothing to crop")); } if let Some(t) = target { @@ -1141,6 +1147,12 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?; return Ok(json!({ "id": id.0, "width": cw, "height": ch })); } + // A drawn crop is made at a resolution asked for even when it is the image's own: the box of a + // turned or skewed image holds fewer of its pixels a point than the image does. + let target = asked.map(|(t, _)| t); + if let Some(t) = target { + check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?; + } // Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more // than the image's own, measured on its pixel grid however it is turned, nor past the size a // drawing may have), and resampled to it. diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 688e1f7804..fb836e9099 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1760,6 +1760,25 @@ fn crop_image_of_a_turned_image_resamples_its_drawing() { assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}"); } +/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower +/// density of the box around it. +#[test] +fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}"); + // Over the whole box around it, its own resolution draws it square to the page. + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap(); + assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}"); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}"); +} + /// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it. #[test] fn crop_image_takes_a_linked_image_up_to_300_ppi() { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8cd7146589..bbbe80f0e1 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -848,7 +848,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 53b5bd86f9..ed67b094d9 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -213,9 +213,18 @@ impl CropImageTool { let max = im.map_or(f64::INFINITY, |im| image_ppi(im).1); // A resolution set before this image was selected is held to this image's limit. let resample = ppi.map(|v| v.min(max)).filter(|v| im.is_none_or(|im| !keeps_resolution(im, *v, 1e-3))); - if !same(r, image) || resample.is_some() { + // A turned or skewed image is drawn to be cropped: the resolution goes with it even when + // it is the image's own, which the PPI field shows until another is chosen (when it is + // one `object.cropImage` takes). A resolution chosen for it crops even over the whole box. + let drawn = im.filter(|im| { + let [_, b, c, _, _, _] = im.xf.as_coeffs(); + b.abs() > 1e-9 || c.abs() > 1e-9 + }); + let own = |im: &ImageObject| Some(image_ppi(im).0).filter(|v| (1.0..=2400.0).contains(v)); + let send = resample.or_else(|| drawn.and_then(|im| ppi.or_else(|| own(im))).map(|v| v.min(max))); + if !same(r, image) || resample.is_some() || (drawn.is_some() && ppi.is_some()) { let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }); - if let Some(v) = resample { + if let Some(v) = send { p["ppi"] = json!(v); } out.push(Action::Exec("object.cropImage".into(), p)); @@ -679,6 +688,36 @@ mod tests { assert_eq!(exec(&enter(&mut t, &cx)), None, "held to its own over the whole image: nothing to do"); } + /// A turned image is drawn to be cropped, so Apply sends its own resolution too, the one the + /// PPI field shows, or the one chosen. + #[test] + fn apply_sends_a_turned_image_s_own_resolution() { + // Turned about the page's corner, it stays within the artboard. + let (mut d, s) = doc_with_image((150.0, 60.0)); + let Some(id) = s.objects.first().copied() else { panic!("an image") }; + if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) { + im.xf = Affine::rotate(0.5) * im.xf; + } + let p = paint(); + let cx = cx(&d, &s, &p); + let ppi = |acts: &[Action]| { + acts.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "object.cropImage" => v.get("ppi").and_then(Value::as_f64), + _ => None, + }) + }; + let mut t = CropImageTool::default(); + t.set_option("rect", &json!([150, 150, 20, 20])); + assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); + t.set_option("rect", &json!([150, 150, 20, 20])); + t.set_option("ppi", &json!(36)); + assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); + // Over the whole box, Apply crops at a resolution chosen, and leaves it alone without one. + t.set_option("ppi", &json!(36)); + assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); + assert!(!enter(&mut t, &cx).iter().any(|a| matches!(a, Action::Exec(..)))); + } + /// A crop that fails leaves the tool chosen (the switch to the Selection tool is not made), so /// the box and the resolution stay for another try; leaving the tool forgets them. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fe7563b096..2d212f4d96 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -849,7 +849,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/docs/mcp.md b/docs/mcp.md index d691dc7948..57d4f96066 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1922,12 +1922,15 @@ missing one does. `object.cropImage {ppi}` sets the cropped image's resolution in pixels per inch: the cut pixels are resampled to it, and the image keeps the size of the crop box. A `rect` over the whole image with a new `ppi` only resamples the image. An image scaled differently across and down is resampled on both sides, so its pixels come out square at `ppi`. +A turned or skewed image is drawn at the `ppi` given, even its own, and over the whole box around it as well; without +`ppi` it is drawn at the density of that box. The Crop Image tool's Apply sends such an image's own resolution when +no other is set, and crops it over the whole box only when a resolution is chosen. The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or 300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with `ppi must be a positive number, not {ppi}`. A resample whose working copies would pass the raster allowance (2 GB, 512 MB in the web app) is refused with `an image of {w} × {h} pixels is too large to resample`, naming the size -of the pixels being resampled. A null `ppi` keeps the image's own, as a missing one does, and `ppi` with +of the pixels being resampled. A null `ppi` is read as a missing one, and `ppi` with `trim` is refused. While the Crop Image tool is chosen, `tool.setOption` sets `ppi` (the resolution Apply sends), `reference` (0 to 8, left to right and top to bottom: the point of the box that the Control bar's X and Y name and that its W and H resize about; 4, the center, by default) and `linked` (W and H keep the box's proportions; false by From 829e399da98fbed74b68889be7bbfbb6fd351954 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:57:10 -0800 Subject: [PATCH 47/50] Crop Image: Apply leaves out a linked image's own resolution above 300 ppi A turned linked image whose own resolution is above the 300 ppi it can be cropped to is cropped as before, without ppi, instead of at 300 ppi. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/cropimage.rs | 15 +++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 2 +- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index bbbe80f0e1..967eaf2337 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -848,7 +848,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ed67b094d9..13691da613 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -220,8 +220,8 @@ impl CropImageTool { let [_, b, c, _, _, _] = im.xf.as_coeffs(); b.abs() > 1e-9 || c.abs() > 1e-9 }); - let own = |im: &ImageObject| Some(image_ppi(im).0).filter(|v| (1.0..=2400.0).contains(v)); - let send = resample.or_else(|| drawn.and_then(|im| ppi.or_else(|| own(im))).map(|v| v.min(max))); + let own = |im: &ImageObject| Some(image_ppi(im).0).filter(|v| (1.0..=2400.0).contains(v) && *v <= max + 1e-6); + let send = resample.or_else(|| drawn.and_then(|im| ppi.map(|v| v.min(max)).or_else(|| own(im)))); if !same(r, image) || resample.is_some() || (drawn.is_some() && ppi.is_some()) { let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }); if let Some(v) = send { @@ -716,6 +716,17 @@ mod tests { t.set_option("ppi", &json!(36)); assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); assert!(!enter(&mut t, &cx).iter().any(|a| matches!(a, Action::Exec(..)))); + // A linked image's own resolution above what it can be cropped to is not sent in its place. + let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") }; + let mut linked = d.clone(); + if let Some(NodeKind::Image(l)) = linked.node_mut(id).map(|n| &mut n.kind) { + l.link = Some("photo.png".into()); + l.xf = im.xf * Affine::scale(0.1); + } + // 0.2 pt a pixel: 360 ppi, above the 300 a linked image is cropped to. + let cx = crate::testutil::cx(&linked, &s, &p); + t.set_option("rect", &json!([105, 128, 4, 4])); + assert_eq!(ppi(&enter(&mut t, &cx)), None); } /// A crop that fails leaves the tool chosen (the switch to the Selection tool is not made), so diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2d212f4d96..bd3ffe009f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -849,7 +849,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 57d4f96066..c6fd8fb0e4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1924,7 +1924,7 @@ and the image keeps the size of the crop box. A `rect` over the whole image with An image scaled differently across and down is resampled on both sides, so its pixels come out square at `ppi`. A turned or skewed image is drawn at the `ppi` given, even its own, and over the whole box around it as well; without `ppi` it is drawn at the density of that box. The Crop Image tool's Apply sends such an image's own resolution when -no other is set, and crops it over the whole box only when a resolution is chosen. +no other is set and the image can be cropped to it, and crops it over the whole box only when a resolution is chosen. The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or 300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with From ebd621d454699a00a43c4029d23bb0bd4108fa8e Mon Sep 17 00:00:00 2001 From: makesomethingshit Date: Mon, 16 Nov 2026 11:05:09 +0900 Subject: [PATCH 48/50] Fix #8005: Record Color spectrum resizing in the parity assessment --- 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 23915b5ce1..1f81421170 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -249,7 +249,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | From 5163f9a9b901c0bcaa6dc1bfd04de834b6c43523 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:11:50 -0800 Subject: [PATCH 49/50] PSD export: a CR LF in an HTML Text slice's type is one line break A type object whose text ends its lines with CR LF no longer writes two
tags for each line ending in its HTML Text slice's cell text. --- crates/render/src/encode/psd.rs | 3 ++- crates/render/src/encode/tests_psd.rs | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 0d568f9e04..480e8d33e4 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -541,10 +541,11 @@ fn background(o: &SliceOptions) -> [u8; 4] { } /// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a -/// line break as `
`. Empty for anything but type. +/// line break as `
` (CR LF is one break). Empty for anything but type. fn html_text(n: &Node) -> String { let NodeKind::Text(t) = &n.kind else { return String::new() }; t.plain_text() + .replace("\r\n", "\n") .split(['\n', '\r', '\u{2029}']) .map(|l| l.replace('&', "&").replace('<', "<").replace('>', ">")) .collect::>() diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index 6875648df3..30e50843f3 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -452,6 +452,20 @@ fn slices_are_cut_to_the_exported_region_in_its_pixels() { assert!(slices_of(&file).is_none()); } +#[test] +fn an_html_text_slice_writes_one_break_for_each_line_ending() { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + use vectorcraft_geom::Point; + let mut d = DocBuilder::new(100.0, 60.0).build(); + let t = TextObject::point(Point::new(10.0, 30.0), "A\r\nB\rC\nD\u{2029}E", CharStyle { size: 12.0, ..CharStyle::default() }); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.extras_mut().slice = Some(Box::new(SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() })); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let res = slices_of(&export(&d, &opts(PsdOptions::default()))).unwrap(); + assert_eq!(res.slices[0].cell_text, "A
B
C
D
E"); +} + #[test] fn slice_ids_count_from_1_and_the_limits_are_errors() { let mut doc = doc(); From fd55592167b033f0ad4edd131bfb3e876a546a78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:16:50 -0800 Subject: [PATCH 50/50] Ellipse: a circle drawn from its center snaps its radius to touch a nearby path With Smart Guides and Snap to Tangent on, an Alt+Shift drag with the Ellipse tool snaps the circle's radius so that the circle touches a nearby path, when the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, including an anchor where a curve's handle lies on the anchor. A circle can touch another circle from outside or from inside. Corners, open path ends and curves around the same center are not offered. The touch point shows the "tangent" label, the radius is measured along the Constrain Angle's axes, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. When an anchor, center or crossing is near the pointer, or the dragged corner snapped onto one, the circle is not resized. An ellipse without Shift is not snapped. Snap to Grid and pixel snapping place the point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. Each pointer move measures at most 256 segments near that radius. --- ROADMAP.md | 1 + crates/tools/src/guides/snap.rs | 17 ++ crates/tools/src/guides/targets.rs | 151 +++++++++++++ crates/tools/src/shape.rs | 50 ++++- crates/tools/src/shape/tests.rs | 350 +++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 568 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 879133f4c7..24ed4abd7b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index d7ee8ecdd8..36bea9b231 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -421,6 +421,23 @@ impl DrawSnap { self.guides.clear(); } + /// Snap to Tangent for a circle drawn around `center`, its radius `r` set by the pointer at `p` + /// through the dragged `corner` (where [`Self::drag`] put it): the radius, within the Smart + /// Guides snapping tolerance of `r`, at which the circle touches nearby art + /// ([`Targets::tangent_radius`]), its guides replacing the last snap's. None, the guides kept, + /// with Smart Guides or Snap to Tangent off, pixels or the grid snapping instead (each read + /// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in + /// reach, or an anchor, center or crossing in reach of `p` or at `corner`. + pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option { + let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None }; + if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid { + return None; + } + let (radius, guides) = t.tangent_radius(center, p, corner, r, cx.tol(*tol))?; + self.guides = guides; + Some(radius) + } + /// Snap `p`, dragged since the press, with the targets the press gathered. pub fn drag(&mut self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> Point { if self.targets.is_none() { diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index e3e6abeef6..7341cf2713 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -107,6 +107,89 @@ pub(super) fn span(r: &Rect, x: bool) -> (f64, f64) { if x { (r.x0, r.x1) } else { (r.y0, r.y1) } } +/// Is `v` square to the direction `d` (both nonzero)? +fn square_to(v: Vec2, d: Vec2) -> bool { + let scale = v.hypot() * d.hypot(); + scale > 1e-18 && v.dot(d).abs() <= 1e-9 * scale +} + +/// Do the directions `a` and `b` (both nonzero) run the same way? +fn parallel(a: Vec2, b: Vec2) -> bool { + let scale = a.hypot() * b.hypot(); + scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale +} + +/// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn +/// with curves does: nearly square to the center all along, and its distance from the center +/// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`]) +/// strays outward from its radius by up to 0.0273%, so an ellipse whose axes differ by less than +/// that cannot be told from one. A circle around the center then lies along the curve. +fn runs_round(seg: &PathSeg, center: Point) -> bool { + const SAMPLES: [f64; 9] = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]; + if matches!(seg, PathSeg::Line(_)) { + return false; + } + let (mut lo, mut hi) = (f64::INFINITY, 0.0_f64); + for t in SAMPLES { + let (v, d) = (seg.eval(t) - center, seg_direction(seg, t)); + if v.dot(d).abs() > 2e-3 * v.hypot() * d.hypot() { + return false; + } + (lo, hi) = (lo.min(v.hypot()), hi.max(v.hypot())); + } + hi - lo <= 3e-4 * hi +} + +/// Whether a segment of `segs` other than the `i`th carries on past the end `at` of the `i`th +/// (its start when `at_start`) in the same direction: it has an end at `at` and runs away from +/// it the way the `i`th runs out through it, so the two join smoothly there rather than overlap. +fn continues_smoothly(segs: &[&PathSeg], i: usize, at: Point, at_start: bool) -> bool { + let Some(seg) = segs.get(i) else { return false }; + let d = end_direction(seg, at_start); + let out = if at_start { -d } else { d }; + let close = 1e-9 * (1.0 + at.x.abs().max(at.y.abs())); + segs.iter().enumerate().filter(|(j, _)| *j != i).any(|(_, s)| { + [(true, s.start()), (false, s.end())].into_iter().any(|(start, end)| { + let d = end_direction(s, start); + end.distance(at) <= close && parallel(if start { d } else { -d }, out) + }) + }) +} + +/// The direction `seg` runs at its start (`at_start`) or its end. Where a curve's handle lies on +/// its anchor the derivative there is zero, so the direction is taken toward the next control +/// point that differs from the anchor, the direction the curve leaves the anchor in. +fn end_direction(seg: &PathSeg, at_start: bool) -> Vec2 { + let mut points: Vec = match seg { + PathSeg::Line(l) => vec![l.p0, l.p1], + PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2], + PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3], + }; + if !at_start { + points.reverse(); + } + let Some((&anchor, rest)) = points.split_first() else { return Vec2::ZERO }; + let away = rest.iter().map(|q| *q - anchor).find(|v| v.hypot2() > 0.0).unwrap_or(Vec2::ZERO); + if at_start { away } else { -away } +} + +/// The points inside `seg` where the line from `center` meets it square, where a circle round +/// `center` touches it, with the segment's direction there. A straight segment has at most one, its +/// foot of the perpendicular. On a curve, besides the sign changes [`touch_params`] finds, a sample +/// where the line is square exactly counts too: a center straight out from a symmetric curve's +/// middle meets it square at t = 0.5. +fn radial_touches(seg: &PathSeg, center: Point) -> Vec<(Point, Vec2)> { + /// The samples checked for an exact square meeting, as [`touch_params`] samples the curve. + const STEPS: u32 = 24; + if let PathSeg::Line(l) = seg { + let d = l.p1 - l.p0; + let t = (center - l.p0).dot(d) / d.hypot2(); + return if t.is_finite() && t > 0.0 && t < 1.0 { vec![(l.p0 + d * t, d)] } else { vec![] }; + } + let sampled = (1..STEPS).map(|i| f64::from(i) / f64::from(STEPS)).filter(|&t| square_to(seg.eval(t) - center, seg_direction(seg, t))); + sampled.chain(touch_params(seg, center, true)).map(|t| (seg.eval(t), seg_direction(seg, t))).collect() +} + /// Along axis `x`, does dragging `handle` move the box's minimum edge (true) or maximum (false)? fn resize_moves_min_edge(handle: Handle, x: bool) -> Option { let (ax, ay) = handle.axes(); @@ -778,6 +861,74 @@ impl Targets { out } + /// Snap to Tangent for a circle drawn around `center` with radius `r`: the radius nearest `r`, + /// within `tol` of it, at which the circle touches a target segment (where the line from + /// `center` meets the path square, at a point the path runs smoothly through), and the guides + /// showing it. None with an anchor, a center or a crossing within `tol` of the pointer `p`, or + /// at `corner`, where the drawn point snapped to: those win as they do for a drawn point. At + /// most 256 segments are measured, the ones nearest `p` when more cross the ring round + /// `center` at radius `r`. + pub(super) fn tangent_radius(&self, center: Point, p: Point, corner: Point, r: f64, tol: f64) -> Option<(f64, Vec)> { + /// How many segments one pointer move measures at most. + const MAX_SEGMENTS: usize = 256; + let finite = [center.x, center.y, p.x, p.y, corner.x, corner.y, r, tol].iter().all(|v| v.is_finite()); + if !self.tangent || !finite || r < 0.0 || tol <= 0.0 { + return None; + } + if self.nearest_point(p, tol).is_some() || self.crossing(p, tol).is_some() { + return None; + } + // The corner snapped onto a point or a crossing: it lies on one, not merely near. + let on = |q: Point| q.distance(corner) <= 1e-9 * (1.0 + corner.x.abs().max(corner.y.abs())); + if self.nearest_point(corner, tol).is_some_and(|(q, _)| on(q)) || self.crossing(corner, tol).is_some_and(on) { + return None; + } + let (lo, hi) = (r - tol, r + tol); + // A segment can touch the circle only if part of its control bounds lies within the ring + // between `lo` and `hi` around the center. + let in_ring = |b: &Rect| { + let near = Point::new(center.x.clamp(b.x0, b.x1), center.y.clamp(b.y0, b.y1)).distance(center); + let far = (center.x - b.x0).abs().max((center.x - b.x1).abs()).hypot((center.y - b.y0).abs().max((center.y - b.y1).abs())); + near <= hi && far >= lo + }; + let mut best: Option<(f64, Point, Vec2)> = None; + let mut offer = |q: Point, d: Vec2| { + let rho = q.distance(center); + if rho > tol && (rho - r).abs() <= tol && best.is_none_or(|(b, ..)| (rho - r).abs() < (b - r).abs()) { + best = Some((rho, q, d)); + } + }; + let mut ring: Vec<&(Rect, PathSeg)> = self.segments.iter().filter(|(b, _)| in_ring(b)).collect(); + if ring.len() > MAX_SEGMENTS { + let from_p = |b: &Rect| Point::new(p.x.clamp(b.x0, b.x1), p.y.clamp(b.y0, b.y1)).distance(p); + ring.select_nth_unstable_by(MAX_SEGMENTS, |a, b| from_p(&a.0).total_cmp(&from_p(&b.0))); + ring.truncate(MAX_SEGMENTS); + } + let near: Vec<&PathSeg> = ring.into_iter().map(|(_, s)| s).collect(); + for (i, seg) in near.iter().enumerate() { + // A circle around the same center lies along such a curve rather than touching it. + if runs_round(seg, center) { + continue; + } + for (q, d) in radial_touches(seg, center) { + offer(q, d); + } + // At an end square to the center the circle touches the path only where the next + // segment carries on in the same direction: at a corner or an open end it meets it. + // That segment ends on the circle too, so it is in the ring; when more than + // MAX_SEGMENTS segments are in the ring and it is not among those kept, the end is not + // offered. + for (at_start, end) in [(true, seg.start()), (false, seg.end())] { + let d = end_direction(seg, at_start); + if square_to(end - center, d) && continues_smoothly(&near, i, end, at_start) { + offer(end, d); + } + } + } + let (rho, q, d) = best?; + Some((rho, self.touch_guides(center, q, false, d, tol))) + } + /// The segment extension nearest `p`, within `tol` of it (and `p` farther than that from the /// end it starts at): that end, its direction and where `p` lands on it. Where `p` is nearer /// the horizontal or the vertical through that end there is none: lining up with it ("align") diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 9eda809c03..0743036fb6 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -15,6 +15,10 @@ //! box's eight handles scales the selection, a press on the selection's centre point (Show Center) //! moves it, and one just outside a corner of its box turns it about that centre, as the Selection //! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477). +//! +//! With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) +//! takes the radius at which it touches a nearby path whenever its radius comes within the +//! snapping tolerance of it ([`DrawSnap::circle_radius`]). use serde_json::{Value, json}; use vectorcraft_doc::OrientedBox; @@ -92,6 +96,10 @@ pub struct ShapeTool { pub star_ratio: f64, /// The star's inner radius held while Ctrl/Cmd is down in a drag. inner: Option, + /// Where the last drag put the dragged corner of a circle drawn from its center, from the + /// center, when Snap to Tangent sized it ([`Self::tangent_circle`]); none when the pointer + /// sized it. Space moving the circle moves the corner it was drawn with there and clears it. + tangent_corner: Option, /// Line Segment Tool Options: the length and angle (degrees) a click's dialog opens with, and /// Fill Line (new lines take the current fill). pub line_length: f64, @@ -153,6 +161,7 @@ impl ShapeTool { corner_radius: 12.0, star_ratio: 0.5, inner: None, + tangent_corner: None, snap: DrawSnap::default(), line_length: 100.0, line_angle: 0.0, @@ -418,6 +427,27 @@ impl ShapeTool { } } + /// Snap to Tangent for a circle drawn from its center `s` (the Ellipse tool with Alt and + /// Shift): the dragged corner `p` moved toward or away from `s` so that the circle touches a + /// nearby path, when its radius is within the snapping tolerance of a touching one + /// ([`DrawSnap::circle_radius`]); `raw` is the pointer before snapping. The radius is measured + /// along the Constrain Angle's axes, as the drawn box is ([`turned_box`]). None for any other + /// shape or modifiers, or with `p` on `s`. + fn tangent_circle(&mut self, cx: &ToolContext, s: Point, raw: Point, p: Point, m: Mods) -> Option { + if self.id != "ellipse" || !(m.alt && m.shift) || m.space { + return None; + } + let axes = vectorcraft_geom::constrain_axes(cx.constrain_angle).unwrap_or(Affine::IDENTITY); + let back = axes.inverse(); + let (c, d) = (back * s, back * p - back * s); + let r = d.x.abs().max(d.y.abs()); + if r.is_nan() || r <= 0.0 { + return None; + } + let radius = self.snap.circle_radius(cx, s, raw, p, r)?; + Some(axes * (c + d * (radius / r))) + } + /// The command for a drag from `start` to `p` (snapped: a line's end already keeps Shift's /// angle). pub fn command(&self, start: Point, p: Point, m: Mods) -> (String, Value) { @@ -560,6 +590,7 @@ impl Tool for ShapeTool { } PointerKind::Drag => { let Some(mut s) = self.start else { return vec![] }; + let raw = ev.pos; let pos = self.snap.drag(cx, ev.pos, self.leave(cx, s, ev.mods).as_ref()); let ev = &PointerEvent { pos, ..*ev }; // The inner radius of the star the last drag showed, with the ratio it drew with: @@ -567,15 +598,28 @@ impl Tool for ShapeTool { // first arrives with the next position. let ratio = if self.mods.alt { straight_ratio(self.points).unwrap_or(self.star_ratio) } else { self.star_ratio }; let shown = (self.last - s).hypot() * ratio; + // Space moves a circle Snap to Tangent sized from the corner it was drawn with, so + // it keeps that size while it moves and after Space is let go. + if ev.mods.space + && self.began + && let Some(d) = self.tangent_corner.take() + { + self.last = s + d; + } space_moves(&mut s, &mut self.last, ev, self.began); self.start = Some(s); self.mods = ev.mods; if self.id == "star" { self.hold_inner(shown, s, ev.pos, ev.mods); } + // A circle from its center takes a radius that touches a nearby path. Whether the + // drag has begun is judged before that snap. + let dragged = ev.pos; + self.tangent_corner = self.tangent_circle(cx, s, raw, ev.pos, ev.mods).map(|q| q - s); + let ev = &PointerEvent { pos: self.tangent_corner.map_or(ev.pos, |d| s + d), ..*ev }; let mut out = vec![]; if !self.began { - if ev.pos.distance(s) < cx.tol(2.0) { + if dragged.distance(s) < cx.tol(2.0) { return out; } self.began = true; @@ -733,7 +777,9 @@ impl Tool for ShapeTool { let (w, h) = match self.id { "polygon" => ((self.last - s).x.abs(), (self.last - s).y.abs()), _ => { - let (r, _) = turned_box(s, self.last, self.mods, cx.constrain_angle); + // The corner Snap to Tangent moved a circle's to, as the preview draws it. + let corner = self.tangent_corner.map_or(self.last, |d| s + d); + let (r, _) = turned_box(s, corner, self.mods, cx.constrain_angle); (r.width(), r.height()) } }; diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index c76eef404e..4e0ee1d1dc 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -196,6 +196,356 @@ fn shift_square_alt_center() { assert_eq!(v, json!({"x": -10.0, "y": -10.0, "width": 20.0, "height": 20.0})); } +/// A 500 × 500 document holding `paths`. +fn doc_holding_paths(paths: impl IntoIterator) -> vectorcraft_doc::Document { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + for (i, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), i, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + d +} + +/// The box of the last preview of a drag: x, y, width, height. +fn previewed_box(a: &[Action]) -> [f64; 4] { + let Some(Action::Preview(_, v)) = a.last() else { panic!("no preview: {a:?}") }; + ["x", "y", "width", "height"].map(|k| v[k].as_f64().unwrap_or(f64::NAN)) +} + +/// An Alt+Shift drag with the Ellipse tool from `center` to `to`: the circle's box as previewed, +/// and the overlays it shows. +fn circle_drag(c: &ToolContext, center: Point, to: Point) -> ([f64; 4], Vec) { + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(both)); + let a = t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both)); + (previewed_box(&a), t.overlays(c)) +} + +fn tangent_label_at(o: &[Overlay], at: Point, within: f64) -> bool { + o.iter().any(|o| matches!(o, Overlay::Label { text, p, .. } if text == "tangent" && p.distance(at) <= within)) +} + +/// Snap to Tangent: a circle drawn from its center takes the radius at which it touches a nearby +/// straight path, with the "tangent" label at the touch point, also when the touch point is the +/// middle of the segment; the size label gives the circle as drawn. +#[test] +fn a_circle_from_its_center_snaps_its_radius_to_touch_a_line() { + // The line's ends and middle line up with none of the corners below. + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) }; + // The pointer makes the radius 98; the line is 100 below the center. + let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(203.0, 102.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.size_label(200.0, 200.0))), "{o:?}"); + // From the other side of the touching radius too (102). + let (b, _) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(205.0, 98.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + // Space moves the snapped circle and keeps its size. + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(both)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 203.0, 102.0).with_mods(both)); + // Space pressed with the pointer still moves the circle by no more than the snap moved its + // corner. + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 203.0, 102.0).with_mods(Mods { space: true, ..both })); + let b = previewed_box(&a); + assert!(b[2] == 200.0 && b[3] == 200.0 && (b[0] - 100.0).abs() <= 4.0 && (b[1] - 100.0).abs() <= 4.0, "{b:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 253.0, 152.0).with_mods(Mods { space: true, ..both })); + let b = previewed_box(&a); + assert!(b[2] == 200.0 && b[3] == 200.0 && (b[0], b[1]) != (100.0, 100.0), "moved, same size: {b:?}"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.size_label(200.0, 200.0)))); + // Letting go of Space where the moved circle no longer touches the line keeps its size, and + // moving on grows it from there. + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 253.0, 152.0).with_mods(both)); + assert_eq!(previewed_box(&a), b, "Space let go"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 243.0, 142.0).with_mods(both)); + let (grown, moved) = (previewed_box(&a), Point::new(b[0] + 100.0, b[1] + 100.0)); + let radius = (243.0 - moved.x).abs().max((142.0 - moved.y).abs()); + assert!(grown[2] == 2.0 * radius && grown[3] == 2.0 * radius && radius > 105.0, "{grown:?} from {moved:?}"); + // Out of reach (radius 90): the pointer sizes it. + let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(203.0, 110.0)); + assert_eq!(b, [110.0, 110.0, 180.0, 180.0]); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); +} + +/// A circle drawn around a center outside another circle touches it from outside at the nearer +/// side and takes it inside at the farther side, the radii those of the closed form (the distance +/// between the centers less or plus the other radius) within the error of the curves that draw a +/// circle. A center inside a circle gives the inscribed circle; its touch point is an anchor of +/// the circle, where two segments join smoothly. A center at the circle's own center gets no snap: +/// every point is square to it. +#[test] +fn a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside() { + use vectorcraft_geom::shapes::ellipse; + // A circle of radius 50 around (350, 300), its center 50√13 from (200, 200). + let d = doc_holding_paths([ellipse(Rect::new(300.0, 250.0, 400.0, 350.0))]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (center, between) = (Point::new(200.0, 200.0), 50.0 * 13f64.sqrt()); + let toward = Vec2::new(150.0, 100.0) / between; + for (radius, pointer) in [(between - 50.0, Vec2::new(20.0, -(between - 52.0))), (between + 50.0, Vec2::new(-20.0, between + 48.0))] { + let (b, o) = circle_drag(&c, center, center + pointer); + assert!((b[2] / 2.0 - radius).abs() < 0.02 && b[2] == b[3], "{b:?}, want radius {radius}"); + assert!(tangent_label_at(&o, center + toward * radius, 0.2), "{o:?}"); + } + // Concentric: no tangent snap. + let (_, o) = circle_drag(&c, Point::new(350.0, 300.0), Point::new(374.0, 252.0)); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); + // Ellipses with radii 10010 and 10000, or 1001 and 1000, around the center are nearly square + // to it all round, but they are not circles: a circle touches each at the ends of its axes. + for (rx, ry) in [(10_010.0, 10_000.0), (1001.0, 1000.0)] { + let d = doc_holding_paths([ellipse(Rect::new(250.0 - rx, 250.0 - ry, 250.0 + rx, 250.0 + ry))]); + let c = cx(&d, &s, &p); + let (_, o) = circle_drag(&c, Point::new(250.0, 250.0), Point::new(280.0, 252.0 - ry)); + assert!(tangent_label_at(&o, Point::new(250.0, 250.0 - ry), 1e-6), "{rx} × {ry}: {o:?}"); + } + let near = |b: [f64; 4], want: [f64; 4]| b.iter().zip(want).all(|(a, w)| (a - w).abs() < 1e-6); + // Inside a circle of radius 150 around (250, 250), 50 from its center: the inscribed circle has + // radius 100. + let d = doc_holding_paths([ellipse(Rect::new(100.0, 100.0, 400.0, 400.0))]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, Point::new(200.0, 250.0), Point::new(203.0, 152.0)); + assert!(near(b, [100.0, 150.0, 200.0, 200.0]), "{b:?}"); + assert!(tangent_label_at(&o, Point::new(100.0, 250.0), 1e-6), "{o:?}"); +} + +/// The touch point can fall inside a curved segment: the radius is the distance to the nearest +/// point of the curve, measured here by sampling the path's own segments densely. +#[test] +fn a_circle_from_its_center_snaps_to_touch_a_curve() { + use vectorcraft_geom::ParamCurve; + let path = vectorcraft_geom::shapes::ellipse(Rect::new(300.0, 100.0, 500.0, 200.0)); + let center = Point::new(250.0, 300.0); + let sp = &path.subpaths[0]; + let (want, at) = (0..sp.segment_count()) + .flat_map(|i| (0..=20_000).map(move |k| (i, f64::from(k) / 20_000.0))) + .map(|(i, t)| sp.segment(i).eval(t)) + .map(|q| (q.distance(center), q)) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .unwrap(); + let d = doc_holding_paths([path]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let r = want - 2.0; + let (b, o) = circle_drag(&c, center, center + Vec2::new(-r * 0.3, r)); + assert!((b[2] / 2.0 - want).abs() < 1e-4 && (b[3] / 2.0 - want).abs() < 1e-4, "radius {} want {want}", b[2] / 2.0); + assert!(tangent_label_at(&o, at, 1e-2), "{at:?} {o:?}"); + // Straight out from a symmetric curve's middle (t = 0.5, (200, 262.5)), 162.5 from (200, 100). + let mut bump = vectorcraft_geom::BezPath::new(); + bump.move_to((100.0, 300.0)); + bump.curve_to((150.0, 250.0), (250.0, 250.0), (300.0, 300.0)); + let d = doc_holding_paths([vectorcraft_geom::PathData::from_bezpath(&bump)]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, Point::new(200.0, 100.0), Point::new(40.0, 40.0)); + assert!((b[2] - 325.0).abs() < 1e-9 && (b[3] - 325.0).abs() < 1e-9, "{b:?}"); + assert!(tangent_label_at(&o, Point::new(200.0, 262.5), 1e-9), "{o:?}"); +} + +/// The snap is Snap to Tangent's, under Smart Guides: off, the pointer sizes the circle. An +/// ellipse (no Shift) and a box drawn from a corner (no Alt) do not snap. An open path's end and +/// a corner square to the center are where a circle meets the path rather than touches it, so +/// neither is offered. +#[test] +fn a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch() { + let line = vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0)); + let d = doc_holding_paths([line]); + let (s, p) = (Selection::default(), paint()); + // The pointer makes the radius 98, 2 short of touching the line. + let (center, to) = (Point::new(200.0, 200.0), Point::new(215.0, 102.0)); + for off in [ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }, ToolContext { smart_guides: false, ..cx(&d, &s, &p) }] { + assert_eq!(circle_drag(&off, center, to).0, [102.0, 102.0, 196.0, 196.0]); + } + let c = cx(&d, &s, &p); + assert_eq!(circle_drag(&c, center, to).0, [100.0, 100.0, 200.0, 200.0], "on, it snaps"); + for (mods, want) in + [(Mods { alt: true, ..Mods::default() }, [185.0, 102.0, 30.0, 196.0]), (Mods { shift: true, ..Mods::default() }, [200.0, 102.0, 98.0, 98.0])] + { + let mut t = ShapeTool::new("ellipse"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(mods)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods)); + assert_eq!(previewed_box(&a), want, "{mods:?}"); + } + // The line's left end is square below (60, 200), but it is an open end, also with a second + // line starting there the same way, which overlaps it rather than carrying it on. + assert_eq!(circle_drag(&c, Point::new(60.0, 200.0), Point::new(63.0, 102.0)).0, [-38.0, 102.0, 196.0, 196.0]); + let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1)); + let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((60.0, 300.0), (200.0, 300.0))]); + let c = cx(&d, &s, &p); + assert_eq!(circle_drag(&c, Point::new(60.0, 200.0), Point::new(63.0, 102.0)).0, [-38.0, 102.0, 196.0, 196.0]); + // Two lines end to end in one direction meet smoothly under (200, 200): the circle touches there. + let d = doc_holding_paths([line((60.0, 300.0), (200.0, 300.0)), line((200.0, 300.0), (380.0, 300.0))]); + let c = cx(&d, &s, &p); + assert_eq!(circle_drag(&c, center, to).0, [100.0, 100.0, 200.0, 200.0]); + // A rectangle's corner (200, 200) is 100√2 from (300, 300), diagonal to both its sides. + let (d, _) = doc_with_rect(); + let c = cx(&d, &s, &p); + let r = 100.0 * 2f64.sqrt() - 2.0; + let (b, _) = circle_drag(&c, Point::new(300.0, 300.0), Point::new(300.0 + r, 300.0 + r * 0.5)); + assert!((b[2] - 2.0 * r).abs() < 1e-9, "{b:?}"); +} + +/// An anchor the dragged corner snapped to wins over the tangent radius, as it does for a drawn +/// point. With more segments near the radius than one move measures, the ones nearest the pointer +/// are measured. +#[test] +fn a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer() { + let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1)); + let (s, p) = (Selection::default(), paint()); + let center = Point::new(200.0, 200.0); + // Shift keeps the corner on the diagonal, and it slides onto the anchor (297, 103): radius 97. + let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((297.0, 103.0), (297.0, 40.0))]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0)); + assert_eq!(b, [103.0, 103.0, 194.0, 194.0]); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); + // A corner that only lines up with an anchor near it, (300, 104), still takes the tangent. + let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((300.0, 104.0), (300.0, 40.0))]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}"); + // 300 short segments pointing at the center cross the ring above it, ahead of the line below. + let spokes = (0..300).map(|i| { + let a = (-55.0 + 110.0 * f64::from(i) / 299.0_f64).to_radians(); + let at = |r: f64| (200.0 + r * a.sin(), 200.0 - r * a.cos()); + line(at(95.0), at(105.0)) + }); + let d = doc_holding_paths(spokes.chain([line((60.0, 300.0), (380.0, 300.0))])); + let c = cx(&d, &s, &p); + // The press lines up with a spoke's anchor, so the center moves by less than a point. + let (b, o) = circle_drag(&c, center, Point::new(215.0, 298.0)); + assert!((b[2] - 200.0).abs() < 1e-9 && (b[3] - 200.0).abs() < 1e-9 && (b[1] - 100.0).abs() < 1e-9, "{b:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Label { text, p, .. } if text == "tangent" && (p.y - 300.0).abs() < 1e-9)), "{o:?}"); +} + +/// With a Constrain Angle the radius is measured, and the snapped box rebuilt, along the turned +/// axes: the circle still touches the line. +#[test] +fn a_circle_snapped_to_touch_keeps_to_the_constrain_angle() { + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(0.0, 300.0), Point::new(450.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { constrain_angle: 30.0, ..cx(&d, &s, &p) }; + let axes = vectorcraft_geom::constrain_axes(30.0).unwrap(); + let center = Point::new(200.0, 200.0); + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(both)); + let to = center + (axes * Point::new(-40.0, -97.0)).to_vec2(); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + let (w, h) = (v["width"].as_f64().unwrap(), v["height"].as_f64().unwrap()); + assert!((w - 200.0).abs() < 1e-9 && (h - 200.0).abs() < 1e-9, "{v}"); + assert!((v["rotation"].as_f64().unwrap() + 30.0).abs() < 1e-9, "{v}"); + let mid = Point::new(v["x"].as_f64().unwrap() + w / 2.0, v["y"].as_f64().unwrap() + h / 2.0); + assert!(mid.distance(center) < 1e-9, "centered on the press: {mid:?}"); + // Space pressed with the pointer still keeps the size and moves the circle by no more than + // the snap moved its corner. + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { space: true, ..both })); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + let (w, h) = (v["width"].as_f64().unwrap(), v["height"].as_f64().unwrap()); + assert!((w - 200.0).abs() < 1e-9 && (h - 200.0).abs() < 1e-9, "{v}"); + let mid = Point::new(v["x"].as_f64().unwrap() + w / 2.0, v["y"].as_f64().unwrap() + h / 2.0); + assert!(mid.distance(center) <= 4.0, "{mid:?}"); +} + +/// Snap to Grid and pixel snapping place the drawn point instead of the tangent snap, also when +/// one is turned on while the circle is dragged out. Snap to Tangent turned off while dragging +/// stops the snap. +#[test] +fn a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels() { + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let on = cx(&d, &s, &p); + let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) }; + let pixels = ToolContext { snap_to_pixel: true, pixel_snap: crate::PixelSnap { drawing: true, ..on.pixel_snap }, ..cx(&d, &s, &p) }; + let no_tangent = ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }; + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let drag = |press: &ToolContext, moved: &ToolContext, to: Point| { + let mut t = ShapeTool::new("ellipse"); + t.pointer(press, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(both)); + let a = t.pointer(moved, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both)); + (previewed_box(&a), t.overlays(moved)) + }; + let tangent = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")); + // The pointer makes the radius 98: the snap would make it 100. + let to = Point::new(203.0, 102.0); + assert_eq!(drag(&on, &on, to).0, [100.0, 100.0, 200.0, 200.0], "the snap applies"); + // Pixels round (203.2, 102.2) to (203, 102): radius 98. + let to = Point::new(203.2, 102.2); + for (press, moved) in [(&pixels, &pixels), (&on, &pixels)] { + let (b, o) = drag(press, moved, to); + assert_eq!(b, [102.0, 102.0, 196.0, 196.0]); + assert!(!tangent(&o), "{o:?}"); + } + // The grid (every 9 points) puts the corner on (207, 99): radius 101 from (200, 200), or 99 + // from (198, 198), where the grid puts a press made with it on. + for (press, moved, want) in [(&grid, &grid, [99.0, 99.0, 198.0, 198.0]), (&on, &grid, [99.0, 99.0, 202.0, 202.0])] { + let (b, o) = drag(press, moved, to); + assert_eq!(b, want); + assert!(!tangent(&o), "{o:?}"); + } + let (b, o) = drag(&on, &no_tangent, Point::new(203.0, 102.0)); + assert_eq!(b, [102.0, 102.0, 196.0, 196.0]); + assert!(!tangent(&o), "{o:?}"); +} + +/// A press and a small jitter is a click, not a drag, even when the tangent snap would size the +/// circle at the jittered pointer large enough to begin a drag. +#[test] +fn a_jittered_alt_shift_press_beside_a_path_is_a_click() { + // With a Constrain Angle, Shift does not hold the corner on the page's diagonal, which would + // take it onto the line. + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { constrain_angle: 30.0, ..cx(&d, &s, &p) }; + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + // 5.5 above the line, beyond the snapping tolerance of 4. The jitter of 1.9 makes the radius + // 1.9 cos 30°, about 1.65, within 4 of the touching radius 5.5. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 294.5).with_mods(both)); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 201.9, 294.5).with_mods(both)), vec![]); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 201.9, 294.5).with_mods(both)); + assert!(!a.contains(&Action::Commit), "{a:?}"); +} + +/// An anchor or a crossing within the snapping tolerance of the pointer takes the point, and the +/// circle is not sized to touch the line. +#[test] +fn a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer() { + let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1)); + let (s, p) = (Selection::default(), paint()); + let center = Point::new(200.0, 200.0); + let base = line((60.0, 300.0), (380.0, 300.0)); + // An anchor at (205, 104), and two lines crossing there. + for extra in [vec![line((205.0, 104.0), (260.0, 40.0))], vec![line((185.0, 84.0), (225.0, 124.0)), line((185.0, 124.0), (225.0, 84.0))]] { + let d = doc_holding_paths(std::iter::once(base.clone()).chain(extra)); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0)); + assert!(b[2] != 200.0, "{b:?}"); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); + } +} + +/// A path whose anchor below the center joins two straight curves with their handles drawn back +/// onto that anchor runs smoothly through it: the circle touches it there. +#[test] +fn a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles() { + let mut run = vectorcraft_geom::BezPath::new(); + run.move_to((60.0, 300.0)); + run.curve_to((100.0, 300.0), (200.0, 300.0), (200.0, 300.0)); + run.curve_to((200.0, 300.0), (300.0, 300.0), (380.0, 300.0)); + let d = doc_holding_paths([vectorcraft_geom::PathData::from_bezpath(&run)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(215.0, 102.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}"); +} + /// General › Constrain Angle: a Shift-drag squares along the turned axes, and the shape turns /// by the angle about its centre. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7ab675f44e..1921a1aba0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -612,6 +612,7 @@ since 2026-10-01. **Drawing tools — Polygon and Star counts:** The existing canvas placement dialog reads the stored count and saves it only after successful placement. `polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs` covers both tools, repeated drags, tool switching, reopening and Cancel. Counts remain session tool options. Existing click and toolbar gestures are retained; no score or hour change. **Drawing tools, Star inner radius held with Ctrl/Cmd:** While a star is dragged out, Ctrl/Cmd keeps the inner radius the star showed when the key went down, also when the key is pressed with the pointer still. `a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt` and `a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down` cover it, with Alt's straight shoulders and a drag canceled with Escape. +**Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it.