From 12e702c676a9988771b51c6cf077d4d1f7ac3ae7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:26:18 -0800 Subject: [PATCH 01/21] i18n: drop SVG filter rows that main already has Main added a "give one element" message row to the cs, fr, ko, pl, uk, zh-hans and zh-hant catalogs, so each catalog held it twice. The Gujarati "Attributes" label now differs from "Properties". --- crates/ui-egui/src/i18n/cs.tsv | 1 - crates/ui-egui/src/i18n/fr.tsv | 1 - crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 1 - crates/ui-egui/src/i18n/pl.tsv | 1 - crates/ui-egui/src/i18n/uk.tsv | 1 - crates/ui-egui/src/i18n/zh-hans.tsv | 1 - crates/ui-egui/src/i18n/zh-hant.tsv | 1 - 8 files changed, 1 insertion(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f5855cd863..1f8d3d9ac4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5992,7 +5992,6 @@ mark-style Japanese Japonské @msg a 3D effect on a group's fill or stroke draws nothing 3D efekt na výplni nebo tahu skupiny nic nekreslí @msg a 3D effect on a group's fill or stroke draws nothing to export 3D efekt na výplni nebo tahu skupiny nekreslí nic k exportu @msg The 3D object is too complex to export 3D objekt je pro export příliš složitý -@msg give one element zadejte jeden prvek @msg the element needs an id, the filter's name prvek potřebuje id, název filtru @msg an SVG filter's id is at most {MAX_NAME} characters id filtru SVG má nejvýše {MAX_NAME} znaků @msg <{_1}> isn't an element of an SVG filter <{_1}> není prvkem filtru SVG diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 71d66e82c7..f125fb5792 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5560,7 +5560,6 @@ lighting Light Lumière @msg a 3D effect on a group's fill or stroke draws nothing un effet 3D sur le fond ou le contour d'un groupe ne dessine rien @msg a 3D effect on a group's fill or stroke draws nothing to export un effet 3D sur le fond ou le contour d'un groupe ne dessine rien à exporter @msg The 3D object is too complex to export L'objet 3D est trop complexe pour être exporté -@msg give one element indiquez un seul élément @msg the element needs an id, the filter's name l’élément doit avoir un id, le nom du filtre @msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG compte au plus {MAX_NAME} caractères @msg <{_1}> isn't an element of an SVG filter <{_1}> n’est pas un élément de filtre SVG diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..5ea47ab195 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -329,7 +329,7 @@ Attach Objects on Path પાથ પર ઑબ્જેક્ટ જોડો Attach to Active Plane સક્રિય સમતલ પર જોડો Attribute: ગુણધર્મ: - Attributes ગુણધર્મો + Attributes એટ્રિબ્યુટ્સ Author Title: લેખકનું શીર્ષક: Author: લેખક: Auto ઑટો diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 02b6b048a9..0a255943f0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5569,7 +5569,6 @@ lighting Light 광원 @msg a 3D effect on a group's fill or stroke draws nothing 그룹의 칠이나 획에 있는 3D 효과는 아무것도 그리지 않습니다 @msg a 3D effect on a group's fill or stroke draws nothing to export 그룹의 칠이나 획에 있는 3D 효과는 내보낼 것을 그리지 않습니다 @msg The 3D object is too complex to export 3D 개체가 너무 복잡하여 내보낼 수 없습니다 -@msg give one element 요소를 하나 지정하세요 @msg the element needs an id, the filter's name 요소에는 필터 이름인 id가 필요합니다 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 필터의 id는 최대 {MAX_NAME}자입니다 @msg <{_1}> isn't an element of an SVG filter <{_1}>은(는) SVG 필터의 요소가 아닙니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6cc084d852..869233f3be 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5823,7 +5823,6 @@ mark-style Japanese Japońskie @msg a 3D effect on a group's fill or stroke draws nothing efekt 3D na wypełnieniu lub obrysie grupy niczego nie rysuje @msg a 3D effect on a group's fill or stroke draws nothing to export efekt 3D na wypełnieniu lub obrysie grupy nie rysuje niczego do eksportu @msg The 3D object is too complex to export Obiekt 3D jest zbyt złożony, aby go wyeksportować -@msg give one element podaj jeden element @msg the element needs an id, the filter's name element wymaga id, czyli nazwy filtra @msg an SVG filter's id is at most {MAX_NAME} characters id filtra SVG ma najwyżej {MAX_NAME} znaków @msg <{_1}> isn't an element of an SVG filter <{_1}> nie jest elementem filtra SVG diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9690c1da98..c906e9e532 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5588,7 +5588,6 @@ lighting Light Світло @msg a 3D effect on a group's fill or stroke draws nothing 3D-ефект на заливці або обведенні групи нічого не малює @msg a 3D effect on a group's fill or stroke draws nothing to export 3D-ефект на заливці або обведенні групи не малює нічого для експорту @msg The 3D object is too complex to export 3D-об’єкт надто складний для експорту -@msg give one element укажіть один елемент @msg the element needs an id, the filter's name елементу потрібен id, назва фільтра @msg an SVG filter's id is at most {MAX_NAME} characters id фільтра SVG містить не більше {MAX_NAME} символів @msg <{_1}> isn't an element of an SVG filter <{_1}> не є елементом фільтра SVG diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 72db56716e..f4e00afea2 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5862,7 +5862,6 @@ lighting Light 光源 @msg a 3D effect on a group's fill or stroke draws nothing 编组填色或描边上的 3D 效果不绘制任何内容 @msg a 3D effect on a group's fill or stroke draws nothing to export 编组填色或描边上的 3D 效果没有可导出的内容 @msg The 3D object is too complex to export 3D 对象过于复杂,无法导出 -@msg give one element 请提供一个 元素 @msg the element needs an id, the filter's name 元素需要 id,即滤镜的名称 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 滤镜的 id 最多 {MAX_NAME} 个字符 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 滤镜的元素 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bd549b2ee5..4a1761f4df 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5697,7 +5697,6 @@ lighting Light 光源 @msg a 3D effect on a group's fill or stroke draws nothing 群組填色或筆畫上的 3D 效果不會繪製任何內容 @msg a 3D effect on a group's fill or stroke draws nothing to export 群組填色或筆畫上的 3D 效果沒有可匯出的內容 @msg The 3D object is too complex to export 3D 物件過於複雜,無法匯出 -@msg give one element 請提供一個 元素 @msg the element needs an id, the filter's name 元素需要 id,也就是濾鏡的名稱 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 濾鏡的 id 最多 {MAX_NAME} 個字元 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 濾鏡的元素 From 38aaab3a832345a83c0afffa6f4ef15c1ab6e30b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:47:46 -0800 Subject: [PATCH 02/21] i18n: drop the Dutch SVG filter row that main already has --- crates/ui-egui/src/i18n/nl.tsv | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0b05fcaaa9..3cdac52058 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7751,7 +7751,6 @@ mark-style Japanese Japans @msg a 3D effect on a group's fill or stroke draws nothing een 3D-effect op de vulling of contour van een groep tekent niets @msg a 3D effect on a group's fill or stroke draws nothing to export een 3D-effect op de vulling of contour van een groep tekent niets om te exporteren @msg The 3D object is too complex to export Het 3D-object is te complex om te exporteren -@msg give one element geef één -element op @msg the element needs an id, the filter's name het -element heeft een id nodig, de naam van het filter @msg an SVG filter's id is at most {MAX_NAME} characters de id van een SVG-filter is hoogstens {MAX_NAME} tekens lang @msg <{_1}> isn't an element of an SVG filter <{_1}> is geen element van een SVG-filter From bf6e0f835d991eb40ad4d97ea2dc735ec55b6630 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:58:50 -0800 Subject: [PATCH 03/21] i18n: drop the Hungarian and Japanese SVG filter rows that main already has main added `give one element` to hu and ja, so each catalog held the row twice and bundled_catalogs_are_consistent failed. The rows from main stay. --- crates/ui-egui/src/i18n/hu.tsv | 1 - crates/ui-egui/src/i18n/ja.tsv | 1 - 2 files changed, 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9b9fc2a050..6dda8381ea 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5980,7 +5980,6 @@ imageTrace Outline Körvonal @msg a 3D effect on a group's fill or stroke draws nothing a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmit @msg a 3D effect on a group's fill or stroke draws nothing to export a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmi exportálhatót @msg The 3D object is too complex to export A 3D objektum túl összetett az exportáláshoz -@msg give one element adjon meg egy elemet @msg the element needs an id, the filter's name a elemnek id kell, a szűrő neve @msg an SVG filter's id is at most {MAX_NAME} characters egy SVG-szűrő id-je legfeljebb {MAX_NAME} karakter @msg <{_1}> isn't an element of an SVG filter a(z) <{_1}> nem SVG-szűrő eleme diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1a05676307..90adbf8f21 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5655,7 +5655,6 @@ lighting Light ライト @msg a 3D effect on a group's fill or stroke draws nothing グループの塗りまたは線にある 3D 効果は何も描画しません @msg a 3D effect on a group's fill or stroke draws nothing to export グループの塗りまたは線にある 3D 効果には書き出せる描画がありません @msg The 3D object is too complex to export 3D オブジェクトが複雑すぎるため書き出せません -@msg give one element 要素を 1 つ指定してください @msg the element needs an id, the filter's name 要素には id (フィルターの名前) が必要です @msg an SVG filter's id is at most {MAX_NAME} characters SVG フィルターの id は {MAX_NAME} 文字までです @msg <{_1}> isn't an element of an SVG filter <{_1}> は SVG フィルターの要素ではありません From 3cfe025ad09f4914a81450ec6de0e9f767b01a8f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:02:07 -0800 Subject: [PATCH 04/21] i18n: Danish rows for SVG filter refusals --- crates/ui-egui/src/i18n/da.tsv | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b99ae26197..ead5acbe15 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -290,6 +290,25 @@ @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere @msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg give one element angiv ét -element +@msg the element needs an id, the filter's name -elementet skal have et id, filterets navn +@msg an SVG filter's id is at most {MAX_NAME} characters et SVG-filters id er højst {MAX_NAME} tegn +@msg <{_1}> isn't an element of an SVG filter <{_1}> er ikke et element i et SVG-filter +@msg an SVG filter has no event attributes such as {_1} et SVG-filter har ingen hændelsesattributter som {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs et SVG-filters billeder er data:-URL'er i PNG, JPEG, GIF eller WebP +@msg the SVG filter isn't valid XML: {e} SVG-filteret er ikke gyldig XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves for feTurbulence er højst {MAX_OCTAVES} +@msg {what} is at most {max} {what} er højst {max} +@msg feConvolveMatrix's order order for feConvolveMatrix +@msg feMorphology's radius radius for feMorphology +@msg a blur's stdDeviation stdDeviation for en sløring +@msg the SVG filter has no primitives SVG-filteret har ingen filterprimitiver +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives et SVG-filter har højst {MAX_PRIMITIVES} filterprimitiver +@msg the SVG filter is too large once its attributes are written out SVG-filteret er for stort, når dets attributter er skrevet ud +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all et SVG-filters billeder har i alt højst {MAX_IMAGE_PIXELS} pixels +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG-filteret kan ikke tegnes: kontrollér dets filterprimitiver og deres input +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep et SVG-filters elementer er højst indlejret {MAX_DEPTH} niveauer dybt +@msg an SVG filter is at most {_1} KB et SVG-filter er højst {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér) @msg its 3D effect builds no solid dens 3D-effekt danner intet legeme @msg bevel must be none or one of {_1} bevel skal være none eller en af {_1} From 39f41da03e69b8c7ddec93a665144e40aefbe2e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:39:56 -0800 Subject: [PATCH 05/21] i18n: SVG filter refusal rows that main already has are listed once main added the SVG filter refusal rows to the Georgian catalog and `give one element` to the Russian and Turkish catalogs, so after the merge those catalogs held each of these rows twice and `bundled_catalogs_are_consistent` failed. The branch's copies are removed and main's rows are kept. The Georgian rows for the three `{what}` values stay, since main has none. --- crates/ui-egui/src/i18n/ka.tsv | 16 ---------------- crates/ui-egui/src/i18n/ru.tsv | 1 - crates/ui-egui/src/i18n/tr.tsv | 1 - 3 files changed, 18 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 26106e8485..1c4f2a9c54 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7483,25 +7483,9 @@ font-technology Variable ცვლადი @msg a 3D effect on a group's fill or stroke draws nothing ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი არაფერს ხატავს @msg a 3D effect on a group's fill or stroke draws nothing to export ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი ექსპორტისთვის არაფერს ხატავს @msg The 3D object is too complex to export 3D ობიექტი ზედმეტად რთულია ექსპორტისთვის -@msg give one element მიუთითეთ ერთი ელემენტი -@msg the element needs an id, the filter's name ელემენტს სჭირდება id, ფილტრის სახელი -@msg an SVG filter's id is at most {MAX_NAME} characters SVG ფილტრის id მაქსიმუმ {MAX_NAME} სიმბოლოა -@msg <{_1}> isn't an element of an SVG filter <{_1}> არ არის SVG ფილტრის ელემენტი -@msg an SVG filter has no event attributes such as {_1} SVG ფილტრს არ აქვს მოვლენის ატრიბუტები, როგორიცაა {_1} -@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG ფილტრის გამოსახულებები PNG, JPEG, GIF ან WebP data: URL-ებია -@msg the SVG filter isn't valid XML: {e} SVG ფილტრი არ არის სწორი XML: {e} -@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence-ის numOctaves მაქსიმუმ {MAX_OCTAVES}-ია -@msg {what} is at most {max} {what}: მაქსიმუმ {max} @msg feConvolveMatrix's order feConvolveMatrix-ის order @msg feMorphology's radius feMorphology-ის radius @msg a blur's stdDeviation დაბინდვის stdDeviation -@msg the SVG filter has no primitives SVG ფილტრს არ აქვს პრიმიტივები -@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG ფილტრს აქვს მაქსიმუმ {MAX_PRIMITIVES} პრიმიტივი -@msg the SVG filter is too large once its attributes are written out SVG ფილტრი ზედმეტად დიდია მისი ატრიბუტების ჩაწერის შემდეგ -@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG ფილტრის გამოსახულებებს სულ მაქსიმუმ {MAX_IMAGE_PIXELS} პიქსელი აქვს -@msg the SVG filter can't be drawn: check its primitives and their inputs SVG ფილტრის დახატვა შეუძლებელია: შეამოწმეთ მისი პრიმიტივები და მათი შემავალი მონაცემები -@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG ფილტრის ელემენტები მაქსიმუმ {MAX_DEPTH} დონის სიღრმეზეა ჩადგმული -@msg an SVG filter is at most {_1} KB SVG ფილტრი მაქსიმუმ {_1} KB-ია @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ობიექტს არ აქვს 3D ეფექტი (ამოწევა და წაკვეთა, ბრუნვა, გაბერვა ან შემობრუნება) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` უნდა იყოს ობიექტი, რომელიც შეიცავს მხოლოდ `mode`-ს, მნიშვნელობით shaded ან wireframe @msg its 3D effect builds no solid მისი 3D ეფექტი სხეულს არ ქმნის diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 26048918cf..f9a9cf9eb2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5736,7 +5736,6 @@ lighting Light Свет @msg a 3D effect on a group's fill or stroke draws nothing 3D-эффект на заливке или обводке группы ничего не рисует @msg a 3D effect on a group's fill or stroke draws nothing to export 3D-эффект на заливке или обводке группы не рисует ничего для экспорта @msg The 3D object is too complex to export 3D-объект слишком сложен для экспорта -@msg give one element укажите один элемент @msg the element needs an id, the filter's name элементу нужен id, имя фильтра @msg an SVG filter's id is at most {MAX_NAME} characters id фильтра SVG содержит не более {MAX_NAME} символов @msg <{_1}> isn't an element of an SVG filter <{_1}> не является элементом фильтра SVG diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cd9f7bf490..92fa4d3e22 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5443,7 +5443,6 @@ lighting Light Işık @msg a 3D effect on a group's fill or stroke draws nothing bir grubun dolgusundaki veya konturundaki 3 boyutlu efekt hiçbir şey çizmez @msg a 3D effect on a group's fill or stroke draws nothing to export bir grubun dolgusundaki veya konturundaki 3 boyutlu efekt dışa aktarılacak hiçbir şey çizmez @msg The 3D object is too complex to export 3 boyutlu nesne dışa aktarmak için çok karmaşık -@msg give one element bir öğesi ver @msg the element needs an id, the filter's name öğesinin, filtrenin adı olan bir id değeri olmalıdır @msg an SVG filter's id is at most {MAX_NAME} characters bir SVG filtresinin id değeri en fazla {MAX_NAME} karakterdir @msg <{_1}> isn't an element of an SVG filter <{_1}> bir SVG filtresi öğesi değildir From d436d38fb17fb3ee5a443b1b75d10a35eadb8ff5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:54:49 -0800 Subject: [PATCH 06/21] Effects: each copy of a group's or layer's Transform effect carries the raster effects listed before it A group's or layer's own Drop Shadow, glow, blur, Feather or pixel filter listed before its last Transform effect that makes copies now goes with each copy, made of all the copy's members together. Its sizes scale by the copy's mean scale, and a Drop Shadow's offset turns, reflects and scales with the copy. Before, one shadow was drawn around all the copies at the group's own distances. A raster effect listed after the Transform effect still paints once around all the copies, and the members' own raster effects stay as a copying Transform effect leaves them. Each copy is a group holding the members. A clip group's copies each clip, a layer's art stays a layer, and its ruler guides stay once above the copies. Compound shapes, Shaper groups and groups with Pathfinder, 3D, Crop Marks, Vector Halftone, a painting plug-in, a perspective or fills and strokes with geometry effects keep the earlier behavior. The canvas, the object's bounds, baking for export (type in such a group is no longer kept as type under one shadow), export with raster effects as images and Expand Appearance draw the same copies. Expand Appearance gives the copies ids of their own, expanding a copy with a random Transform effect before its ids change so it keeps the canvas's random values. --- crates/effects/src/bake.rs | 10 +- crates/effects/src/group.rs | 56 +++++++++- crates/effects/src/reshape.rs | 90 ++++++++++++++- crates/effects/src/tests/rasterfollow.rs | 135 ++++++++++++++++++++++- crates/engine/src/cmd/effectcmd.rs | 62 ++++++++++- crates/engine/src/tests/objexpand.rs | 130 ++++++++++++++++++++++ crates/engine/src/tests/pdfraster.rs | 39 +++++++ crates/render/src/fx/bounds.rs | 6 +- crates/render/src/tests/objectfx.rs | 40 +++++++ docs/target-app-parity.md | 3 +- 10 files changed, 557 insertions(+), 14 deletions(-) diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 67388c0d72..294c08962a 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -715,7 +715,9 @@ fn moved_type_group(n: &Node) -> Option { /// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live /// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is /// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of -/// them. `None` when no type stays type. +/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster +/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the +/// canvas draws it ([`evaluate_container`]). fn container_keeping_type(d: &Document, n: &Node) -> Option { fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) { if !clipping { @@ -751,7 +753,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { } } } - if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) + || has_pathfinder(n) + || has_own_paint(n) + || crate::reshape::copied_container_raster_at(n).is_some() + { return None; } let fx = geometry_effects(n); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 94c5509938..88f54c2840 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -820,11 +820,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl /// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live /// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and /// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -889,6 +893,56 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let mut m = n.clone(); + let mut guides = vec![]; + take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); + let mut source = m.clone(); + source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec(); + let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { + let mut p = crate::reshape::outlined_members(doc, &source); + { + // The members' raster effects follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut p); + } + p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); + p + }); + // The piece is one copy: the transparency, opacity mask and guides stay on the art. + piece.name = None; + piece.visible = true; + piece.locked = false; + (piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false); + piece.extras_mut().mask = None; + // A layer's copies are groups in it. + if let NodeKind::Layer { children, clip, .. } = &mut piece.kind { + piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip }; + } + let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece); + let copies = art.children().cloned().unwrap_or_default(); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind { + *children = copies; + *clip = false; + } + m.appearance.items.clear(); + m.appearance.contents_index = None; + m.appearance.effects = effects; + if let Some(ch) = m.children_mut() { + ch.extend(guides); + } + m +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c3238199a2..c6278f3e4f 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -147,6 +147,91 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option { (carried && !excluded).then_some(t) } +/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect +/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of +/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes +/// copies, when a visible raster effect that follows a Transform effect is listed before it and +/// every other visible effect before it is a geometry effect or such a raster effect. `None` +/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a +/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints +/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own. +pub(crate) fn copied_container_raster_at(n: &Node) -> Option { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let effects = &n.appearance.effects; + // Checked first: this runs for every group and layer drawn. + if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return None; + } + let t = effects.iter().rposition(|e| { + e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0 + })?; + let before = effects.get(..t)?; + let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)); + let excluded = n.is_compound_shape() + || n.extras().shaper.is_some() + || crate::has_pathfinder(n) + || n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + || crate::has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) + || effects.iter().any(|e| painted_plugin(e).is_some()) + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); + (carried && !excluded).then_some(t) +} + +/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`, +/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster +/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding +/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved, +/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale +/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect +/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as +/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. Returns the art +/// and the raster effects from `t` on, as they ran. +pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node) -> (Node, Vec) { + let rest = n.appearance.effects.get(t..).unwrap_or_default(); + let own = piece.appearance.effects.clone(); + let mut art = Node::group(n.id, vec![Arc::new(piece)]); + if let (Some(e), Some(bounds)) = (rest.first(), art.geometric_bounds()) { + let params = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); + let max = Budget::EFFECTS.at_least(art_cost(&art)); + copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(¶ms)), max); + if let Some(children) = art.children_mut() { + // The original is last, and each copy above it is mapped once more by `m`. + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let mut a = Affine::IDENTITY; + for (k, c) in children.iter_mut().rev().enumerate() { + // Each copy is the piece in a group of its own: the piece takes its place. + if let Some([one]) = c.children().map(Vec::as_slice) { + *c = one.clone(); + } + if k > 0 { + a *= step; + // Scale Strokes & Effects scaled the copy's own effects with it: they follow + // its map from their values on the original instead. + let copy = Arc::make_mut(c); + copy.appearance.effects = own.clone(); + crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY); + } + } + } + } + let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); + let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, false, doc); + let mut ran = n.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); + (art, effects) +} + /// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id, /// else `None`. fn painted_plugin(e: &Effect) -> Option<&str> { @@ -1083,9 +1168,10 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> } /// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect -/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]). +/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]) +/// and for a group or layer whose copies do ([`copied_container_raster_at`]). pub fn outer_effects(n: &Node) -> &[Effect] { - match copied_raster_at(n) { + match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) { Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), None => &n.appearance.effects, } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index 586481d9b5..0dbbe401fc 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -781,7 +781,7 @@ fn a_groups_transform_moves_its_members_shadows() { } /// A group's Transform effect that makes copies or moves at random leaves its members' shadows as -/// they are, as it leaves the shadows listed before it in its own effects. +/// they are. #[test] fn a_groups_copying_transform_leaves_its_members_shadows() { for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] { @@ -792,6 +792,139 @@ fn a_groups_copying_transform_leaves_its_members_shadows() { } } +/// A layer of `members` with `effects` of its own. +fn layer(id: u64, members: Vec, effects: Vec) -> Node { + let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = members.into_iter().map(std::sync::Arc::new).collect(); + } + l.appearance.effects = effects; + l +} + +/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order. +fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> { + art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect() +} + +fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y)) +} + +/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed +/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and +/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and +/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not +/// scaled a second time. A layer's art stays a layer. +#[test] +fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() { + let cases = [ + (json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]), + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + ]; + for (params, want) in cases { + let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect(); + for container in ["group", "layer"] { + let members = vec![square(101, vec![]), square(102, vec![])]; + let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]; + let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) }; + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}"); + let art = crate::evaluate_container(None, &n).unwrap(); + assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}"); + assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects); + let drawn = copy_shadows(&art); + assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}"); + assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none"); + for c in art.children().into_iter().flatten() { + assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}"); + } + let b = baked(n); + assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b)); + } + } +} + +/// A group's copying Transform effect leaves its members' own shadows on each copy as they are, +/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip +/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has +/// Transform Objects off, leaves the group's shadows on the group. +#[test] +fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() { + let g = group( + 110, + vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)], + ); + assert_eq!(crate::outer_effects(&g).len(), 2); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art)); + + let mut clip = square(121, vec![]); + if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]); + if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(!art.clips()); + assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}"); + assert!(close_all(©_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art)); + + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert_eq!(crate::outer_effects(&g).len(), 2, "{params}"); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow"); + } +} + +/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without +/// one, and no shadow is left without its copy. +#[test] +fn a_groups_copies_past_the_budget_each_keep_their_shadow() { + let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + let paths = paths_in(&art); + assert!(paths > 1 && paths < 1001, "{paths}"); + assert_eq!(shadows_in(&art).len(), paths); +} + +/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow. +#[test] +fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() { + let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None }); + let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let ch = art.children().unwrap(); + assert_eq!(ch.len(), 4, "three copies, then the guide"); + assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1); + assert_eq!(shadows_in(&art).len(), 3); +} + +/// A group holding type whose Transform effect only moves its copies, baked for export, gives each +/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type +/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs +/// and the test is skipped. +#[test] +fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { + use vectorcraft_doc::text::{CharStyle, TextObject}; + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); + let b = baked(g); + assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); +} + /// The Transform effects inside a group apply before the group's: a member's own turn of 90° /// applies to its shadow before the group's uneven scale does, for the member's own shadow, its /// fill's shadow, and the shadow of a member of a nested group that has the turn. diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 1f471d84a3..f75dc307b8 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1121,6 +1121,56 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush } } +/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects +/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]): +/// the copies become groups of their own with those effects, and they and what they hold get ids +/// of their own, so they expand as its members do; the raster effects after the Transform effect +/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect +/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does, +/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of +/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there. +/// Returns whether `n` changed; any other object stays as it is. +fn copies_carrying_raster( + d: &mut Document, + n: &mut Node, + (brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]), + kept: &mut Vec, + members: &mut std::collections::HashMap>, + (out, listed): (&mut Vec, &mut bool), +) -> bool { + if !is_container(n) || effects::outer_effects(n).len() == n.appearance.effects.len() { + return false; + } + let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return false }; + let mut seen = std::collections::HashSet::from([n.id]); + for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { + let c = Arc::make_mut(c); + let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip)); + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); + } + fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default()); + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + if let Some(expanded) = expanded { + members.insert(c.id, expanded); + } + } + if !*listed { + out.push((n.id, 0)); + *listed = true; + } + *n = m; + true +} + /// [`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. The objects `skip` lists are not expanded. @@ -1186,15 +1236,17 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } return Some(m); } + // New ids of the copies of objects `skip` lists among the members. + let mut kept = vec![]; + // Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id, + // with what their expansion lists. + let mut members = std::collections::HashMap::new(); + changed |= copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n)); let image = raster_image(d, &n); let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); - // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. - let mut members = std::collections::HashMap::new(); - // New ids of the copies of objects `skip` lists among those members. - let mut kept = vec![]; let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -1206,7 +1258,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art); + members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art)); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 1bac01d48d..ff58dafc35 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -278,6 +278,136 @@ fn each_copys_shadow_expands_as_the_canvas_draws_it() { assert_eq!(diff, 0, "{diff} pixels differ"); } +/// Each copy of a group's Transform effect draws the drop shadow listed before the effect under +/// itself, of both its squares together and scaled with it, and Expand Appearance keeps those +/// shadows: the squares (20..40 together) have their shadow 20 pt to their right, and their copy +/// scaled 200 % and moved 80 pt down (10..50 across, 90..130 down) has its own 40 pt to its right. +/// A copy moved 30 pt right (50..70) lies under the squares' shadow (40..60), which still paints +/// over it once expanded. The expanded art has no effects left, and each object in it an id of its +/// own. +#[test] +fn each_copys_shadow_on_a_group_expands_as_the_canvas_draws_it() { + let cases = [ + (json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}), (80, 110), "the copy's shadow"), + (json!({"moveH": 30, "copies": 1}), (55, 30), "the squares' shadow over the copy"), + ]; + for (params, (x, y), what) in cases { + let mut s = session(); + let mut ids = vec![]; + for x in [20, 30] { + ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 20}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + } + run(&mut s, "select.set", json!({"ids": ids})); + run(&mut s, "object.group", json!({})); + let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": params})); + let before = render(&s); + assert_eq!(before.pixel(x, y), [0, 255, 0, 255], "{params}: {what}"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{params}: {diff} pixels differ"); + let doc = &s.doc().unwrap().doc; + let (mut seen, mut count, mut effects) = (std::collections::HashSet::new(), 0, 0); + for l in &doc.layers { + l.walk(&mut |n| { + seen.insert(n.id); + count += 1; + effects += n.appearance.effects.len(); + }); + } + assert_eq!(seen.len(), count, "{params}: each object has an id of its own"); + assert_eq!(effects, 0, "{params}: no effects are left"); + } +} + +/// A member's random Transform effect takes its seed from the member's id, and the canvas draws +/// every copy of the group with that id: Expand Appearance of a group with a stroke of its own, a +/// shadow and a copying Transform effect gives each copy's symbol instance the same random move, so +/// the copies, 60 pt apart, still draw alike. +#[test] +fn each_copys_random_member_expands_as_the_canvas_draws_it() { + let mut s = session(); + let mut ids = vec![]; + for x in [20, 50] { + ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + } + run(&mut s, "select.set", json!({"ids": [ids[0]]})); + ids[0] = run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [ids[0]]})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveH": 16, "moveV": 16, "random": true}})); + run(&mut s, "select.set", json!({"ids": ids})); + let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [g]})); + run(&mut s, "appearance.addStroke", json!({})); + assert!(node(&s, NodeId(g)).appearance.items.iter().any(|i| i.visible()), "the group has a stroke of its own"); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveV": 60, "copies": 2}})); + // The pixels of each copy's 60 pt band that differ from the first copy's by more than 64. + let unlike = |r: &vectorcraft_render::Rendered| { + let px = |x: usize, y: usize| { + let i = (y * r.width as usize + x) * 4; + r.pixels.get(i..i + 4).map(<[u8]>::to_vec).unwrap_or_default() + }; + let mut n = 0; + for k in [60, 120] { + for y in 0..60 { + for x in 0..r.width as usize { + n += usize::from(px(x, y).iter().zip(px(x, y + k)).any(|(a, b)| a.abs_diff(b) > 64)); + } + } + } + n + }; + let before = render(&s); + assert_eq!(unlike(&before), 0, "the canvas draws the copies alike"); + let art = vectorcraft_render::effects::evaluate_container(Some(&s.doc().unwrap().doc), &node(&s, NodeId(g))).unwrap(); + let mut live = 0; + art.walk(&mut |n| live += n.appearance.effects.iter().filter(|e| e.id == "distort.transform").count()); + assert_eq!(live, 3, "each copy's instance keeps its random effect live"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + assert_eq!(unlike(&after), 0, "the expanded copies draw alike"); + assert!(differing(&before, &after, 64) < 200, "the copies stay where they are drawn"); +} + +/// A member's own Offset Path applies before the copying Transform effect of its group, which has +/// a stroke of its own, whether or not a shadow is listed before that Transform effect: the copy +/// scaled 200 % draws the offset square scaled, with or without a shadow at 0 % opacity. +#[test] +fn a_members_offset_path_applies_before_its_painted_groups_copies() { + let draw = |shadow: bool| { + let mut s = session(); + let mut ids = vec![]; + for x in [20, 40] { + ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 10}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + } + run(&mut s, "select.set", json!({"ids": [ids[0]]})); + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 5}})); + run(&mut s, "select.set", json!({"ids": ids})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({})); + if shadow { + let fx = json!({"x": 10, "y": 0, "blur": 0, "opacity": 0, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": fx})); + } + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}})); + let n = node(&s, g); + assert_eq!(vectorcraft_render::effects::outer_effects(&n).len() < n.appearance.effects.len(), shadow, "each copy carries the shadow"); + render(&s) + }; + let diff = differing(&draw(false), &draw(true), 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + /// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on /// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide. #[test] diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index 1e0a2ecfde..dd7ad9c00d 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -191,6 +191,45 @@ fn shadows_and_glows_keep_their_blend_modes() { assert_eq!(modes, [vectorcraft_color::BlendMode::Multiply, vectorcraft_color::BlendMode::Screen]); } +/// Each copy of a group's Transform effect has its own image of the shadow listed before the +/// effect, under that copy: the squares' shadow (40..60) paints over their copy moved 30 pt right +/// (50..70), as on the canvas, and the copies' objects have ids of their own. +#[test] +fn each_copys_shadow_on_a_group_flattens_under_that_copy() { + let mut d = Document::new(200.0, 200.0); + let members = [20.0, 30.0].map(|x| Arc::new(rect(&mut d, Rect::new(x, 40.0, x + 10.0, 60.0), Color::rgb(1.0, 0.0, 0.0)))); + let mut g = Node::group(d.alloc_id(), members.to_vec()); + g.appearance.effects = vec![ + Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 20.0, "y": 0.0, "blur": 0.0, "opacity": 100.0, "mode": "normal", "color": "#00ff00"}), + visible: true, + }, + Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 1}), visible: true }, + ]; + add(&mut d, g); + let canvas = render(&d); + let flat = crate::flatten_raster_effects(&d).unwrap(); + let back = render(&flat); + let at = |r: &Rendered, x: usize| { + let i = (50 * r.width as usize + x) * 4; + (r.pixels[i], r.pixels[i + 1], r.pixels[i + 2]) + }; + for x in [55, 65, 85] { + let (want, got) = (at(&canvas, x), at(&back, x)); + assert!(want.0.abs_diff(got.0) < 32 && want.1.abs_diff(got.1) < 32 && want.2.abs_diff(got.2) < 32, "x {x}: {want:?} {got:?}"); + } + assert!(at(&back, 55).1 > 200 && at(&back, 55).0 < 60, "the squares' shadow over the copy: {:?}", at(&back, 55)); + let (mut seen, mut count) = (std::collections::HashSet::new(), 0); + for l in &flat.layers { + l.walk(&mut |n| { + seen.insert(n.id); + count += 1; + }); + } + assert_eq!(seen.len(), count, "each object has an id of its own"); +} + #[test] fn pdf_resolution_cap_warns_once_for_original_object_when_appearance_items_split() { let mut d = Document::new(300.0, 300.0); diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index e6400c90af..1ca2de572a 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -780,9 +780,11 @@ pub(crate) fn three_d_art_bounds(symbols: &SymbolBoxes, art: &Node) -> Option Rect { - let o = outset(symbols, &n.appearance.effects, b); + let o = outset(symbols, effects::outer_effects(n), b); b.inflate(o, o) } diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index f93124e1b9..b509d39c08 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1242,3 +1242,43 @@ fn each_copy_of_a_transform_effect_draws_its_own_shadow() { let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap(); assert!(b.x1 >= 80.0 - 1e-9, "{b:?}"); } + +/// Each copy of a group's or layer's Transform effect draws the drop shadow listed before the +/// effect under itself, of all its members together and scaled with it: two red squares side by +/// side (10..30 together) have one green shadow 20 pt to their right, and their copy scaled 200 % +/// and moved 60 pt down (0..40 across, 60..100 down) has its own 40 pt to its right. The bounds +/// reach as far as the copy's shadow, and no further. +#[test] +fn each_copy_of_a_groups_or_layers_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1})); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + for layer in [false, true] { + let mut d = Document::new(100.0, 100.0); + let members: Vec> = [Rect::new(10.0, 10.0, 20.0, 30.0), Rect::new(20.0, 10.0, 30.0, 30.0)] + .into_iter() + .map(|r| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), red.clone()))) + .collect(); + if layer { + let l = Arc::make_mut(&mut d.layers[0]); + if let Some(ch) = l.children_mut() { + *ch = members; + } + l.appearance.effects = vec![shadow.clone(), copies.clone()]; + } else { + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = vec![shadow.clone(), copies.clone()]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + } + let img = render(&d); + assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "layer {layer}: the squares"); + assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "layer {layer}: the squares' shadow"); + assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "layer {layer}: the copy"); + assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "layer {layer}: the copy's shadow, 40 pt to its right"); + assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "layer {layer}: past the copy's shadow"); + let n = if layer { d.layers[0].clone() } else { d.layers[0].children().unwrap()[0].clone() }; + let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), &n).unwrap(); + assert!((b.x1 - 80.0).abs() < 1e-9, "layer {layer}: {b:?}"); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 21b0074bbd..574f51c238 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -634,7 +634,8 @@ since 2026-10-01. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged. -- **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of type, images, symbol instances and groups, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged. +- **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of type, images and symbol instances, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged. +- **Raster effects before a group's or layer's Transform effect that makes copies:** groups and layers can carry effects of their own ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/vector-and-raster-effects.html)), and the rule above for paths now covers them as VectorCraft's own rule. Each copy of a group's or layer's own last Transform effect that makes copies carries the Drop Shadow, glow, blur, Feather or pixel filter listed before that effect, made of all the copy's members together, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies, and the members' own raster effects in each copy stay as a copying Transform effect leaves them. Before, one shadow was drawn around all the copies at the group's own distances. A clip group's copies each clip, and a layer's ruler guides stay once above the copies. The canvas, the bounds, export with raster effects as images and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint`, `tests::rasterfollow::a_groups_copies_past_the_budget_each_keep_their_shadow`, `tests::rasterfollow::a_layers_guides_stay_once_above_copies_that_carry_its_shadow`, `tests::rasterfollow::a_baked_group_with_type_keeps_a_shadow_on_each_copy`; render `objectfx::each_copy_of_a_groups_or_layers_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_on_a_group_expands_as_the_canvas_draws_it`, `objexpand::each_copys_random_member_expands_as_the_canvas_draws_it`, `pdfraster::each_copys_shadow_on_a_group_flattens_under_that_copy`). Not yet: a compound shape, a Shaper group, and a group or layer with a Pathfinder effect, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints what it returns, a perspective or a fill or stroke with geometry effects of its own keep one set of raster effects around their copies. Scores and hours unchanged. - **Rasterize before a Transform effect:** effects apply in the order they are listed, each one taking the result of the one before ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). On a path or compound path, a Transform effect listed after the object's own Rasterize effect now moves the image that Rasterize makes: the image is made of the art before the Transform effect, at the Rasterize effect's resolution and with its room around the art, and the Transform effect scales, turns, reflects and moves the image with its pixel grid. Before, the Transform effect moved the art and Rasterize made a new image of the moved art on a grid square to the page. Keeping the image's pixel grid under the Transform effect is VectorCraft's own rule. A hidden Transform effect, or one with Transform Objects off, leaves the image where it is, and one that scales it to nothing leaves nothing drawn. The canvas, the object's bounds, Expand Appearance and PDF export draw the same image (effects `tests::rasterfollow::rasterize_following_ignores_hidden_and_objects_off`, `tests::rasterfollow::the_image_moves_by_each_transform_about_the_art_it_takes`; render `rasterize::rasterize_then_scale_uses_the_pretransform_pixels`, `rasterize::rasterize_then_rotate_and_reflect_moves_the_pixel_grid`, `rasterize::rasterize_then_nonuniform_scale_and_zero_scale_are_bounded`; engine `rastersettings::expand_rasterize_then_transform_matches_canvas`). Not yet: a Transform effect that makes copies or moves at random, a Transform effect followed by another kind of effect, a fill's or stroke's own Rasterize effect, and Rasterize on type, images, symbol instances and groups keep the earlier behavior. Scores and hours unchanged. - **Raster effects before a Transform effect past the effect budget:** VectorCraft leaves out a Transform effect whose result would pass its geometry budget of 2 million anchors or 8 million lines drawn, and the art stays where it was. The raster effects listed before that Transform effect now stay with the art too: a Drop Shadow keeps its own offset and blur, and the Transform effects after it that fit still move both. Before, the art stayed while the shadow scaled with the Transform effect it did not take. This is VectorCraft's own rule. It applies to a path's own effects and to its fills' and strokes' own, also when the path is in a group whose geometry effects run after its members' own, on the canvas and in its bounds, in export, Expand Appearance, Object › Expand and Outline Stroke, and a hidden shadow keeps its values once shown (effects `tests::rasterfollow::a_transform_past_the_line_budget_moves_the_art_with_its_shadow`, `tests::rasterfollow::only_transforms_that_ran_move_a_preceding_shadow`, `tests::rasterfollow::a_skipped_item_transform_keeps_its_shadow`, `tests::rasterfollow::the_shape_art_of_a_skipped_transform_keeps_its_shadows`, `tests::rasterfollow::a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects`; render `objectfx::a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn`, `fx::renderer::tests::a_path_paints_from_the_transforms_that_moved_it`; engine `objexpand::a_shadow_before_a_skipped_transform_expands_with_its_own_offset`). Not yet: the shadow of type, an image, a symbol instance or a group whose art a Transform effect leaves in place past the budget still follows that effect. Scores and hours unchanged. - **Raster effects inside an object or group with a Transform effect:** effects applied to a group affect everything in it ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). How a Transform effect changes the raster effects inside a group or object is VectorCraft's own rule. A group's Transform effect that moves it once now transforms the raster effects of its members, of their fills and strokes, of nested groups and of the art of the linked opacity masks in it, after the members' own Transform effects. A raster effect that a member's own Transform effect with copies or random holds back keeps its value through that effect and still transforms with the group's. VectorCraft applies the same rule to the raster effects of an object's fills and strokes under the object's Transform effect. Sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, with Scale Strokes & Effects on or off. Before, they kept their values, or with Scale Strokes & Effects on scaled by the mean scale with the offset unturned. A group's or object's Transform effect that makes copies or moves at random leaves them as before. The canvas, the redraw region, export, Expand Appearance, Object › Expand and Outline Stroke use the same values (effects `tests::rasterfollow`, `group::tests::a_compound_shapes_transform_turns_its_fills_shadow`; render `a_transform_scales_the_shadows_of_fills_and_members_with_the_art`; engine `objexpand::a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it`, `objexpand::shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them`, `outlinestroke::a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it`). Scores and hours unchanged. From b464ec2825829634b03e92f028356d4fa0bf52ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:26:34 -0800 Subject: [PATCH 07/21] Effects: a group's or layer's copies keep members' effects, hidden members and earlier copies' shadows in step - A group or layer with a fill or stroke of its own and only raster effects before its copying Transform effect now applies its members' own effects before the copies are made, as one without a fill or stroke does. - A layer's copies are made about the bounds of its visible members, as the layer measures them, rather than about its hidden members as well. - When an earlier copying Transform effect of the group or layer made copies that carry its raster effects, each copy of a later one moves, turns, reflects and scales those raster effects with it. --- crates/effects/src/group.rs | 21 +++++--- crates/effects/src/reshape.rs | 25 +++++++-- crates/effects/src/tests/rasterfollow.rs | 65 ++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 10 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 1e8d75f52e..9531159e01 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -920,13 +920,17 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); let mut source = m.clone(); source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec(); + // With no geometry effect before the Transform effect, `evaluate_container` leaves the members' + // own effects live (it only paints the group's own fills and strokes): the members are drawn + // first, so their effects apply before the copies are made. + if crate::reshape::geometry_effects(&source).is_empty() { + source = crate::reshape::outlined_members(doc, &source); + // The members' raster effects follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut source); + } let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { - let mut p = crate::reshape::outlined_members(doc, &source); - { - // The members' raster effects follow the group's own Transform effects as well. - let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); - members_as_drawn(doc, &mut p); - } + let mut p = source.clone(); p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); p }); @@ -936,11 +940,14 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { piece.locked = false; (piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false); piece.extras_mut().mask = None; + // The copies are made about the piece's bounds, measured first: a layer leaves its hidden + // members out of them, and a group does not. + let bounds = piece.geometric_bounds(); // A layer's copies are groups in it. if let NodeKind::Layer { children, clip, .. } = &mut piece.kind { piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip }; } - let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece); + let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds); let copies = art.children().cloned().unwrap_or_default(); if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind { *children = copies; diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c6278f3e4f..584e98055b 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -191,13 +191,17 @@ pub(crate) fn copied_container_raster_at(n: &Node) -> Option { /// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale /// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect /// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as -/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. Returns the art +/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies +/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have +/// their raster effects moved, turned, reflected and scaled with each copy in the same way +/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art /// and the raster effects from `t` on, as they ran. -pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node) -> (Node, Vec) { +pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option) -> (Node, Vec) { let rest = n.appearance.effects.get(t..).unwrap_or_default(); let own = piece.appearance.effects.clone(); + let original = piece.clone(); let mut art = Node::group(n.id, vec![Arc::new(piece)]); - if let (Some(e), Some(bounds)) = (rest.first(), art.geometric_bounds()) { + if let (Some(e), Some(bounds)) = (rest.first(), bounds) { let params = merged_params(&e.id, &e.params); let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); let max = Budget::EFFECTS.at_least(art_cost(&art)); @@ -218,6 +222,7 @@ pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, p let copy = Arc::make_mut(c); copy.appearance.effects = own.clone(); crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY); + follow_carried(copy, &original, n.id, a); } } } @@ -232,6 +237,20 @@ pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, p (art, effects) } +/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a +/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster +/// effects of the matching members of `original`, the piece `copy` was made from, made to follow +/// `a` ([`crate::raster::follow_contents`]). +fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) { + let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return }; + for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) { + let c = Arc::make_mut(c); + c.appearance.effects = w.appearance.effects.clone(); + crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY); + follow_carried(c, w, id, a); + } +} + /// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id, /// else `None`. fn painted_plugin(e: &Effect) -> Option<&str> { diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index 0dbbe401fc..3c59d3e773 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -907,6 +907,71 @@ fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() { assert_eq!(shadows_in(&art).len(), 3); } +/// The bounds of every node with `id` under `art`, in order. +fn bounds_of(art: &Node, id: u64) -> Vec { + let mut out = vec![]; + art.walk(&mut |m| { + if m.id == NodeId(id) + && let Some(b) = m.geometric_bounds() + { + out.push(b); + } + }); + out +} + +fn rects_near(a: &[Rect], b: &[Rect]) -> bool { + let near = |p: f64, q: f64| (p - q).abs() < 1e-6; + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1)) +} + +/// A group with a fill of its own and only a shadow before its copying Transform effect applies +/// its members' own effects before it copies them, as a group without a fill does: a member's own +/// move is turned with each copy. +#[test] +fn a_painted_groups_copies_take_their_members_own_effects_first() { + let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])]; + let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))]; + let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap(); + let mut painted = group(170, members(), effects()); + *painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + painted.appearance.effects = effects(); + let art = crate::evaluate_container(None, &painted).unwrap(); + let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171)); + assert!(!want.is_empty()); + assert!(rects_near(&got, &want), "{got:?} {want:?}"); +} + +/// A layer's copies are made about the bounds of its visible members, as the layer measures them: +/// a hidden member does not move the center that a reflected copy turns about. +#[test] +fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() { + let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]); + hidden.visible = false; + let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let got = bounds_of(&art, 181); + assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}"); +} + +/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each +/// copy of a later one, drawn and baked. +#[test] +fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() { + let g = || { + group( + 190, + vec![square(191, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))], + ) + }; + let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)]; + let art = crate::evaluate_container(None, &g()).unwrap(); + assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art)); + let b = baked(g()); + assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b)); +} + /// A group holding type whose Transform effect only moves its copies, baked for export, gives each /// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type /// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs From b4e45fa93c38aad7403e7cccaefc981b1d2e4c8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:51:59 -0800 Subject: [PATCH 08/21] Direct Selection: a marquee picks the points of a selected blend's spine A Direct Selection marquee now picks the spine points inside it on the topmost selected blend, and the picked points drag together as Shift-clicked ones do. With Shift the marquee adds points or takes picked ones away, and the blend stays selected. A plain marquee around none of them drops the picks, and Escape during the marquee keeps them. Unselected, locked and hidden blends are skipped. --- crates/tools/src/direct.rs | 43 +++++++++- crates/tools/src/direct/tests.rs | 131 +++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 4 files changed, 172 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 5a5c951548..4c93660ace 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -25,8 +25,9 @@ //! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]). //! A Cmd/Ctrl+Shift double-click with either one releases the ruler guide or guide path under the //! pointer ([`release_guide_at`]). -//! Direct Selection also edits a blend's spine: drag its points (Shift-click picks several, which -//! drag together; a key object on a point moves with it) and, once a point is clicked, its +//! Direct Selection also edits a blend's spine: drag its points (Shift-click and, on a selected +//! blend, the marquee pick several, which drag together; a key object on a point moves with it) +//! and, once a point is clicked, its //! handles; and the points of selected gradient meshes //! and of mesh and warp envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several, //! a click on a gradient mesh's line picks its two ends and one inside a patch the four points @@ -192,7 +193,8 @@ pub struct DirectSelectionTool { moved: Option, /// The spine point last clicked (blend, anchor): its handles show and can be dragged. spine: Option<(NodeId, usize)>, - /// Other points of that spine picked with it (Shift-click adds or takes one away); dragging + /// Other points of that spine picked with it (Shift-click adds or takes one away, and a + /// marquee picks those inside it); dragging /// a picked point moves them all (#5285). spine_more: Vec, mesh: MeshEdit, @@ -915,6 +917,10 @@ impl Tool for DirectSelectionTool { if let Some(out) = self.press_hidden(cx, ev, p) { return out; } + // The spine points picked before stay picked while the marquee is drawn: its + // release replaces them (with Shift, toggles them), and Escape keeps them. + self.spine = held; + self.spine_more = if held.is_some() { more } else { vec![] }; self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false, whole: ev.mods.alt }; vec![] } @@ -1641,12 +1647,14 @@ impl DirectSelectionTool { return vec![]; } self.frame.clear(); + (self.spine, self.spine_more) = (None, vec![]); return vec![Action::Exec("select.none".into(), json!({}))]; } // With Group Selection's enclosed marquee, the tool selects the objects inside it // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every // object it touches, each whole. if enclosed || whole { + (self.spine, self.spine_more) = (None, vec![]); let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); @@ -1702,6 +1710,33 @@ impl DirectSelectionTool { } } } + // Direct Selection: the points of a selected blend's spine inside the rect are picked, on + // the topmost such blend; with Shift they are toggled. The blend stays selected. A plain + // marquee that holds none of them drops the points picked before. + let mut spined: Option = None; + if !self.group { + let found = spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + let inside: BTreeSet = path.anchors().filter(|(s, _, a)| *s == 0 && r.contains(a.p)).map(|(_, i, _)| i).collect(); + (!inside.is_empty()).then_some((id, inside)) + }); + match found { + Some((id, inside)) => { + let held = self.spine.filter(|(h, _)| toggle && *h == id); + let before: BTreeSet = held.map(|(_, a)| self.spine_more.iter().copied().chain([a]).collect()).unwrap_or_default(); + let picked: BTreeSet = if toggle { before.symmetric_difference(&inside).copied().collect() } else { inside }; + let focus = held.map(|(_, a)| a).filter(|a| picked.contains(a)).or_else(|| picked.last().copied()); + self.spine = focus.map(|a| (id, a)); + self.spine_more = picked.into_iter().filter(|a| Some(*a) != focus).collect(); + spined = Some(id); + if !toggle { + sel.push((id, vec![])); + } + } + None if !toggle => (self.spine, self.spine_more) = (None, vec![]), + // With Shift, the blend holding the picked points stays selected with them. + None => spined = self.spine.map(|(id, _)| id), + } + } let mut marked: BTreeMap> = if toggle { self.frame_anchors(cx).into_iter().map(|(id, v)| (id, v.into_iter().collect())).collect() } else { BTreeMap::new() }; for (id, inside) in &framed { @@ -1721,7 +1756,7 @@ impl DirectSelectionTool { // the marquee touches them, as with the Selection tool (#927). for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); - if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) { + if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) { sel.push((id, vec![])); } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 1a7cb68a55..0c2aabb768 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -246,6 +246,137 @@ fn shift_click_picks_several_spine_points_which_drag_together() { assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 0 && v.get("with").is_none()), "{a:?}"); } +/// [`blend_doc`] with a spine through (110, 310), (160, 310) and (210, 310). +fn blend_doc_with_three_spine_points() -> (vectorcraft_doc::Document, NodeId) { + let (mut d, g, _) = blend_doc(); + let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(160.0, 310.0), Point::new(210.0, 310.0)], false); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![0, 2]); + (d, g) +} + +/// A marquee drawn with Direct Selection from `from` to `to`, released. +fn spine_marquee(t: &mut DirectSelectionTool, cx: &ToolContext, from: (f64, f64), to: (f64, f64), mods: Mods) -> Vec { + assert_eq!(t.pointer(cx, &PointerEvent::new(PointerKind::Down, from.0, from.1).with_mods(mods)), vec![]); + t.pointer(cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1).with_mods(mods)); + assert!(t.overlays(cx).iter().any(|o| matches!(o, Overlay::Marquee(_))), "a marquee"); + t.pointer(cx, &PointerEvent::new(PointerKind::Up, to.0, to.1).with_mods(mods)) +} + +/// A Direct Selection marquee picks the points of a selected blend's spine inside it, which then +/// drag together, and keeps the blend selected; a marquee around none of them drops the picks. +#[test] +fn marquee_picks_selected_blend_spine_points_which_drag_together() { + let (d, g) = blend_doc_with_three_spine_points(); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let filled = |t: &DirectSelectionTool| t.overlays(&cx).iter().filter(|o| matches!(o, Overlay::Anchor { filled: true, .. })).count(); + let mut t = DirectSelectionTool::new(false); + // Around (160, 310) and (210, 310), the second on the rect's edge. + let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (160.0, 290.0), Mods::default()); + assert!( + matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["mode"] == "set" && v["items"].as_array().is_some_and(|i| i.iter().any(|i| i["id"] == g.0))), + "the blend stays selected: {a:?}" + ); + assert_eq!(filled(&t), 2, "both picked points show"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 330.0)); + assert_eq!( + a.last(), + Some(&Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": g.0, "anchor": 2, "x": 210.0, "y": 330.0, "with": [1]}))) + ); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 330.0)), vec![Action::Commit]); + // A marquee around none of the points drops them. + spine_marquee(&mut t, &cx, (300.0, 330.0), (240.0, 290.0), Mods::default()); + assert_eq!((t.spine, filled(&t)), (None, 0)); +} + +/// With Shift, a Direct Selection marquee toggles the spine points inside it: a picked one leaves, +/// another joins, and those outside it keep their state; the blend is not toggled away. +#[test] +fn shift_marquee_toggles_selected_blend_spine_points() { + let (d, g) = blend_doc_with_three_spine_points(); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0)); + let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (150.0, 290.0), shift); + assert!( + matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["items"].as_array().is_some_and(|i| !i.iter().any(|i| i["id"] == g.0))), + "the blend is not toggled: {a:?}" + ); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![])); + spine_marquee(&mut t, &cx, (130.0, 330.0), (90.0, 290.0), shift); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0])); + // A Shift-marquee around none of them keeps them, and keeps the blend selected when it + // touches the blend's art. + spine_marquee(&mut t, &cx, (300.0, 330.0), (240.0, 290.0), shift); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0])); + let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (205.0, 315.0), shift); + assert!( + matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["items"].as_array().is_some_and(|i| !i.iter().any(|i| i["id"] == g.0))), + "the blend is not toggled: {a:?}" + ); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0])); +} + +/// A Direct Selection marquee does not pick the spine points of a blend that is not selected, or +/// of a selected blend that is locked or hidden. +#[test] +fn marquee_skips_unselected_locked_and_hidden_blend_spines() { + let (d, g) = blend_doc_with_three_spine_points(); + let p = paint(); + let mut s = Selection::default(); + let none = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + spine_marquee(&mut t, &none, (230.0, 330.0), (150.0, 290.0), Mods::default()); + assert_eq!(t.spine, None, "not selected"); + s.set([g]); + for lock in [true, false] { + let mut d = d.clone(); + let Some(n) = d.node_mut(g) else { panic!("blend") }; + if lock { + n.locked = true; + } else { + n.visible = false; + } + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + spine_marquee(&mut t, &c, (230.0, 330.0), (150.0, 290.0), Mods::default()); + assert_eq!(t.spine, None, "locked: {lock}"); + } + // The same marquee on the selected blend picks them. + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + spine_marquee(&mut t, &c, (230.0, 330.0), (150.0, 290.0), Mods::default()); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![1])); +} + +/// Escape during a Direct Selection marquee cancels it and keeps the spine points picked before. +#[test] +fn escape_cancels_a_marquee_and_keeps_the_picked_spine_points() { + let (d, g) = blend_doc_with_three_spine_points(); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 330.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 290.0)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 290.0)), vec![]); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 1)), vec![])); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Anchor { filled: true, .. })), "the picked point shows"); +} + /// #1111: the Anchor Point tool bends a selected blend's straight spine; Direct Selection /// reshapes a curved spine segment and leaves a straight one alone, as it does a path's. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..a257d8c187 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1239,6 +1239,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). + - **Blend spine points by marquee:** with Direct Selection, a marquee picks the spine points inside it on a selected blend, the topmost one when several are selected, and the picked points drag together as Shift-clicked ones do; Shift-marquee adds points or takes picked ones away, a plain marquee around none of them drops the picks, and Escape during the marquee keeps them. Unselected, locked and hidden blends are skipped. The spine's points are anchor points edited with Direct Selection ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/modify-spine-of-blended-objects.html)), and a boundary drag with the tool selects anchor points ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/select-anchor-points-in-paths.html)); the rules for selected, topmost and Shift are VectorCraft's own (`crates/tools/src/direct/tests.rs`, `marquee_picks_selected_blend_spine_points_which_drag_together`, `shift_marquee_toggles_selected_blend_spine_points`, `marquee_skips_unselected_locked_and_hidden_blend_spines`, `escape_cancels_a_marquee_and_keeps_the_picked_spine_points`). - **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. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..b5cd387544 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -182,7 +182,7 @@ tools, never checked side by side) isn't captured row by row. | Layers panel lists a blend's spine (#4820) | done | an open blend shows a `` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | -| Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee doesn't pick spine points yet | +| Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | | Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | From bed9c71f61edd8534dd47e1fd268f12e226a39f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:45:35 -0800 Subject: [PATCH 09/21] Effects: a group's copies keep their random moves when the raster budget leaves one Expand Appearance gave each copy of a group's or layer's Transform effect new ids after expanding it. When the raster budget refused the image for a copy that held a random Transform effect, the copy stayed unexpanded, but its new ids gave that effect a new seed, so the copy moved. The group or layer now stays as it is in that case, as it does when its own raster effects go past the budget. That rollback also removes the images its earlier copies added to the document and gives their charge back to the budget, so later objects in the same command can still use it. --- crates/engine/src/cmd/effectcmd.rs | 44 +++++++++++++++++------- crates/engine/src/cmd/effectcmd/tests.rs | 39 +++++++++++++++++++++ 2 files changed, 71 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 0dfb967422..f21adcbc10 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1246,7 +1246,9 @@ fn expand_node_except( /// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does, /// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of /// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there. -/// Returns whether `n` changed; any other object stays as it is. +/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when +/// such a copy still holds a random Transform effect after the raster budget left part of it as +/// it is: its new ids would give that effect another seed. fn copies_carrying_raster( d: &mut Document, n: &mut Node, @@ -1255,15 +1257,19 @@ fn copies_carrying_raster( members: &mut std::collections::HashMap>, (out, listed): (&mut Vec, &mut bool), raster: &mut RasterBudget, -) -> bool { - if !is_container(n) || effects::outer_effects(n).len() == n.appearance.effects.len() { - return false; +) -> std::result::Result { + if !carries_copies(n) { + return Ok(false); } - let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return false }; + let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) }; let mut seen = std::collections::HashSet::from([n.id]); for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { let c = Arc::make_mut(c); + let left = raster.left; let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster)); + if expanded.is_some() && raster.left > left && has_seeded(c) { + return Err(OverBudget); + } let mut was = vec![]; if !skip.is_empty() { c.walk(&mut |n| was.push(n.id)); @@ -1286,7 +1292,13 @@ fn copies_carrying_raster( *listed = true; } *n = m; - true + Ok(true) +} + +/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed +/// before it ([`copies_carrying_raster`])? +fn carries_copies(n: &Node) -> bool { + is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len() } /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when @@ -1318,10 +1330,13 @@ 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()) + // The embedded images before the adjustment and the expansions of the copies + // ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the + // recolored copies and the images those add then go again. + let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n)) .then(|| d.images.keys().cloned().collect::>()); + // What the raster budget had left before those expansions: it gets back what they took. + let budget_before = (raster.images, raster.pixels); if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1372,14 +1387,19 @@ fn expanded_node( // Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id, // with what their expansion lists. let mut members = std::collections::HashMap::new(); - changed |= copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster); + let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster); // Raster effects whose image would go past the budget stay: so does the object, with what is - // inside it and its color adjustments (a symbol instance stays an instance of its symbol). - let Ok(image) = raster_image(d, &n, raster) else { + // inside it and its color adjustments (a symbol instance stays an instance of its symbol), and + // so does a group or layer whose copies keep a random Transform effect the budget left. + let Ok(image) = copies.and_then(|copied| { + changed |= copied; + raster_image(d, &n, raster) + }) else { out.truncate(listed_before); if let Some(keys) = images_before { d.images.retain(|k, _| keys.contains(k)); } + (raster.images, raster.pixels) = budget_before; return None; }; let mut v = n.clone(); diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 5a1146f28f..d035c24860 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1150,3 +1150,42 @@ fn an_image_past_the_pixels_left_stays_unmade() { 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"); } + +/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a +/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it +/// is when the raster budget has no image left for a copy's shadow, with none left or with one for +/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as +/// before, and the document holds no image the first copy's expansion made, nor the budget its +/// charge. +#[test] +fn copies_the_raster_budget_leaves_keep_their_random_moves() { + let (mut s, id) = session_with_rect(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap()); + let random = json!({"moveH": 40, "moveV": 40, "random": true}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap(); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap(); + let draw = |d: &vectorcraft_doc::Document| { + vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + for images in [0, 1] { + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let before = d.node(g).cloned().unwrap(); + assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow"); + let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::>()); + + let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 }; + let mut out = vec![]; + super::expand_node(&mut d, g, &[], &mut out, &mut budget); + assert!(budget.left > 0, "{images}: a copy's shadow is left"); + assert!(out.is_empty(), "{images}: nothing expands: {out:?}"); + assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is"); + assert!(draw(&d) == drawn, "{images}: the group draws as before"); + assert_eq!(d.images.keys().cloned().collect::>(), keys, "{images}: no image is added"); + assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took"); + } +} From 2c270a1d57c1ec34bde9e1fba93804a8f42d4281 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:03:55 -0800 Subject: [PATCH 10/21] =?UTF-8?q?Context=20menu:=20the=20Spelling=20submen?= =?UTF-8?q?u=20on=20type=20also=20has=20Check=20Spelling=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-click on type now has Check Spelling… after Auto Spell Check in its Spelling submenu, as Edit › Spelling has it. The item runs the existing ui.checkSpelling command on the selection, which the right-click sets to the type under the pointer. A right-click on an underlined word offers it too. The help page describes this right-click route to the dialog: https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html The context menu draws check marks only in a submenu of toggles alone. The Spelling submenu now also shows them, so Auto Spell Check keeps its mark next to the plain Check Spelling… item. Other submenus are unchanged. --- crates/ui-egui/src/menus/bar.rs | 12 +++-- crates/ui-egui/src/menus/context.rs | 13 +++-- crates/ui-egui/src/tests/contextmenu.rs | 64 ++++++++++++++++++++++++- docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 82 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index 85588620e8..72cbc4535b 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -138,7 +138,7 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite ui.menu_button(label, |ui| { widgets::menu_scroll(ui, |ui| { widgets::menu_min_width(ui, 200.0); - render_items(app, ui, children, checks || only_toggles(app, children), clicked); + render_items(app, ui, children, checks || shows_marks(app, children), clicked); }); }); } @@ -147,8 +147,14 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite } } -/// Whether every item of a submenu can be on or off: a menu drawn without check marks (the canvas -/// context menu) still shows them there, since its label alone can't say whether it is on. +/// Whether a submenu of a menu drawn without check marks (the canvas context menu) still shows +/// them: when every item can be on or off, or when it holds Auto Spell Check (the Spelling +/// submenu, with Check Spelling… after it), since a toggle's label alone can't say whether it is on. +fn shows_marks(app: &VectorcraftApp, items: &[Item]) -> bool { + only_toggles(app, items) || items.iter().any(|it| matches!(it, Item::Cmd(_, "edit.autoSpellCheck", _))) +} + +/// Whether every item of a submenu can be on or off. fn only_toggles(app: &VectorcraftApp, items: &[Item]) -> bool { let mut rows = items.iter().filter_map(|it| entry(app, it)).filter(|e| !matches!(e, Entry::Sep)).peekable(); rows.peek().is_some() && rows.all(|e| matches!(e, Entry::Item(r) if r.checked.is_some())) diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 68b2a93574..ca7dae0ef5 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -96,10 +96,13 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { // The paragraphs of the selected type, or those the Type tool's selection touches. if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); - // A right-click on type turns Auto Spell Check on or off, as Edit › Spelling does, per - // the public [Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html) - // page. Its submenu holds only toggles, so it shows the check mark (`render_items`). - v.push(sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck")])); + // A right-click on type turns Auto Spell Check on or off and opens Check Spelling…, as + // Edit › Spelling does, per the public [Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html) + // page. The submenu shows Auto Spell Check's check mark (`render_items`). + v.push(sub( + "Spelling", + vec![c("Auto Spell Check", "edit.autoSpellCheck"), c("Check Spelling…", crate::dialogs::check_spelling::COMMAND)], + )); } v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]); if intertwine.is_none() { @@ -274,7 +277,7 @@ pub fn context_menu_body(app: &VectorcraftApp, ui: &mut egui::Ui, clicked: &mut widgets::menu_scroll(ui, |ui| { widgets::menu_min_width(ui, 200.0); // Its toggles already say what they do (Show Rulers, Hide Guides): no check-mark gutter, - // except in a submenu of toggles alone (Spelling › Auto Spell Check). + // except in a submenu of toggles alone and in Spelling, for Auto Spell Check. render_items(app, ui, &context_items(app), false, clicked); }); } diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index b73bb08dfa..d82edabe51 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -383,7 +383,7 @@ fn selected_type_has_apply_numbers() { /// A right-click on type has Spelling › Auto Spell Check, which turns it on or off as Edit › /// Spelling does (helpx: Check and correct spelling, "Turn on Auto Spell Check"). The context menu -/// draws no check marks, but this submenu holds only the toggle, so it shows whether it is on; +/// draws no check marks, but this submenu shows whether it is on, with Check Spelling… after it; /// other submenus stay without the room for one. Other art has no Spelling submenu. #[test] fn right_click_on_type_turns_auto_spell_check_on_and_off() { @@ -417,10 +417,72 @@ fn right_click_on_type_turns_auto_spell_check_on_and_off() { assert!(!has(&texts, "Spelling"), "the menu closed: {texts:?}"); let texts = open_spelling(&mut app); assert!(texts.iter().any(|(s, _)| s == "✓ Auto Spell Check"), "checked: {texts:?}"); + assert!(texts.iter().any(|(s, _)| s == "Check Spelling…"), "the dialog's item, which has no check mark: {texts:?}"); click(&mut app, &ctx, at(&texts, "✓ Auto Spell Check"), PointerButton::Primary); assert!(!app.ui.view.auto_spell_check, "turned off"); } +/// A right-click on type has Spelling › Check Spelling… after Auto Spell Check, as Edit › +/// Spelling has, which opens the Check Spelling dialog on the type right-clicked (helpx: Check and +/// correct spelling). Other art has no such item. +#[test] +fn right_click_on_type_opens_check_spelling() { + let mut app = app(); + rect(&mut app, 200.0, 150.0); + let t = NodeId(app.run("text.create", json!({"x": 20, "y": 60, "text": "Hello wrold", "size": 24})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 250.0, 200.0); + click(&mut app, &ctx, p, PointerButton::Secondary); + let dialog_item = |app: &VectorcraftApp| { + menus::context_entries(app).into_iter().position(|e| e.command.as_deref() == Some(crate::dialogs::check_spelling::COMMAND)) + }; + assert!(dialog_item(&app).is_none(), "a rectangle has no Check Spelling…"); + let away = screen(&app, 390.0, 290.0); + click(&mut app, &ctx, away, PointerButton::Primary); + let p = word_at(&app, t, 0, 5); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [t], "the type right-clicked is selected"); + // Agents see it under the Spelling path, after Auto Spell Check. + let entries = menus::context_entries(&app); + let i = dialog_item(&app).expect("Check Spelling…"); + assert_eq!((entries[i].path.as_slice(), entries[i].label.as_str(), entries[i].enabled), (&["Spelling".to_string()][..], "Check Spelling…", true)); + assert_eq!(entries.get(i.wrapping_sub(1)).and_then(|e| e.command.as_deref()), Some("edit.autoSpellCheck")); + frame(&mut app, &ctx, vec![Event::PointerMoved(at(&texts, "Spelling"))]); + let texts = frame(&mut app, &ctx, vec![]); + let (auto, check) = (at(&texts, " Auto Spell Check"), at(&texts, "Check Spelling…")); + assert!(auto.y < check.y, "Auto Spell Check first: {texts:?}"); + let texts = click(&mut app, &ctx, check, PointerButton::Primary); + assert!(!has(&texts, "Spelling"), "the menu closed: {texts:?}"); + let d = app.ui.dialog.as_ref().expect("a dialog opened"); + assert_eq!(d.kind.as_str(), crate::dialogs::check_spelling::KIND); + assert_eq!(d.fields["ids"], json!([t.0]), "it checks the type right-clicked"); + assert_eq!(d.fields["not_in_dictionary"], json!("wrold"), "and stops at its unknown word"); +} + +/// A right-click on a word Auto Spell Check underlined lists the suggestions, Ignore All and Add +/// to Dictionary, and the type's Spelling submenu with Check Spelling… as well. +#[test] +fn right_click_on_an_underlined_word_also_offers_check_spelling() { + let mut app = app(); + let id = spelled(&mut app, "the speling cat"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = word_at(&app, id, 4, 11); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Ignore All") && has(&texts, "Add to Dictionary"), "{texts:?}"); + let e = menus::context_entries(&app).into_iter().find(|e| e.command.as_deref() == Some(crate::dialogs::check_spelling::COMMAND)); + assert_eq!(e.map(|e| e.path), Some(vec!["Spelling".to_string()]), "Spelling › Check Spelling…"); + frame(&mut app, &ctx, vec![Event::PointerMoved(at(&texts, "Spelling"))]); + let texts = frame(&mut app, &ctx, vec![]); + assert!(texts.iter().any(|(s, _)| s == "✓ Auto Spell Check"), "checked: {texts:?}"); + click(&mut app, &ctx, at(&texts, "Check Spelling…"), PointerButton::Primary); + let d = app.ui.dialog.as_ref().expect("a dialog opened"); + assert_eq!(d.kind.as_str(), crate::dialogs::check_spelling::KIND); + assert_eq!(d.fields["not_in_dictionary"], json!("speling")); +} + /// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn /// there, bottom first. fn intertwine_order(app: &VectorcraftApp, g: NodeId, x: f64, y: f64) -> Vec { diff --git a/docs/gaps.md b/docs/gaps.md index eda7bb21dd..90bd9d4a8d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -460,7 +460,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** COLR and SVG glyphs go with type that geometry effects reshape, into Expand Appearance and EMF/WMF export, where the type's outlines used to leave them out; bitmap glyphs (emoji) too, as images that hold their own pixels until a document takes them in; estimate unchanged. -- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation. Estimate unchanged. +- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation. Estimate unchanged. - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..197b3333b9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2596,7 +2596,7 @@ Auto Spell Check followed (2026-11-09): the same page has Edit › Spelling › The right-click followed (2026-11-10), as the same page's "Correct spelling errors during Auto Spell Check" describes it: right-click a word with a red underline, then choose a suggested word, Ignore All to skip it in the current document, or Add to Dictionary (#4936). The canvas context menu lists the words `text.spelling.suggest` gives for it in its run's language, each replacing the word with `text.editRange` as one undo step, or No Suggestions; then Ignore All (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`). It lists nothing for a word that is right, with Auto Spell Check off, or once the word under the right-click has changed (`ui-egui/src/tests/contextmenu.rs`). The dialogs remain. -The page's other way to turn Auto Spell Check on followed (2026-11-10): right-click the text and choose Spelling › Auto Spell Check (#4936). A right-click on type (which selects it) has a Spelling submenu with Auto Spell Check, which runs `edit.autoSpellCheck` as Edit › Spelling does. The context menu draws no check marks, its toggles saying what they do (Show Rulers, Hide Guides), but a submenu that holds only toggles shows them, so Auto Spell Check is checked while it is on; other art has no Spelling submenu (`right_click_on_type_turns_auto_spell_check_on_and_off`). +The page's other way to turn Auto Spell Check on followed (2026-11-10): right-click the text and choose Spelling › Auto Spell Check (#4936). A right-click on type (which selects it) has a Spelling submenu with Auto Spell Check, which runs `edit.autoSpellCheck` as Edit › Spelling does. The context menu draws no check marks, its toggles saying what they do (Show Rulers, Hide Guides), but a submenu that holds only toggles shows them, and so does Spelling, so Auto Spell Check is checked while it is on; other art has no Spelling submenu (`right_click_on_type_turns_auto_spell_check_on_and_off`). Check Spelling… followed in the same submenu (2026-11-15), after Auto Spell Check as in Edit › Spelling, as the page also describes opening the Check Spelling dialog from Spelling in the menu of right-clicked text. It runs `ui.checkSpelling` on the selection, which the right-click made the type under the pointer, and a right-click on an underlined word has it too (`right_click_on_type_opens_check_spelling`, `right_click_on_an_underlined_word_also_offers_check_spelling`). Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custom dictionary" describes it: Edit › Edit Custom Dictionary…, then enter a word in the Entry field and Add it, select a word and Delete it, or select a word, edit it in the Entry field and Change it, then Done (#4936). The dialog lists the custom dictionary's words (`text.spelling.dictionary`); picking one puts it in the Entry field. Add and Change take one word that isn't listed yet, kept in lower case as the dictionary keeps it, and Delete and Change need a word picked. Nothing changes until Done, which deletes and adds the words that differ (`text.spelling.removeWord`, `text.spelling.addWord`); Cancel leaves the dictionary as it was (`ui-egui/src/dialogs/custom_dictionary.rs`). From e6dc0f09308e74ed8d44b38999ff23f1f29da2d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:35:31 -0800 Subject: [PATCH 11/21] =?UTF-8?q?Rounded=20Rectangle:=20the=20click=20dial?= =?UTF-8?q?og=20opens=20on=20General=20=E2=80=BA=20Corner=20Radius,=20and?= =?UTF-8?q?=20OK=20makes=20its=20radius=20the=20default?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A click with the Rounded Rectangle tool opened the size dialog at a fixed 12 pt radius, and the radius typed there drew one shape without changing General › Corner Radius. The dialog now starts from the preference, and OK sets the preference to the radius drawn (in any unit), so the next dialog and the next drag use it. A radius equal to the preference sets nothing. A radius outside the preference's range of 0 to 1296 pt, or one that is not a length, is refused with an error: the dialog stays open, nothing is drawn and the preference keeps its value. --- crates/ui-egui/src/dialogs/shapes.rs | 63 +++++++++++++++++++++++++++- crates/ui-egui/src/dialogs/tools.rs | 6 ++- docs/target-app-parity.md | 1 + 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index b807bc5274..b761383752 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -398,6 +398,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }) .or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)}))) .or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d))); + let corner_radius = if d.kind == "roundedRectangle" { Some(rounded_radius(app, d)?) } else { None }; let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); let (bx, by) = box_origin(d); let (id, params) = match d.kind.as_str() { @@ -462,7 +463,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } _ => ( "shape.rectangle", - json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "radius": d.f64("radius", 0.0)}), + json!({ + "x": bx, + "y": by, + "width": d.f64("width", 100.0), + "height": d.f64("height", 100.0), + "radius": corner_radius.unwrap_or_else(|| d.f64("radius", 0.0)), + }), ), }; // On the active plane while the perspective grid shows, sized in plane units from the click; @@ -484,9 +491,21 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(options) = options { app.run("tool.setOption", json!({"tool": d.kind, "values": options}))?; } + // The radius of the rounded rectangle drawn is General › Corner Radius from then on. + if let Some(r) = corner_radius.filter(|r| *r != app.session.prefs.corner_radius) { + app.run("prefs.set", json!({"key": "cornerRadius", "value": r}))?; + } Ok(result) } +/// The Rounded Rectangle dialog's radius in points, checked as General › Corner Radius checks it +/// (an error leaves the dialog open and draws nothing). Without the field, the preference. +fn rounded_radius(app: &VectorcraftApp, d: &Dialog) -> Result { + let r = if d.fields.contains_key("radius") { d.f64("radius", f64::NAN) } else { app.session.prefs.corner_radius }; + vectorcraft_engine::cmd::prefscmds::validate("cornerRadius", &json!(r))?; + Ok(r) +} + #[cfg(test)] mod tests { use super::*; @@ -524,6 +543,48 @@ mod tests { assert_eq!(box_origin(&fields(true)), (80.0, 40.0)); } + /// The Rounded Rectangle click dialog opens on General › Corner Radius, and OK makes the radius + /// typed (in any unit) that preference: the next dialog and the tool's next drag use it. + #[test] + fn rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("tool.select", json!({"tool": "roundedRectangle"})).unwrap(); + app.run("prefs.set", json!({"key": "cornerRadius", "value": 20})).unwrap(); + + super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0})); + let d = app.ui.dialog.as_mut().expect("Rounded Rectangle dialog"); + assert_eq!((d.kind.as_str(), d.f64("radius", 0.0)), ("roundedRectangle", 20.0)); + d.fields.insert("radius".into(), json!("0.5 in")); + super::super::confirm(&mut app).unwrap(); + + assert!(app.ui.dialog.is_none()); + let n = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].clone(); + assert_eq!(crate::panels::corner_radius(&app, &n), Some(36.0)); + assert_eq!(app.session.prefs.corner_radius, 36.0); + assert_eq!(app.session.tool_options_of("roundedRectangle")["cornerRadius"], json!(36.0)); + super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); + } + + /// A radius General › Corner Radius would refuse leaves the dialog open, draws nothing and + /// keeps the preference. + #[test] + fn rounded_rectangle_click_dialog_refuses_a_radius_out_of_range() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let before = app.session.prefs.corner_radius; + for bad in [json!(-1), json!(1297), json!("19 in"), json!("wide")] { + super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), bad.clone()); + assert!(super::super::confirm(&mut app).is_err(), "{bad}"); + assert!(app.ui.dialog.is_some(), "{bad}"); + assert!(app.session.doc().unwrap().doc.layers[0].children().unwrap().is_empty(), "{bad}"); + assert_eq!(app.session.prefs.corner_radius, before, "{bad}"); + app.ui.dialog = None; + } + } + /// Turn the link on or off as its button or `ui.dialog.set` does, then apply it as the form /// does on its next frame; what [`link_changed`] returned. fn turn(d: &mut Dialog, on: bool) -> Option { diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index bf65dd4894..6dbcfe28ce 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -18,7 +18,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}), ), - "roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})), + // The radius starts at General › Corner Radius, which OK sets to the radius typed. + "roundedRectangle" => { + let radius = format!("{} pt", app.session.prefs.corner_radius); + Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": radius})) + } "polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})), "star" => { Dialog::new(kind, json!({"x": x, "y": y, "radius1": "50 pt", "radius2": "25 pt", "points": app.session.tool_options_of(kind)["points"]})) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..6ceee393b4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1197,6 +1197,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). Escape while a polygon, star or rounded rectangle is dragged out cancels it and puts back the side count, point count, corner radius or star ratio its Up/Down and Ctrl/Cmd changed, so the next drag, the tool's options and General › Corner Radius start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. + A click with the Rounded Rectangle tool opens the size dialog with its radius at General › Corner Radius, and OK makes the radius typed there that preference, so later rounded rectangles and the dialog's next opening start from it while rounded rectangles already drawn keep their corners, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=64) describes. A radius outside the preference's range of 0 to 1296 pt, which is VectorCraft's own, or one that is not a length is refused with an error: the dialog stays open, nothing is drawn and the preference keeps its value. Evidence: `dialogs::shapes::tests::{rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius, rounded_rectangle_click_dialog_refuses_a_radius_out_of_range}`. While a grid is dragged out, F lowers `rowSkew` (rectangular) or `radialSkew` (polar) by 10 percentage points and V raises it by 10; X lowers `columnSkew` (rectangular) or `concentricSkew` (polar) by 10 and C raises it by 10. Plain and Shift presses work; with Alt, Ctrl or Cmd held they do not, as for the other letters a tool takes while dragging. Each press changes the skew once and updates the preview; values stay within ±500% and remain in the tool options after release. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list the four drag keys and a 10% change. The signs (positive values follow VectorCraft's existing skew convention, so F and X lower the stored value) and one change per press with key repeat ignored are our own rules. While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind and Decay as the amount each wind decreases. An 80% spiral has 80% of its outer radius after four segments; newly drawn spirals with the same settings wind more broadly than in earlier VectorCraft builds. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. From 359a7a2be5e6617bad4bd515601a26790a3821da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:48:17 -0800 Subject: [PATCH 12/21] Symbols: a symbol dragged onto New Symbol is duplicated A symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (symbol.duplicate), with no Symbol Options dialog, in one undo step. The drop works while no art is selected and the button is disabled for clicks. The copy is made of the dragged symbol, not the current one, and the current symbol and the selection stay as they were. The button is outlined while a symbol of the document is held over it; a library symbol, art or a name the document no longer has is ignored. --- crates/ui-egui/src/panels/symbols.rs | 110 ++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 2 files changed, 110 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index a8392cdf50..e095e8b0bf 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -400,7 +400,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("symbol.breakLink", json!({})).ok(); } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); - if widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0).clicked() { + let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0); + // A symbol dragged from the panel and dropped on New Symbol is duplicated, with or without + // art selected. + if let Some(name) = symbol_dropped(ui, &new, &names) { + if let Err(e) = app.run("symbol.duplicate", json!({ "name": name })) { + app.status(e); + } + } else if new.clicked() { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the // dialog's default. let (cmd, p) = if ui.input(|i| i.modifiers.alt) { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; @@ -486,6 +493,18 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The document symbol (one of `names`) dragged from the panel and released on `button` this +/// frame, if any; `button` is outlined while one is held over it. +fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String]) -> Option { + let held = button.dnd_hover_payload::()?; + let PanelDrag::Symbol(name) = &*held else { return None }; + if !names.contains(name) { + return None; + } + widgets::drop_target_outline(ui, button.rect); + button.dnd_release_payload::().map(|_| name.clone()) +} + /// The panel state key of the symbols Select All Unused picked. const MARKED: &str = "sym-unused"; @@ -1896,6 +1915,95 @@ mod tests { assert_eq!(current(&app).as_deref(), Some("Dot")); } + /// The rectangle of the panel's button labeled `label`, enabled or not. + fn button_rect(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) -> Rect { + ctx.enable_accesskit(); + let out = frame_held(ctx, app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l.trim() == label)).find_map(|(_, n)| n.bounds()); + let b = b.unwrap_or_else(|| panic!("a {label} button")); + Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)) + } + + /// Whether `out` draws the drop outline around `rect`. + fn outlined(out: &egui::FullOutput, rect: Rect) -> bool { + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.rect.center().distance(rect.center()) < 0.5 && (r.stroke.width - 1.5).abs() < 0.01, + _ => false, + }) + } + + /// A symbol dragged from the panel, in Thumbnail View or a list view, and dropped on New Symbol + /// is duplicated as Duplicate Symbol does it: a copy of the dragged symbol, not the current one, + /// is added under its default name in one undo step, with no dialog and no placed instance, and + /// the selection and the current symbol stay as they were, with art selected or none (when the + /// button is disabled for clicks). The button is outlined while the symbol is held over it. + #[test] + fn symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views() { + for (view, select) in [("thumbnail", false), ("smallList", true)] { + let mut app = leaf_and_dot(); + app.run("ui.panelView", json!({"panel": "symbols", "view": view})).unwrap(); + if select { + let leaf = instance_of(&app, "Leaf").expect("a Leaf instance"); + app.run("select.set", json!({"ids": [leaf.0]})).unwrap(); + } + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let new = button_rect(&ctx, &mut app, "New Symbol"); + let from = if select { panel_labels(&ctx, &mut app, &["Leaf"])[0].1 } else { pos2(26.0, 26.0) }; + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from + vec2(40.0, 40.0))]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from + vec2(80.0, 80.0))]); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into())), "{view}"); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(new.center())], egui::Modifiers::NONE); + assert!(outlined(&out, new), "{view}: outlined while Leaf is held over it"); + frame(&ctx, &mut app, vec![button(new.center(), false)]); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "Leaf copy"], "{view}"); + let d = app.session.active().unwrap(); + assert_eq!(d.history.undo.len(), undo + 1, "{view}: one undo step"); + assert_eq!(d.selection, selection, "{view}: the selection is unchanged"); + let (leaf, copy) = (&d.doc.symbols[0], &d.doc.symbols[2]); + assert!(!Arc::ptr_eq(&leaf.art, ©.art) && leaf.dynamic == copy.dynamic, "{view}: an independent copy of Leaf"); + assert_eq!(d.doc.symbol_registration("Leaf copy"), d.doc.symbol_registration("Leaf"), "{view}"); + assert_eq!(dialog_kind(&app), None, "{view}: no Symbol Options"); + assert_eq!(art(&app, "Leaf copy").0, 0, "{view}: no instance placed"); + assert_eq!(current(&app).as_deref(), Some("Dot"), "{view}: Dot stays current"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: undo removes only the copy"); + } + } + + /// New Symbol takes only a symbol of the document's: a library symbol, art, a symbol name the + /// document does not have and a symbol released elsewhere make no symbol and no undo step, and + /// the button is not outlined for them. + #[test] + fn new_symbol_button_ignores_other_drops_and_releases_outside() { + let mut app = leaf_and_dot(); + let leaf = instance_of(&app, "Leaf").expect("a Leaf instance"); + let undo = app.session.active().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + let new = button_rect(&ctx, &mut app, "New Symbol"); + let elsewhere = new.center() - vec2(0.0, 60.0); + let cases = [ + ("a library symbol", PanelDrag::LibrarySymbol { library: "basic-shapes".into(), name: "Leaf".into() }, new.center()), + ("art", PanelDrag::Art(vec![leaf]), new.center()), + ("a stale name", PanelDrag::Symbol("Gone".into()), new.center()), + ("a symbol released elsewhere", PanelDrag::Symbol("Leaf".into()), elsewhere), + ]; + for (case, drag, at) in cases { + egui::DragAndDrop::set_payload(&ctx, drag); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + assert!(!outlined(&out, new), "{case}: not outlined"); + frame(&ctx, &mut app, vec![button(at, false)]); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{case}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "{case}: no undo step"); + assert_eq!(dialog_kind(&app), None, "{case}"); + egui::DragAndDrop::clear_payload(&ctx); + } + } + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. fn thread_cpu_ns() -> Option { std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ceb5ea7d0d..c00ef3af4f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1052,6 +1052,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art and keep no guides. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. + - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art or a name the document no longer has is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. From 5daa65c72a7569025dc6f299bcb21cf8e62523ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:17:23 -0800 Subject: [PATCH 13/21] Color Guide: a harmony color or variation dragged onto the Swatches panel becomes a swatch The harmony strip and the variation cells start a paint drag with the primary button. The drag carries the grabbed color as the cell shows it (snapped to the Limit to Library colors), and the Swatches panel's existing drop makes a swatch of it with swatch.new: one undo step, the color's own model, a drop on a color group joins that group, and a color that is already a swatch is added again under another name. Starting a drag does not apply the color or change the base or the selected cells, and a plain click still applies the color as before. --- crates/ui-egui/src/panels/color_guide.rs | 125 +++++++++++++++++++++- crates/ui-egui/src/panels/swatches/dnd.rs | 4 +- crates/ui-egui/src/widgets/drag.rs | 8 +- docs/target-app-parity.md | 1 + 4 files changed, 128 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/color_guide.rs b/crates/ui-egui/src/panels/color_guide.rs index abea906633..bbc1d3db86 100644 --- a/crates/ui-egui/src/panels/color_guide.rs +++ b/crates/ui-egui/src/panels/color_guide.rs @@ -8,7 +8,9 @@ //! without changing the base, and selects it; Shift- or Cmd/Ctrl-click adds //! cells to the selection that Save Colors as Swatches saves as swatches and Save Color Group to //! Swatches saves as one group (without a selection, the group holds the harmony colors). The -//! selection lasts until the guide changes. Limit to Library (the library button, +//! selection lasts until the guide changes. A harmony color or a cell dragged with the primary button +//! carries its color alone, as shown, without applying it or changing the selection; the Swatches +//! panel makes a swatch of it. Limit to Library (the library button, //! `ui.colorGuideLimit`) snaps every colour to a swatch library or the document's swatches; Edit or //! Apply Colors opens Recolor Artwork with the harmony colours, limited the same way. @@ -21,7 +23,7 @@ use vectorcraft_engine::cmd::swatchlib; use super::swatches::{self, colour_libraries, limit_key, limit_name}; use super::{active_paint, apply_click, c32, color_json, library_panel, pstate, set_pstate}; use crate::VectorcraftApp; -use crate::widgets::{self, menu_item}; +use crate::widgets::{self, PanelDrag, menu_item}; /// The base colour before one is set: an orange. const DEFAULT_BASE: Color = Color::Rgb { r: 230.0 / 255.0, g: 120.0 / 255.0, b: 40.0 / 255.0 }; @@ -217,7 +219,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let w = strip.width() / g.colors.len() as f32; for (i, c) in g.colors.iter().enumerate() { let r = Rect::from_min_size(strip.min + vec2(i as f32 * w, 0.0), vec2(w, strip.height())); - let resp = ui.interact(r, ui.scope_id().with(("cg-h", i)), Sense::click()); + let resp = ui.interact(r, ui.scope_id().with(("cg-h", i)), Sense::click_and_drag()); + widgets::drag_source(ui, &resp, || PanelDrag::paint(Paint::solid(*c))); ui.painter().rect_filled(r, 0.0, c32(c)); if resp.on_hover_text(c.to_hex()).clicked() { chosen = Some(*c); @@ -237,7 +240,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (rr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover()); for (ci, v) in row.iter().enumerate() { let r = Rect::from_min_size(rr.min + vec2(x(ci), 0.0), vec2(x(ci + 1) - x(ci) - gap, 17.0)); - let resp = ui.interact(r, ui.scope_id().with(("cg-v", ri, ci)), Sense::click()); + let resp = ui.interact(r, ui.scope_id().with(("cg-v", ri, ci)), Sense::click_and_drag()); + widgets::drag_source(ui, &resp, || PanelDrag::paint(Paint::solid(*v))); ui.painter().rect_filled(r, 0.0, c32(v)); if sel.contains(&(ri, ci)) { ui.painter().rect_stroke(r.shrink(1.0), 0.0, egui::Stroke::new(1.0, egui::Color32::WHITE), egui::StrokeKind::Inside); @@ -433,6 +437,119 @@ mod tests { assert_eq!(base_color(&app).to_hex(), variation, "the base chip adopts the current color"); } + /// One frame at `time` with `events` of the Color Guide panel, followed by the Swatches panel when + /// `swatches` is set; → the center of the guide widget `id` as laid out in that frame. + fn guide_frame( + app: &mut VectorcraftApp, + ctx: &egui::Context, + events: Vec, + time: f64, + swatches: bool, + id: impl std::hash::Hash + std::fmt::Debug, + ) -> egui::Pos2 { + let screen_rect = Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(280.0, 900.0))); + let input = egui::RawInput { events, time: Some(time), screen_rect, ..Default::default() }; + let mut at = None; + let mut out = ctx.run_ui(input, |ui| { + show(app, ui); + at = ctx.read_response(ui.scope_id().with(&id)).map(|r| r.rect.center()); + if swatches { + super::swatches::show(app, ui); + } + }); + out.textures_delta.clear(); + at.expect("the guide widget is drawn") + } + + /// Press on the guide widget `id`, move far enough to start a drag, move to `to` (the widget + /// itself when None) and release there, a frame per step from `time`. → the drag the panel + /// started, read before the release. + fn drag_from( + app: &mut VectorcraftApp, + ctx: &egui::Context, + id: (&str, usize, usize), + to: Option, + time: f64, + swatches: bool, + ) -> Option { + let from = match id.0 { + "cg-h" => guide_frame(app, ctx, vec![], time, swatches, ("cg-h", id.1)), + _ => guide_frame(app, ctx, vec![], time, swatches, ("cg-v", id.1, id.2)), + }; + let to = to.unwrap_or(from); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let step = |app: &mut VectorcraftApp, events, t| { + guide_frame(app, ctx, events, t, swatches, ("cg-h", 0usize)); + }; + step(app, vec![egui::Event::PointerMoved(from), button(from, true)], time + 0.1); + step(app, vec![egui::Event::PointerMoved(from + vec2(8.0, 3.0))], time + 0.2); + let held = egui::DragAndDrop::payload::(ctx).map(|d| (*d).clone()); + step(app, vec![egui::Event::PointerMoved(to)], time + 0.3); + step(app, vec![egui::Event::PointerMoved(to), button(to, false)], time + 0.4); + held + } + + /// A harmony color or a variation dragged from the guide carries that color alone, as a solid + /// paint; the drag applies nothing to the selected art and leaves the base and the selected + /// cells as they were. + #[test] + fn a_dragged_guide_color_carries_its_color_and_applies_nothing() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("paint.setFill", json!({"color": "#3366cc"})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let g = guide(&app, &ctx); + set_pstate(&ctx, "cg-sel", vec![(0usize, 1usize), (1, 2)]); + let fill = |app: &VectorcraftApp| crate::panels::current_paints(app).0.color().map(|c| c.to_hex()); + let held = drag_from(&mut app, &ctx, ("cg-h", 1, 0), None, 1.0, false); + assert_eq!(held, Some(PanelDrag::paint(Paint::solid(g.colors[1]))), "the harmony color"); + let held = drag_from(&mut app, &ctx, ("cg-v", 0, 4), None, 2.0, false); + assert_eq!(held, Some(PanelDrag::paint(Paint::solid(g.grid[0][4]))), "the grabbed cell only, not the selected ones"); + assert_eq!(held.and_then(|d| d.color()), Some(g.grid[0][4])); + assert!(egui::DragAndDrop::payload::(&ctx).is_none(), "the release ends the drag"); + assert_eq!(fill(&app).as_deref(), Some("#3366cc"), "the drag paints no art"); + assert_eq!(base_color(&app).to_hex(), "#3366cc", "the base stays"); + assert_eq!(selected(&ctx), [(0, 1), (1, 2)], "the selected cells stay"); + } + + /// A variation of a guide limited to a library, dragged onto the Swatches panel, becomes one + /// swatch of the color the cell shows, in its own model in a CMYK document, as one undo step; the + /// same color dragged again is added under another name. + #[test] + fn a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("paint.setFill", json!({"color": "#c04020", "keepModel": true})).unwrap(); + app.run("ui.colorGuideLimit", json!({"library": "web-safe-216"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + guide_frame(&mut app, &ctx, vec![], 0.0, true, ("cg-h", 0usize)); + let g = guide(&app, &ctx); + let cell = g.grid[0][1]; + assert!(matches!(cell, Color::Rgb { .. }), "{cell:?}"); + assert!(library_hexes(&app, "web-safe-216").contains(&cell.to_hex()), "the cell shows a library color"); + let tile = |ctx: &egui::Context| ctx.read_response(egui::Id::unique(("swatch-tile", "Red"))).expect("the Red swatch is drawn").rect.center(); + let (count, undo) = { + let st = app.session.doc().unwrap(); + (st.doc.swatches_iter().count(), st.history.undo.len()) + }; + drag_from(&mut app, &ctx, ("cg-v", 0, 1), Some(tile(&ctx)), 1.0, true); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.swatches_iter().count(), count + 1, "{}", app.ui.status); + assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); + let first = st.doc.swatches.last().cloned().expect("a swatch"); + assert_eq!(first.paint, Paint::solid(cell), "the shown color, still RGB"); + assert!(!first.global, "a plain process color"); + drag_from(&mut app, &ctx, ("cg-v", 0, 1), Some(tile(&ctx)), 2.0, true); + let newest = app.session.doc().unwrap().doc.swatches.last().cloned().expect("a swatch"); + assert_eq!(newest.paint, Paint::solid(cell)); + assert_ne!(newest.name, first.name, "another name"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.swatches_iter().count(), count + 1, "Undo takes the second one off"); + } + #[test] fn save_colors_as_swatches_saves_each_selected_cell() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 2adff72887..2c36dabcb3 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -59,8 +59,8 @@ pub(super) enum Drop { /// `target` of its kind (neither None, Registration nor a tint swatch; see [`replaces`]), it /// gives that swatch its paint instead of moving. Move { names: Vec, target: Option, after: bool, with: Option }, - /// A paint from elsewhere (a Fill/Stroke proxy, a Recent Colors chip, the Gradient panel's - /// thumbnail) dropped on row `target` (or between rows) becomes a swatch; with Alt held + /// A paint from elsewhere (a Fill/Stroke proxy, a Recent Colors chip, a Color Guide color, the + /// Gradient panel's thumbnail) dropped on row `target` (or between rows) becomes a swatch; with Alt held /// (`replace`) it replaces swatch `target` when that is of its kind and neither Registration /// nor a tint swatch. New { paint: Paint, target: Option, replace: bool }, diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index 1a9c280f81..a3df5a4098 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -4,8 +4,8 @@ use super::{Paint, Rect, Response, Stroke, StrokeKind, Tokens, Ui, Vec2}; /// handler for all of them (`canvas::panel_drop`); a chip of a dragged paint follows the pointer. #[derive(Clone, Debug, PartialEq)] pub enum PanelDrag { - /// A paint: Swatches panel tiles, a Fill/Stroke proxy, a Recent Colors chip or the Gradient - /// panel's thumbnail. Art it is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; + /// A paint: Swatches panel tiles, a Fill/Stroke proxy, a Recent Colors chip, a Color Guide + /// color or the Gradient panel's thumbnail. Art it is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; /// null for a colour group, which paints nothing) through the active proxy's /// `paint.setFill`/`paint.setStroke`; the Gradient panel's ramp takes its colour as a stop; the /// Swatches panel moves `rows`, or makes a swatch of a paint dragged from elsewhere. `library`: @@ -69,8 +69,8 @@ pub struct SwatchRows { } impl PanelDrag { - /// `paint` dragged from a Fill/Stroke proxy, a Recent Colors chip or the Gradient panel's - /// thumbnail. A gradient carries no placement: it fits the art it lands on (freeform points are + /// `paint` dragged from a Fill/Stroke proxy, a Recent Colors chip, a Color Guide color or the + /// Gradient panel's thumbnail. A gradient carries no placement: it fits the art it lands on (freeform points are /// placed afresh there, coloured like the dragged ones). pub fn paint(mut paint: Paint) -> Self { if let Paint::Gradient(g) = &mut paint { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c66ced12c3..c623d375a0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1691,6 +1691,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. + - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. Windows, the BSDs and other browsers have no sampler yet; the button is gray there. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles, both ends of a vector drawn on the art and the start of a clicked one snap as other drawn points do (path segments, construction guides and View › Snap to Glyph's guides included) and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. From 33e7a8893b7fd3960aeb00c9b84d7923a272868d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:25:45 -0800 Subject: [PATCH 14/21] Cut: take the cut objects out of the selection in one pass Clear with `ids`, which Cut uses for the objects it copied, removed each id from the selection with its own scan of the selected objects. It now calls Selection::remove_all once, which gives the same selection. With 50,000 objects selected and all of them cut, the selection step takes 5.5 ms instead of 572 ms (release build, median of 7 wall-clock runs, measured while other builds were running). The new tests compare the result with removing each id in turn, including Undo and Redo, and an ignored benchmark times both. --- crates/doc/src/selection/tests.rs | 26 ++++ crates/engine/src/cmd/edit.rs | 4 +- crates/engine/tests/it/clear_commands.rs | 170 ++++++++++++++++++++++- docs/target-app-parity.md | 1 + 4 files changed, 197 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index b6090f8993..db8e6f930c 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,32 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +#[test] +fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() { + for kept in [false, true] { + let mut s = Selection::default(); + for i in 1..=4 { + s.add(NodeId(i)); + } + s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)])); + s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)])); + s.key_anchor = Some((NodeId(2), (0, 0))); + s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] }); + s.guides = vec![NodeId(10)]; + s.key_guide = Some(NodeId(10)); + let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] }; + let mut one_by_one = s.clone(); + for id in ids { + one_by_one.remove(id); + } + let mut all = s.clone(); + all.remove_all(ids); + assert_eq!(all, one_by_one); + assert_eq!(all.key_anchor.is_some(), kept); + assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10)))); + } +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f38e23bb5d..5ed472b39a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1189,9 +1189,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } if is_explicit { - for id in &ids { - sel.remove(*id); - } + sel.remove_all(ids.iter().copied()); sel.prune(d); } else { sel.clear(); diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index a50c70c18d..d4c0e5c320 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -1,7 +1,10 @@ //! Clear deletes its exact targets, including compound members (#786). +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + use serde_json::json; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{NodeId, Selection}; use vectorcraft_engine::{EngineError, Session}; fn compound() -> (Session, NodeId, NodeId, NodeId) { @@ -225,3 +228,168 @@ fn clear_explicit_ids_preserves_unrelated_selection() { assert!(s.active().unwrap().doc.node(r2).is_none()); assert!(s.active().unwrap().selection.is_empty()); } + +fn rectangles(s: &mut Session, n: i64) -> Vec { + (0..n) + .map(|i| { + NodeId(s.execute("shape.rectangle", &json!({"x": 10 + 40 * i, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()) + }) + .collect() +} + +/// Clear with `ids` leaves the selection that removing each id on its own leaves: the other objects +/// in their order, their anchor and segment picks, a key object or key anchor that is not removed, +/// and the selected guides. Undo brings back the document and the selection, and Redo the result. +#[test] +fn clear_explicit_ids_leaves_what_removing_each_id_leaves() { + for key_anchor in [false, true] { + for removed in [[1, 4, 1, 6], [0, 2, 2, 6]] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = rectangles(&mut s, 7); + s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap(); + let guide = s.active().unwrap().doc.ruler_guides()[0].id.unwrap(); + let sel = &mut s.active_mut().unwrap().selection; + // The seventh rectangle is not selected: Clear removes it from the document only. + sel.set(r[..6].iter().copied()); + sel.guides = vec![guide]; + for (id, anchor) in [(r[1], (0, 1)), (r[2], (0, 2)), (r[4], (0, 0)), (r[5], (0, 2))] { + sel.anchors.insert(id, BTreeSet::from([anchor, (0, 1)])); + } + for id in [r[2], r[5]] { + sel.segments.insert(id, BTreeSet::from([(0, 1)])); + } + if key_anchor { + sel.key_anchor = Some((r[4], (0, 0))); + } else { + sel.key = Some(r[4]); + } + let before = sel.clone(); + // The selection is one that `prune` keeps as it is, so Undo can restore it unchanged. + let mut pruned = before.clone(); + pruned.prune(&s.active().unwrap().doc); + assert_eq!(pruned, before); + let doc_before = s.active().unwrap().doc.clone(); + let ids: Vec = removed.iter().map(|i| r[*i]).collect(); + s.execute("edit.clear", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + let st = s.active().unwrap(); + let mut expected = before.clone(); + for id in &ids { + expected.remove(*id); + } + expected.prune(&st.doc); + assert_eq!(st.selection, expected, "key anchor {key_anchor}, removed {removed:?}"); + assert_eq!(st.selection.guides, vec![guide]); + assert!(ids.iter().all(|id| st.doc.node(*id).is_none())); + let doc_after = st.doc.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, doc_before); + assert_eq!(s.active().unwrap().selection, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, doc_after); + assert_eq!(s.active().unwrap().selection, expected); + } + } +} + +/// Cut of many selected objects puts each of them on the clipboard in paint order, removes them and +/// the selected guide, and leaves nothing selected. One Undo brings all of it back. +#[test] +fn cut_of_many_objects_takes_them_all_out_of_the_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = rectangles(&mut s, 40); + s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap(); + let guide = s.active().unwrap().doc.ruler_guides()[0].id.unwrap(); + let ids: Vec = r.iter().rev().map(|id| id.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let sel = &mut s.active_mut().unwrap().selection; + sel.guides = vec![guide]; + sel.key = Some(r[7]); + let before = sel.clone(); + let doc_before = s.active().unwrap().doc.clone(); + s.execute("edit.cut", &json!({})).unwrap(); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), r); + let st = s.active().unwrap(); + assert!(r.iter().all(|id| st.doc.node(*id).is_none())); + assert!(st.doc.ruler_guides().is_empty()); + assert_eq!(st.selection, Selection::default()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, doc_before); + assert_eq!(s.active().unwrap().selection, before); +} + +/// Timings of taking the cut objects out of a selection of 2,000, 20,000 and 50,000 objects: one +/// [`Selection::remove`] per id, as Clear with `ids` did before, against one +/// [`Selection::remove_all`], for all of the objects and for every other one. The two run in turn +/// in one process, 7 times each, and the two results are compared field by field. It also times +/// Cut of every object, with Undo between the runs. Ignored by default; it prints its timings and +/// sets no bound on them: +/// `cargo test --release -p vectorcraft-engine --test it clear_selection_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn clear_selection_perf() { + fn ms(d: &[Duration]) -> String { + d.iter().map(|d| format!("{:.3}", d.as_secs_f64() * 1000.0)).collect::>().join(" ") + } + fn median(d: &mut [Duration]) -> f64 { + d.sort(); + d[d.len() / 2].as_secs_f64() * 1000.0 + } + for n in [2_000_i64, 20_000, 50_000] { + let mut b = vectorcraft_testkit::fixtures::DocBuilder::new(4000.0, 4000.0); + let r: Vec = (0..n) + .map(|i| { + let (x, y) = ((i % 400) as f64 * 10.0, (i / 400) as f64 * 10.0); + b.rect(vectorcraft_geom::Rect::new(x, y, x + 8.0, y + 8.0), vectorcraft_color::Color::rgb(0.2, 0.4, 0.6), |_| {}) + }) + .collect(); + let doc = b.build(); + let mut sel = Selection::default(); + sel.set(r.iter().copied()); + for id in r.iter().step_by(10) { + sel.anchors.insert(*id, BTreeSet::from([(0, 0)])); + } + sel.key = Some(r[r.len() / 2]); + for (what, ids) in [("all", r.clone()), ("every other", r.iter().copied().step_by(2).collect::>())] { + let (mut each, mut all) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let mut one_by_one = sel.clone(); + let start = Instant::now(); + for id in &ids { + one_by_one.remove(*id); + } + one_by_one.prune(&doc); + each.push(start.elapsed()); + let mut at_once = sel.clone(); + let start = Instant::now(); + at_once.remove_all(ids.iter().copied()); + at_once.prune(&doc); + all.push(start.elapsed()); + assert_eq!(at_once, one_by_one); + } + eprintln!("clear_selection_perf: {n} selected, {what} ({} ids), remove each ms: {}", ids.len(), ms(&each)); + eprintln!("clear_selection_perf: {n} selected, {what} ({} ids), remove_all ms: {}", ids.len(), ms(&all)); + eprintln!( + "clear_selection_perf: {n} selected, {what}: median remove each {:.3} ms, remove_all {:.3} ms", + median(&mut each), + median(&mut all) + ); + } + let mut s = Session::new(); + let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&doc, false)); + s.execute("document.open", &json!({"name": "perf.vectorcraft", "dataBase64": data})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let mut cut = Vec::new(); + for _ in 0..7 { + let start = Instant::now(); + s.execute("edit.cut", &json!({})).unwrap(); + cut.push(start.elapsed()); + assert!(s.active().unwrap().selection.objects.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects.len(), r.len()); + } + eprintln!("clear_selection_perf: {n} selected, edit.cut ms: {}", ms(&cut)); + eprintln!("clear_selection_perf: {n} selected, edit.cut median {:.3} ms", median(&mut cut)); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af7974b880..1533627a82 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2086,6 +2086,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). + Cut, and Clear with `ids`, take the removed objects out of the selection in one pass over the selected objects. With 50,000 objects selected and all of them cut, that step takes 5.07 to 5.91 ms instead of 544 to 630 ms, with 20,000 it takes 1.75 to 1.87 ms instead of 91.7 to 97.2 ms, and with 2,000 it takes 0.120 to 0.148 ms instead of 0.940 to 0.955 ms (release build, 7 wall-clock runs of each, measured while other builds were running). In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). From b4f23804e17c566d19877ed625a6fddfaf8f7c83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:30:22 -0800 Subject: [PATCH 15/21] Symbols: New Symbol ignores a symbol dragged from another document A symbol drag from the Symbols panel keeps the document it started in. A drop on New Symbol after another document became active, even one with a symbol of the same name, makes no copy. --- crates/ui-egui/src/panels/symbols.rs | 59 ++++++++++++++++++++++++---- docs/target-app-parity.md | 2 +- 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e095e8b0bf..d0f024cb2d 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -316,7 +316,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); // Dragged onto the canvas, the symbol is placed there. - widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); + drag_symbol(ui, &resp, n, uid); if on(n) { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { @@ -342,7 +342,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(44.0, 44.0), Sense::click_and_drag()); - widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); + drag_symbol(ui, &resp, n, uid); chip(ui, &doc, &keys, r.shrink(2.0), n); let on = on(n); ui.painter().rect_stroke( @@ -403,7 +403,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0); // A symbol dragged from the panel and dropped on New Symbol is duplicated, with or without // art selected. - if let Some(name) = symbol_dropped(ui, &new, &names) { + if let Some(name) = symbol_dropped(ui, &new, &names, uid) { if let Err(e) = app.run("symbol.duplicate", json!({ "name": name })) { app.status(e); } @@ -493,12 +493,25 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The document symbol (one of `names`) dragged from the panel and released on `button` this -/// frame, if any; `button` is outlined while one is held over it. -fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String]) -> Option { +/// The panel state key of the document (`uid`) the symbol being dragged from the panel belongs to. +const DRAG_DOC: &str = "sym-drag-doc"; + +/// Make `resp` a drag source of the symbol `name` of the document `uid`, and keep `uid` while it +/// is dragged. +fn drag_symbol(ui: &Ui, resp: &egui::Response, name: &str, uid: Option) { + if resp.drag_started_by(egui::PointerButton::Primary) { + set_pstate(ui.ctx(), DRAG_DOC, uid); + } + widgets::drag_source(ui, resp, || PanelDrag::Symbol(name.to_string())); +} + +/// The symbol of the active document (`uid`, whose symbols are `names`) dragged from the panel and +/// released on `button` this frame, if any; `button` is outlined while one is held over it. A +/// symbol dragged from another document is ignored. +fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String], uid: Option) -> Option { let held = button.dnd_hover_payload::()?; let PanelDrag::Symbol(name) = &*held else { return None }; - if !names.contains(name) { + if !names.contains(name) || pstate::>(ui.ctx(), DRAG_DOC) != uid { return None; } widgets::drop_target_outline(ui, button.rect); @@ -1984,6 +1997,8 @@ mod tests { let leaf = instance_of(&app, "Leaf").expect("a Leaf instance"); let undo = app.session.active().unwrap().history.undo.len(); let ctx = egui::Context::default(); + // The payloads are set directly, as if dragged from this document's panel. + set_pstate(&ctx, DRAG_DOC, uid(&app)); let new = button_rect(&ctx, &mut app, "New Symbol"); let elsewhere = new.center() - vec2(0.0, 60.0); let cases = [ @@ -2004,6 +2019,36 @@ mod tests { } } + /// A symbol dragged from one document's panel and dropped on New Symbol after another document + /// with a symbol of the same name became active is duplicated in neither document, and the + /// button is not outlined for it. + #[test] + fn a_symbol_dragged_from_another_document_is_not_duplicated() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let tile = pos2(26.0, 26.0); + frame(&ctx, &mut app, vec![]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into()))); + // While Leaf is held, a new document with a Leaf of its own becomes active. + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": "Leaf"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let new = button_rect(&ctx, &mut app, "New Symbol"); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(new.center())], egui::Modifiers::NONE); + assert!(!outlined(&out, new), "not outlined"); + frame(&ctx, &mut app, vec![button(new.center(), false)]); + assert_eq!(symbols(&mut app), ["Leaf"], "no copy in the active document"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(dialog_kind(&app), None); + assert!(app.session.set_active(0)); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "no copy in the first document"); + } + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. fn thread_cpu_ns() -> Option { std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index efb325a5b6..a6aa8615b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1055,7 +1055,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art and keep no guides. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art or a name the document no longer has is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`. + - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`, `a_symbol_dragged_from_another_document_is_not_duplicated`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. From 7508f7cfe326d231fd4ab89687a4153f7cac5e34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:44:03 -0800 Subject: [PATCH 16/21] Graphic Styles: a style dropped on New Graphic Style is duplicated at the end of the list A graphic style dragged from the panel onto the New Graphic Style button runs Duplicate Graphic Style. The button takes the drop with no art selected and is outlined while a style is held over it. A dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted. graphicStyle.duplicate now adds the copy at the end of the list instead of right after its source, for the panel menu's command and the drop. The list's drop zone no longer reaches over the footer when the list is shorter than 220 pt, so a style released on New Graphic Style or Delete is not moved to the end of the list. --- crates/engine/src/cmd/style.rs | 12 +- crates/engine/src/tests/styles.rs | 26 ++++ crates/ui-egui/src/panels/graphic_styles.rs | 160 +++++++++++++++++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 5 files changed, 195 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 5780e65ed8..33c9ec67bb 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -53,7 +53,15 @@ pub fn specs() -> Vec { has_doc, style_delete ), - cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name} → {name}", has_doc, style_duplicate), + cmd!( + "graphicStyle.duplicate", + "Duplicate Graphic Style", + ["Window", "Graphic Styles"], + None, + "{name} a copy of the style at the end of the list, named ` copy` (` copy 2`… when that is taken); no object is linked to it → {name}", + has_doc, + style_duplicate + ), cmd!( query "graphicStyle.list", "List Graphic Styles", @@ -431,7 +439,7 @@ fn style_duplicate(s: &mut Session, p: &Value) -> Result { let pos = style_index(d, &name)?; let nm = unique_name(&format!("{name} copy"), |n| d.graphic_style(n).is_some()); let g = GraphicStyle { name: nm.clone(), id: d.next_graphic_style_id(), ..d.graphic_styles[pos].clone() }; - d.graphic_styles.insert(pos + 1, g); + d.graphic_styles.push(g); Ok(nm) })?; Ok(json!({"name": new})) diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index e460aeb890..6f0242c662 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -151,6 +151,32 @@ fn style_names_are_unique() { assert_ne!(style(&s, "Y copy").id, style(&s, "Y").id); } +#[test] +fn duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "graphicStyle.new", json!({"name": "S"})); + let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let before = names(&s); + // A style that is not last: the copy still goes after every other style. + let first = before[0].clone(); + assert_ne!(first, *before.last().unwrap()); + assert_eq!(run(&mut s, "graphicStyle.duplicate", json!({"name": first}))["name"], format!("{first} copy")); + let after = names(&s); + assert_eq!(after[..before.len()], before[..]); + assert_eq!(after.last(), Some(&format!("{first} copy"))); + let (src, copy) = (style(&s, &first), style(&s, &format!("{first} copy"))); + assert_eq!(copy.appearance, src.appearance); + assert_ne!(copy.id, src.id); + // Nothing is linked to the copy, and the source keeps its links. + assert!(linked(&mut s, &format!("{first} copy")).is_empty()); + assert_eq!(linked(&mut s, "S"), vec![a.0]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), before); + assert!(s.execute("graphicStyle.duplicate", &json!({"name": "nope"})).is_err()); + assert_eq!(names(&s), before); +} + /// Three rectangles: `a` (the source of style "S"), `b` and `c`, all linked to "S". fn linked_three(s: &mut Session) -> (NodeId, NodeId, NodeId) { let a = rect(s, 10.0); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index b99f9ec25b..e36eee0e9e 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,9 +3,10 @@ //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from //! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list, or applies it -//! to the art it is dropped on (`canvas::panel_drop`); art dragged off the canvas or the Appearance -//! panel's thumbnail dropped on the panel becomes a new style. Holding the right button on a style +//! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it +//! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a +//! copy of it and of the styles highlighted with it at the end of the list; art dragged off the +//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style. Holding the right button on a style //! shows it large, on the selected object when there is one. The Control bar's Style picker lists //! the same tiles ([`picker`]). Graphic style libraries open in library panels //! ([`GraphicStyleLibraries`]). @@ -566,7 +567,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { None => tiles(app, ui, &shown, &sel, &mut ev), } }); - let zone = ui.interact(out.inner_rect, ui.scope_id().with("gs-drop"), Sense::hover()); + // The drop zone is the part of the list on screen: when the list shrinks to its rows, + // `inner_rect` reaches past it over the footer's buttons. + let zone = ui.interact(out.inner_rect.intersect(ui.min_rect()), ui.scope_id().with("gs-drop"), Sense::hover()); zone_input(ui, &zone, &doc, &mut ev); }); act(app, ui, &shown, ev, false); @@ -584,9 +587,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("graphicStyle.breakLink", json!({})).ok(); } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); - if widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Graphic Style (Alt-click to name it)"), false, has_sel, 24.0).clicked() { + // A style dragged from the list can be dropped on it, also with no art selected: the + // button is enabled while one is held. + let new_enabled = has_sel || dragged_style(ui.ctx(), &doc).is_some(); + let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Graphic Style (Alt-click to name it)"), false, new_enabled, 24.0); + if new.clicked() { new_style(app, alt_held(ui)); } + drop_on_new(app, ui, &new, &sel); if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Graphic Style (Alt-click: without asking)"), false, !sel.is_empty(), 24.0) .clicked() { @@ -632,6 +640,55 @@ fn new_style(app: &mut VectorcraftApp, ask: bool) { } } +/// The style of `d` being dragged from the panel, if one is. +fn dragged_style(ctx: &egui::Context, d: &Document) -> Option { + match egui::DragAndDrop::payload::(ctx).as_deref() { + Some(PanelDrag::GraphicStyle(n)) if d.graphic_style(n).is_some() => Some(n.clone()), + _ => None, + } +} + +/// The styles a style dragged from the panel carries: every highlighted style (`sel`) in panel +/// order when the dragged style `name` is one of them, else that style alone. +fn carried(d: &Document, sel: &[String], name: &str) -> Vec { + if sel.iter().any(|s| s == name) { + d.graphic_styles.iter().filter(|g| sel.contains(&g.name)).map(|g| g.name.clone()).collect() + } else { + vec![name.to_string()] + } +} + +/// A style dragged onto New Graphic Style (`button`): the button is outlined while the style is +/// held over it, and on release the style, with the styles highlighted with it (`sel`), is +/// duplicated ([`duplicate`]). Other drags are left to their own targets. +fn drop_on_new(app: &mut VectorcraftApp, ui: &Ui, button: &Response, sel: &[String]) { + let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; + let Some(name) = dragged_style(ui.ctx(), &doc) else { return }; + if button.dnd_hover_payload::().is_none() { + return; + } + widgets::drop_target_outline(ui, button.rect); + if button.dnd_release_payload::().is_some() { + duplicate(app, ui.ctx(), &carried(&doc, sel, &name)); + } +} + +/// Duplicates `names` (`graphicStyle.duplicate`, each copy at the end of the list) in one undo +/// step and highlights the copies. A failure is shown in the status bar and changes nothing. +fn duplicate(app: &mut VectorcraftApp, ctx: &egui::Context, names: &[String]) { + let made = if let [name] = names { + app.run("graphicStyle.duplicate", json!({ "name": name })).map(|r| vec![r]) + } else { + let commands: Vec = names.iter().map(|n| json!({ "command": "graphicStyle.duplicate", "params": { "name": n } })).collect(); + app.run("command.batch", json!({ "label": "Duplicate Graphic Style", "commands": commands })) + .map(|r| r["results"].as_array().cloned().unwrap_or_default()) + }; + match made { + Ok(made) => set_pstate(ctx, "gs-sel", made.iter().filter_map(|r| r["name"].as_str().map(str::to_string)).collect::>()), + Err(e) => app.status(e), + } +} + /// Delete `names` after asking, or at once with `now` (Alt-click). fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { let params = json!({ "names": names }); @@ -1164,6 +1221,99 @@ mod tests { assert_eq!(d.node(rect).unwrap().extras().graphic_style, d.graphic_styles.last().map(|g| g.id)); } + /// A style dropped on New Graphic Style is duplicated at the end of the list, also with no art + /// selected; a highlighted style carries the other highlighted styles with it, in one undo step. + /// A style dropped on the Delete button is not moved in the list. + #[test] + fn a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events`: the center of the footer button labeled `label` + // and whether it is enabled. + let button = |app: &mut VectorcraftApp, events: Vec, label: &str| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("accessibility tree").nodes; + let (_, node) = nodes.iter().find(|(_, n)| n.label() == Some(label)).unwrap_or_else(|| panic!("{label}")); + let b = node.bounds().expect("visible button"); + (pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32), !node.is_disabled()) + }; + let new_button = |app: &mut VectorcraftApp, events: Vec| button(app, events, "New Graphic Style (Alt-click to name it)"); + let release = |at: egui::Pos2| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + vec![egui::Event::PointerMoved(at), up] + }; + let links = |app: &VectorcraftApp| { + app.session.active().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.extras().graphic_style).collect::>() + }; + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + for view in [View::SmallList, View::Thumbnail] { + app.ui.graphic_styles_view = view; + let n = names(&app); + let linked = links(&app); + // With no art selected the button is off until a style is held over it. + let (at, on) = new_button(&mut app, vec![]); + assert!(!on, "{view:?}: off with no art selected"); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(n[1].clone())); + let (_, on) = new_button(&mut app, vec![egui::Event::PointerMoved(at)]); + assert!(on, "{view:?}: on while a style is dragged"); + assert_eq!(names(&app), n, "{view:?}: holding it there changes nothing"); + // Released on it: a copy with the same look and a new id goes to the end, highlighted. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(n[1].clone())); + new_button(&mut app, release(at)); + let copy = format!("{} copy", n[1]); + assert_eq!(names(&app)[..n.len()], n[..], "{view:?}"); + assert_eq!(names(&app)[n.len()..], *std::slice::from_ref(©), "{view:?}"); + let d = doc(&app); + let (src, made) = (d.graphic_style(&n[1]).unwrap(), d.graphic_style(©).unwrap()); + assert_eq!(made.appearance, src.appearance); + assert_ne!(made.id, src.id); + assert_eq!(links(&app), linked, "{view:?}: no art is linked or unlinked"); + assert_eq!(selected(&ctx, &d), std::slice::from_ref(©)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}: one undo step"); + } + + // Two highlighted styles, one of them dragged: both are copied in panel order, in one step. + app.ui.graphic_styles_view = View::SmallList; + let n = names(&app); + let (at, _) = new_button(&mut app, vec![]); + set_pstate(&ctx, "gs-sel", vec![n[3].clone(), n[0].clone()]); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(n[3].clone())); + new_button(&mut app, release(at)); + let copies = [format!("{} copy", n[0]), format!("{} copy", n[3])]; + assert_eq!(names(&app)[n.len()..], copies); + assert_eq!(selected(&ctx, &doc(&app)), copies); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "the group's copies go in one undo step"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(names(&app)[n.len()..], copies); + app.run("edit.undo", json!({})).unwrap(); + + // A style that is not highlighted is copied alone. + set_pstate(&ctx, "gs-sel", vec![n[3].clone(), n[0].clone()]); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(n[2].clone())); + new_button(&mut app, release(at)); + assert_eq!(names(&app)[n.len()..], [format!("{} copy", n[2])]); + app.run("edit.undo", json!({})).unwrap(); + + // Other drags dropped on the button make nothing. + let rect = doc(&app).layers[0].children().unwrap()[0].id; + for payload in [PanelDrag::Art(vec![rect]), PanelDrag::Appearance(rect), PanelDrag::GraphicStyle("No such style".into())] { + egui::DragAndDrop::set_payload(&ctx, payload); + new_button(&mut app, release(at)); + assert_eq!(names(&app), n); + } + // A style dropped on the Delete button below the list is not moved in the list. + let (trash, _) = button(&mut app, vec![], "Delete Graphic Style (Alt-click: without asking)"); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(n[1].clone())); + button(&mut app, release(trash), "Delete Graphic Style (Alt-click: without asking)"); + assert_eq!(names(&app), n); + } + #[test] fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..7ea18fbb29 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4261,7 +4261,9 @@ style is applied to gets them at the same place relative to its own bounds. `graphicStyle.merge {names, name?}` adds a style stacking the fills, strokes and effects of two or more styles (each on top of the ones before it) with the first one's transparency; `graphicStyle.move {name, to}` reorders the -list (what dragging a style in the panel does). Override Character Color (`graphicStyle.setOptions +list (what dragging a style in the panel does). `graphicStyle.duplicate {name}` adds a copy of the style at the end +of the list, named ` copy` (` copy 2` and so on when that is taken), with no object linked to it; the +panel menu's Duplicate Graphic Style and a style dropped on the panel's New Graphic Style button run it. Override Character Color (`graphicStyle.setOptions {overrideCharColor}`, the preference `overrideCharColor`, on by default) makes a style applied to type replace its characters' fill and stroke with the style's fills and strokes; off, the characters keep their colour under them. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4bda6f151..d5b1378850 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1759,6 +1759,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. + A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named ` copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). From 5371149bf153547a6b38aa02ba6c25ce13b3a3ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:50:19 -0800 Subject: [PATCH 17/21] Select: anchorsMany updates the selected objects in one pass select.anchorsMany, which the Direct Selection and Group Selection marquees, the Lasso and Smart Pen send, checked and changed membership through Selection::contains, add and remove for each item, each a scan of the selected objects. It now keeps the selected objects in a map while the items run and writes them back once. The objects, their order, the anchors, segments, key, key anchor and the other selection fields come out as before, repeated ids and ids deselected and selected again included. Tests compare the result with the item-by-item loop for every mode, four starting selections and fifteen item lists, and bound the passes over the selected objects. An ignored benchmark times both loops on 2,000, 20,000 and 50,000 rectangles. --- crates/engine/src/cmd/select.rs | 184 +++++++++++++---- crates/engine/src/cmd/select/tests.rs | 286 ++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 427 insertions(+), 44 deletions(-) create mode 100644 crates/engine/src/cmd/select/tests.rs diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 791aa47f39..e91fe0ebf1 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_doc::{AnchorRef, Document, LockedArtboards, Node, NodeId, NodeKind, Selection}; use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; @@ -930,52 +930,145 @@ fn anchors_many(s: &mut Session, p: &Value) -> Result { None if bool_or(p, "add", false) => "add", None => "set", }; - s.select(|d, sel| { - if mode == "set" { - sel.clear(); - } - for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); - let all: BTreeSet<(usize, usize)> = - d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); - // Anything but a path is selected, toggled or deselected as a whole. - if all.is_empty() { - match mode { - "toggle" => sel.toggle(id), - "subtract" => sel.remove(id), - _ => sel.add(id), - } - continue; - } - // From the anchors selected now (all of them for a path selected as a whole). - let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), - None if sel.contains(id) => all.clone(), - None => BTreeSet::new(), - }; - let refs: BTreeSet<(usize, usize)> = refs.intersection(&all).copied().collect(); - let next: BTreeSet<(usize, usize)> = match mode { - "toggle" => now.symmetric_difference(&refs).copied().collect(), - "subtract" => now.difference(&refs).copied().collect(), - _ => now.union(&refs).copied().collect(), - }; - if next.is_empty() { - sel.remove(id); - continue; - } - sel.add(id); - if next.len() < all.len() { - sel.anchors.insert(id, next); - } else { - sel.anchors.remove(&id); - } - } - })?; + s.select(|d, sel| select_anchor_items(d, sel, items, mode))?; ok() } +/// `select.anchorsMany`'s change to `sel`: each item in order, with the selected objects kept in a +/// [`Members`] map while the items run, so that an item's membership check and change don't go +/// through `sel.objects`. +fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BTreeSet)>, mode: &str) { + if mode == "set" { + sel.clear(); + } + if items.is_empty() { + return; + } + let mut members = Members::of(sel); + for (id, refs) in items { + // A segment pick's endpoints aren't selected anchors: start from none of them. + let segment_pick = sel.segments.remove(&id).is_some(); + let all: BTreeSet = + d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); + // Anything but a path is selected, toggled or deselected as a whole. + if all.is_empty() { + match mode { + "toggle" => members.toggle(sel, id), + "subtract" => members.remove(sel, id), + _ => members.add(sel, id), + } + continue; + } + // From the anchors selected now (all of them for a path selected as a whole). + let now = match sel.partial(id) { + _ if segment_pick => BTreeSet::new(), + Some(a) => a.clone(), + None if members.contains(id) => all.clone(), + None => BTreeSet::new(), + }; + let refs: BTreeSet = refs.intersection(&all).copied().collect(); + let next: BTreeSet = match mode { + "toggle" => now.symmetric_difference(&refs).copied().collect(), + "subtract" => now.difference(&refs).copied().collect(), + _ => now.union(&refs).copied().collect(), + }; + if next.is_empty() { + members.remove(sel, id); + continue; + } + members.add(sel, id); + if next.len() < all.len() { + sel.anchors.insert(id, next); + } else { + sel.anchors.remove(&id); + } + } + members.finish(sel); +} + +/// The selected objects of a [`Selection`] while [`select_anchor_items`] changes them. Each +/// selected id maps to the activation that selected it: 0 for the objects selected before, and +/// a new number for each later [`Members::add`] of an unselected id, which `added` lists in order. +/// [`Members::finish`] writes them back to `objects`. +struct Members { + live: std::collections::HashMap, + added: Vec<(NodeId, usize)>, + removed: bool, +} + +impl Members { + fn of(sel: &Selection) -> Self { + count_objects_walk(); + Self { live: sel.objects.iter().map(|id| (*id, 0)).collect(), added: Vec::new(), removed: false } + } + + fn contains(&self, id: NodeId) -> bool { + self.live.contains_key(&id) + } + + /// [`Selection::add`]: clears what any selection change clears, and selects `id` at the end + /// unless it is selected. + fn add(&mut self, sel: &mut Selection, id: NodeId) { + sel.target = None; + sel.slices.clear(); + sel.symbol_part = None; + sel.on_path_member = None; + if let std::collections::hash_map::Entry::Vacant(e) = self.live.entry(id) { + let activation = self.added.len() + 1; + e.insert(activation); + self.added.push((id, activation)); + } + } + + /// [`Selection::remove`]: clears what any selection change clears, and deselects `id` with + /// its anchors, segments, and the key or key anchor it is. + fn remove(&mut self, sel: &mut Selection, id: NodeId) { + sel.target = None; + sel.slices.clear(); + sel.symbol_part = None; + sel.on_path_member = None; + if self.live.remove(&id).is_some() { + self.removed = true; + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + if sel.key == Some(id) { + sel.key = None; + } + if sel.key_anchor.is_some_and(|(k, _)| k == id) { + sel.key_anchor = None; + } + } + + /// [`Selection::toggle`]. + fn toggle(&mut self, sel: &mut Selection, id: NodeId) { + if self.contains(id) { self.remove(sel, id) } else { self.add(sel, id) } + } + + /// Writes the selected objects to `sel.objects`: the slots of the objects selected before and + /// still selected by that activation, in their order, then the ids selected since and still + /// selected by the activation that added them, in the order they were added. + fn finish(self, sel: &mut Selection) { + if self.removed { + count_objects_walk(); + sel.objects.retain(|id| self.live.get(id) == Some(&0)); + } + sel.objects.extend(self.added.into_iter().filter(|(id, n)| self.live.get(id) == Some(n)).map(|(id, _)| id)); + } +} + +#[cfg(test)] +thread_local! { + /// Tests: how many walks [`select_anchor_items`] made over the selected objects on this thread. + pub(crate) static OBJECTS_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Tests: count one walk over the selected objects. +fn count_objects_walk() { + #[cfg(test)] + OBJECTS_WALKS.set(OBJECTS_WALKS.get() + 1); +} + /// Select › Same › Fill/Stroke Color: is `a` the same colour as `b`? Tints of one global or spot /// swatch are, unless `tint` (General › Select Same Tint %) asks for the same tint too. pub(crate) fn same_paint(a: &Paint, b: &Paint, tint: bool) -> bool { @@ -1287,3 +1380,6 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result { s.select(|_, sel| sel.set(ids))?; Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/select/tests.rs b/crates/engine/src/cmd/select/tests.rs new file mode 100644 index 0000000000..74416ea09e --- /dev/null +++ b/crates/engine/src/cmd/select/tests.rs @@ -0,0 +1,286 @@ +//! `select.anchorsMany`'s item loop ([`select_anchor_items`]) against a loop that changes the +//! selection one item at a time through [`Selection::add`], [`Selection::remove`] and +//! [`Selection::toggle`]. + +use std::collections::{BTreeSet, HashSet}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use vectorcraft_color::Color; +use vectorcraft_doc::{AnchorRef, Document, NodeId, Selection, SymbolPart}; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +use super::{OBJECTS_WALKS, select_anchor_items}; + +type Items = Vec<(NodeId, BTreeSet)>; + +const MODES: [&str; 4] = ["set", "add", "toggle", "subtract"]; + +/// The item loop through `Selection`'s own methods, each of which goes through `objects`. +fn item_by_item(d: &Document, sel: &mut Selection, items: Items, mode: &str) { + if mode == "set" { + sel.clear(); + } + for (id, refs) in items { + let segment_pick = sel.segments.remove(&id).is_some(); + let all: BTreeSet = + d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); + if all.is_empty() { + match mode { + "toggle" => sel.toggle(id), + "subtract" => sel.remove(id), + _ => sel.add(id), + } + continue; + } + let now = match sel.partial(id) { + _ if segment_pick => BTreeSet::new(), + Some(a) => a.clone(), + None if sel.contains(id) => all.clone(), + None => BTreeSet::new(), + }; + let refs: BTreeSet = refs.intersection(&all).copied().collect(); + let next: BTreeSet = match mode { + "toggle" => now.symmetric_difference(&refs).copied().collect(), + "subtract" => now.difference(&refs).copied().collect(), + _ => now.union(&refs).copied().collect(), + }; + if next.is_empty() { + sel.remove(id); + continue; + } + sel.add(id); + if next.len() < all.len() { + sel.anchors.insert(id, next); + } else { + sel.anchors.remove(&id); + } + } +} + +/// A document with `n` four-anchor rectangles and, after them, a group of two more → the +/// rectangles' ids and the group's. +fn doc(n: usize) -> (Document, Vec, NodeId) { + let mut b = DocBuilder::new(2000.0, 2000.0); + let rects = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0); + b.rect(Rect::new(x, y, x + 5.0, y + 5.0), Color::rgb(0.2, 0.4, 0.6), |_| {}) + }) + .collect(); + let black = Color::rgb(0.0, 0.0, 0.0); + let kids = vec![b.rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), black), b.rect_node(Rect::new(2.0, 0.0, 3.0, 1.0), black)]; + let group = b.group(kids, false); + (b.build(), rects, group) +} + +fn anchors(refs: &[(usize, usize)]) -> BTreeSet { + refs.iter().copied().collect() +} + +/// A selection with every field set: rectangles 0 to 4 and the group, rectangle 2 listed twice, +/// partial anchors on 1 and 3, a segment pick on 4, rectangle 1 the key, a key anchor on 3, and a +/// target, slices, guides, a key guide, new art, a symbol part and an on-path member. +fn seeded(r: &[NodeId], group: NodeId) -> Selection { + let mut s = Selection { objects: vec![r[0], r[1], r[2], r[3], group, r[2], r[4]], ..Selection::default() }; + s.anchors.insert(r[1], anchors(&[(0, 0), (0, 1)])); + s.anchors.insert(r[3], anchors(&[(0, 2)])); + s.anchors.insert(r[4], anchors(&[(0, 0), (0, 1)])); + s.segments.insert(r[4], anchors(&[(0, 0)])); + s.key = Some(r[1]); + s.key_anchor = Some((r[3], (0, 2))); + s.target = Some(r[0]); + s.slices = vec![r[5]]; + s.guides = vec![r[6]]; + s.key_guide = Some(r[6]); + s.new_art = Arc::new(HashSet::from([r[2]])); + s.symbol_part = Some(SymbolPart { instance: r[0], path: vec![0] }); + s.on_path_member = Some(r[7]); + s +} + +/// Item lists with repeated ids, removals followed by additions, the group, anchors outside a +/// path, items that empty a path, and the empty list, then pseudo-random lists. +fn item_streams(r: &[NodeId], group: NodeId) -> Vec { + let all = [(0, 0), (0, 1), (0, 2), (0, 3)]; + let mut streams: Vec = vec![ + vec![], + vec![(r[2], anchors(&[(0, 0)]))], + vec![(r[2], anchors(&all)), (r[2], anchors(&all))], + vec![(r[2], anchors(&all)), (r[5], anchors(&[(0, 1)])), (r[2], anchors(&[(0, 3)]))], + vec![(group, anchors(&[])), (group, anchors(&[(0, 0)])), (group, anchors(&[]))], + vec![(r[6], anchors(&[(0, 0)])), (r[6], anchors(&[(0, 0)])), (r[7], anchors(&[(0, 9), (3, 0)]))], + vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&all)), (r[3], anchors(&all))], + vec![(r[4], anchors(&[])), (r[4], anchors(&[(0, 2)]))], + vec![(r[1], anchors(&all)), (r[3], anchors(&all)), (r[1], anchors(&[(0, 0)])), (r[3], anchors(&[(0, 2)]))], + vec![(r[8], anchors(&[(0, 0)])), (r[0], anchors(&all)), (r[8], anchors(&all)), (r[0], anchors(&[(0, 1)]))], + ]; + let pool: Vec = r.iter().copied().chain([group]).collect(); + let mut x: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + for len in [3, 9, 25, 80, 200] { + let items = (0..len) + .map(|_| { + let id = pool[(next() % pool.len() as u64) as usize]; + // Bits 0 to 4 of a draw pick anchors 0 to 3 and one past the end. + let bits = next(); + let refs = (0..5).filter(|i| (bits >> i) & 1 == 1).map(|i| (0, i)).collect(); + (id, refs) + }) + .collect(); + streams.push(items); + } + streams +} + +/// Starting selections: the seeded one, none, every rectangle whole, and every rectangle with +/// one anchor. +fn starts(r: &[NodeId], group: NodeId) -> Vec { + let mut whole = Selection::default(); + whole.set(r.iter().copied().chain([group])); + let mut partial = whole.clone(); + for id in r { + partial.anchors.insert(*id, anchors(&[(0, 1)])); + } + vec![seeded(r, group), Selection::default(), whole, partial] +} + +#[test] +fn anchor_items_do_what_the_item_by_item_loop_does() { + let (d, r, group) = doc(12); + for start in starts(&r, group) { + for items in item_streams(&r, group) { + for mode in MODES { + let mut expected = start.clone(); + item_by_item(&d, &mut expected, items.clone(), mode); + let mut got = start.clone(); + select_anchor_items(&d, &mut got, items.clone(), mode); + assert_eq!(got, expected, "mode {mode}, items {items:?}, from {start:?}"); + assert_eq!(got.new_art, expected.new_art); + } + } + } +} + +#[test] +fn a_path_deselected_and_selected_again_goes_last_without_its_key() { + let (d, r, group) = doc(12); + let all = anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]); + let mut s = seeded(&r, group); + // Toggling the selected anchors of 1 and 3 deselects them; toggling again selects them again. + let items = vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&[(0, 0)])), (r[3], all)]; + select_anchor_items(&d, &mut s, items, "toggle"); + assert_eq!(s.objects, [r[0], r[2], group, r[2], r[4], r[1], r[3]]); + assert_eq!(s.anchors.get(&r[1]), Some(&anchors(&[(0, 0)]))); + assert_eq!(s.anchors.get(&r[3]), None); + assert_eq!((s.key, s.key_anchor), (None, None)); +} + +/// Every rectangle with one anchor, as a Direct Selection marquee sends them. +fn marquee(r: &[NodeId]) -> Items { + r.iter().map(|id| (*id, anchors(&[(0, 0)]))).collect() +} + +/// Every rectangle with all four anchors, which deselects each in subtract mode. +fn every_anchor(r: &[NodeId]) -> Items { + r.iter().map(|id| (*id, anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]))).collect() +} + +#[test] +fn anchor_items_walk_the_selected_objects_at_most_twice() { + let (d, r, group) = doc(2000); + let mut all = Selection::default(); + all.set(r.iter().copied().chain([group])); + for (start, items, mode) in [ + (Selection::default(), marquee(&r), "set"), + (all.clone(), marquee(&r), "toggle"), + (all.clone(), every_anchor(&r), "subtract"), + (all.clone(), every_anchor(&r).into_iter().chain(marquee(&r)).collect(), "toggle"), + ] { + let mut s = start; + OBJECTS_WALKS.set(0); + select_anchor_items(&d, &mut s, items, mode); + let walks = OBJECTS_WALKS.get(); + assert!(walks <= 2, "{mode}: {walks} walks over the selected objects"); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = Instant::now(); + f(); + start.elapsed() + } + } +} + +fn ms(d: Duration) -> f64 { + d.as_secs_f64() * 1000.0 +} + +/// Timings of the item loop and the item-by-item loop on 2,000, 20,000 and 50,000 rectangles, run +/// in turn on clones of the same selection, 7 runs each. Ignored by default; it prints the median, +/// fastest and slowest run and sets no bound on them: +/// `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn anchor_items_perf() { + const RUNS: usize = 7; + eprintln!("anchor_items_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("anchor_items_perf: {:>6} {:<26} {:>28} {:>28}", "paths", "case", "item by item ms (min-max)", "item loop ms (min-max)"); + for n in [2_000, 20_000, 50_000] { + let (d, r, group) = doc(n); + let mut all = Selection::default(); + all.set(r.iter().copied().chain([group])); + for (case, start, items, mode) in [ + ("set, marquee", Selection::default(), marquee(&r), "set"), + ("add, marquee", Selection::default(), marquee(&r), "add"), + ("toggle, Select All", all.clone(), marquee(&r), "toggle"), + ("subtract every anchor", all.clone(), every_anchor(&r), "subtract"), + ] { + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..RUNS { + let (mut a, mut b) = (start.clone(), start.clone()); + let (ia, ib) = (items.clone(), items.clone()); + // The two loops take turns going first. + if run % 2 == 0 { + old.push(time(|| item_by_item(&d, &mut a, ia, mode))); + new.push(time(|| select_anchor_items(&d, &mut b, ib, mode))); + } else { + new.push(time(|| select_anchor_items(&d, &mut b, ib, mode))); + old.push(time(|| item_by_item(&d, &mut a, ia, mode))); + } + assert_eq!(a, b, "{n} paths, {case}"); + } + old.sort(); + new.sort(); + eprintln!( + "anchor_items_perf: {n:>6} {case:<26} {:>10.3} ({:>7.3}-{:>8.3}) {:>10.3} ({:>7.3}-{:>8.3})", + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..426ef5ec66 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1147,6 +1147,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The search for the segment of a path nearest a point, which Direct Selection runs to pick the cursor over a segment, skips each segment whose anchors and handles lie in a box farther from the point than a segment already measured, starting with a segment at the anchor nearest the point. The segment found is the same as before. Over a segment of an open path of 200,000 anchors, the cursor takes 51 ms instead of 59 ms in a release build (`cargo run --release -p vectorcraft-engine --example anchor_bench`). A Direct Selection marquee over part of a segment, with neither of its anchors inside, selects that segment as a click on it does (Shift toggles it), as [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describes (#4654). To find those segments, the marquee skips each segment whose anchors and handles all lie past one side of it and tests only the rest exactly, without building a path for each segment. It selects the same segments as before, and a marquee over a path of many anchors finishes sooner. + The Direct Selection and Group Selection marquees, the Lasso and Smart Pen select the anchors they reach (`select.anchorsMany`) with one pass over the selected objects, instead of one pass for each path. The objects, their order and the anchors selected are the same as before. Selecting one anchor on each of 50,000 rectangles takes a median of 29 ms of CPU time instead of 776 ms in a release build on Linux, and on 20,000 rectangles 10 ms instead of 124 ms; on 2,000 rectangles both take about 2 ms or less (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`). With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. From 139f881f811cb9d56a0c800b3367e8a77638afc8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:56:57 -0800 Subject: [PATCH 18/21] .ai import: a refused PDF part's error says why the editing data couldn't be read When the import refuses a file's PDF part and its editing data can't be read either, the error named only the PDF part. It now adds "its editing data couldn't be read either ()", as layers already do (crates/eps/src/import.rs). The reasons come from the editing data reader (a size limit, damaged compression) and from the private data streams (larger than 256 MB, another filter or decode parameters, damaged zlib data). A file without editing data, and an open with pages picked, layers off or the editing data off, keep the PDF part's error. Part of #4366. --- crates/engine/src/cmd/fileio/load.rs | 26 +++++--- .../engine/src/cmd/fileio/tests_aiimport.rs | 19 +++++- crates/engine/tests/import_fuzz.rs | 3 +- crates/pdf/src/lib.rs | 2 +- crates/pdf/src/pages.rs | 59 +++++++++++++------ crates/pdf/src/tests/import_layers.rs | 9 +++ crates/testkit/src/ai.rs | 15 ++++- 7 files changed, 100 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index e26d9a765a..ff0e14c40d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -286,16 +286,24 @@ fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option< /// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's /// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility -/// is read, its first note saying why: `None` when pages are picked, layers or the editing data -/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks. -fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec)> { +/// is read, its first note saying why. Else `e`: as it is when pages are picked, layers or the +/// editing data are off, or the file has no editing data, and followed by why when the file has +/// editing data that can't be read. Its type is outlines when `opts` asks. +fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<(Document, Vec)> { if opts.pages.is_some() || !opts.layers || !opts.editing_data { - return None; + return Err(e); + } + let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref()) + .and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose()); + match read { + Ok(Some((doc, warnings))) => { + let notes = + std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect(); + Ok(outlined_if_asked(doc, notes, opts)) + } + Ok(None) => Err(e), + Err(why) => Err(err(format!("{e}; its editing data couldn't be read either ({why})"))), } - let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?; - let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?; - let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect(); - Some(outlined_if_asked(doc, notes, opts)) } /// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the @@ -497,7 +505,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result .inspect(|_| editing_data = true), // A PDF part that can't be read (a stream the import refuses): the editing copy // alone where it reads, else the error. - Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), + Err(e) => without_pdf_part(bytes, opts, e).inspect(|_| editing_data = true), } })?; // The File Info of a file read from its pages or its editing copy. diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index d89dab774f..9d263c8c97 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -799,7 +799,7 @@ fn unread_pdf_part(e: &str) -> String { /// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from /// its editing data, with a first note saying why. Pages picked, layers off or the editing data -/// off keep the error, and so does editing data that can't be read. +/// off keep the error. Editing data that can't be read keeps it too, followed by why. #[test] fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() { let mut s = Session::new(); @@ -817,10 +817,25 @@ fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() { } for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) { let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string(); - assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}"); + let both = format!("{plain}; its editing data couldn't be read either (its zlib compression is damaged)"); + assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), both, "{name}"); + for p in [json!({"pages": "1"}), json!({"layers": false})] { + assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), plain, "{name}: {p}"); + } } } +/// #4366: editing data stored in a form the reader doesn't take, beside a PDF part that can't be +/// read, is named in the error. +#[test] +fn the_error_says_why_the_editing_data_couldnt_be_read() { + let mut s = Session::new(); + let file = ai::ai_with_private_streams(&compressed(&ai::sample_data()), ai::page_pdf(), REFUSED_CONTENT, "/Filter /Bogus "); + let plain = open(&mut s, "art.ai", &file, json!({"editingData": false})).unwrap_err().to_string(); + let e = open(&mut s, "art.ai", &file, json!({})).unwrap_err().to_string(); + assert_eq!(e, format!("{plain}; its editing data couldn't be read either (it is stored in a form that isn't read)")); +} + /// A file saved in units of 10 points (`/UserUnit 10`, as in /// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens /// from its editing data at its size in points. diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 6630f91a47..e8baa20a55 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4498,7 +4498,8 @@ proptest! { })?; match opened { Some(Ok(editing)) => prop_assert!(editing), - Some(Err(e)) => prop_assert_eq!(Some(e), page_error), + // The page's error, followed by why the editing data couldn't be read when it says. + Some(Err(e)) => prop_assert!(page_error.as_deref().is_some_and(|p| e == p || e.starts_with(&format!("{p}; its editing data couldn't be read either ("))), "{e}"), None => {} } } diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 9cef615783..a5f93a2a76 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -87,7 +87,7 @@ pub use import::{ pub use pages::reads_of; pub use pages::{ IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, - is_postscript, open_pdf, + is_postscript, open_pdf, read_illustrator_data_without_pdf_part, }; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 683a14d1c3..64e6217148 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -502,25 +502,42 @@ pub struct IllustratorData { /// objects, and only the private data streams are read, with the same limits. `None` when the /// file itself can't be opened, or as for [`illustrator_data`]. pub fn illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Option { - let pdf = open_structural_with_options(bytes, password, &open_options()).ok()?; - let data = private_data(&pdf)?; - let page = pdf.pages().first()?; + read_illustrator_data_without_pdf_part(bytes, password).ok().flatten() +} + +/// [`illustrator_data_without_pdf_part`], with why the private data can't be read: `Ok(None)` +/// when the file can't be opened or has no private data, `Err` (for a note, such as "it is larger +/// than 256 MB") when it has private data that can't be read. +pub fn read_illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Result, String> { + let Ok(pdf) = open_structural_with_options(bytes, password, &open_options()) else { return Ok(None) }; + let Some(data) = read_private_data(&pdf)? else { return Ok(None) }; + let Some(page) = pdf.pages().first() else { return Ok(None) }; // (The page transform is in points: it applies the `UserUnit`.) let trim = frame(page, CropTo::Trim).1; - Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) }) + Ok(Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) })) } /// The private data of `pdf`'s first page, as [`illustrator_data`] reads it. fn private_data(pdf: &Pdf) -> Option> { - let page = pdf.pages().first()?; - let private = page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")?; + read_private_data(pdf).ok().flatten() +} + +/// [`private_data`], with why a private data stream can't be read ([`inflated`]). +fn read_private_data(pdf: &Pdf) -> Result>, String> { + let Some(private) = pdf + .pages() + .first() + .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")) + else { + return Ok(None); + }; let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" }; let mut data = vec![]; for n in 1..=100_000u32 { let Some(stream) = private.get::>(format!("{key}{n}").as_bytes()) else { break }; - data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len())?); + data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len()).map_err(|why| why.to_string())?); } - (!data.is_empty()).then_some(data) + Ok((!data.is_empty()).then_some(data)) } /// Does the PDF's first page carry an editor's copy of the art: a PDF-compatible `.ai` @@ -538,10 +555,12 @@ fn has_private_data_keys(pdf: &Pdf) -> bool { /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's /// `decoded()`, which has no limit, so a stream of zeros can't grow to the size of the memory. Only a /// stream that is plain or only deflated is read (the private data is no other), without decode -/// parameters; else, or when it is larger once decoded, `None`. A filter the reader doesn't know -/// counts as another filter. -fn inflated(stream: &Stream<'_>, most: usize) -> Option> { +/// parameters; else, or when it is larger once decoded, `Err` with why. A filter the reader +/// doesn't know counts as another filter. +fn inflated(stream: &Stream<'_>, most: usize) -> Result, String> { use std::io::Read; + let unread = || "it is stored in a form that isn't read".to_string(); + let too_large = || format!("it is larger than {} MB", MAX_PRIVATE >> 20); let dict = stream.dict(); let named = |key: &[u8]| match dict.get::>(key) { None | Some(Object::Null(_)) => Some(0), @@ -555,24 +574,28 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Option> { Some(_) => true, }; if params(b"DecodeParms") || params(b"DP") { - return None; + return Err(unread()); } let filters = stream.filters(); // (The reader leaves out the filters it doesn't know.) - if named(b"Filter")?.max(named(b"F")?) != filters.len() { - return None; + if named(b"Filter").zip(named(b"F")).is_none_or(|(a, b)| a.max(b) != filters.len()) { + return Err(unread()); } let raw = stream.raw_data(); let mut out = vec![]; - let limit = u64::try_from(most).ok()?.checked_add(1)?; + let limit = u64::try_from(most).ok().and_then(|m| m.checked_add(1)).ok_or_else(too_large)?; match filters.as_slice() { [] if raw.len() <= most => out.extend_from_slice(&raw), + [] => return Err(too_large()), [craft_pdf::syntax::Filter::FlateDecode] => { - flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).ok()?; + flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).map_err(|_| "its zlib compression is damaged".to_string())?; } - _ => return None, + _ => return Err(unread()), } - (out.len() <= most).then_some(out) + if out.len() > most { + return Err(too_large()); + } + Ok(out) } /// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)? diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 86e1a88fb1..c0f9dfc970 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -446,7 +446,16 @@ fn private_data_reads_without_a_pdf_part_that_cant_be_read() { let pdf = pdf_with_catalog(std::slice::from_ref(&page), &[&first, &two], "", None); assert!(illustrator_data(&pdf, None).is_none(), "{odd}"); assert!(illustrator_data_without_pdf_part(&pdf, None).is_none(), "{odd}"); + let why = read_illustrator_data_without_pdf_part(&pdf, None); + assert_eq!(why, Err("it is stored in a form that isn't read".to_string()), "{odd}"); } + // Damaged zlib data, and a file without private data or that isn't a PDF. + let damaged = stream("/Filter /FlateDecode", "not zlib"); + let pdf = pdf_with_catalog(std::slice::from_ref(&page), &[&damaged, &two], "", None); + assert_eq!(read_illustrator_data_without_pdf_part(&pdf, None), Err("its zlib compression is damaged".to_string())); + let bare = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "")], &[], "", None); + assert_eq!(read_illustrator_data_without_pdf_part(&bare, None), Ok(None)); + assert_eq!(read_illustrator_data_without_pdf_part(b"not a pdf", None), Ok(None)); } /// Art in ordinary tags nested inside a layer's sequence goes to that layer; the group is kept diff --git a/crates/testkit/src/ai.rs b/crates/testkit/src/ai.rs index b560255e32..50af82d04c 100644 --- a/crates/testkit/src/ai.rs +++ b/crates/testkit/src/ai.rs @@ -338,6 +338,12 @@ pub fn ai_with_entries_and_content(private: &[u8], page: &str, entries: &str, co with_private(private, page, "AIPrivateData", entries, content) } +/// [`ai_with_content`] with `streams` more in the dictionary of each private data stream +/// (`/Filter /Bogus `). +pub fn ai_with_private_streams(private: &[u8], page: &str, content: &str, streams: &str) -> Vec { + with_private_streams(private, page, "AIPrivateData", "", content, streams) +} + /// A PDF saved with Illustrator's editing data: [`ai`]'s file with the two streams under /// `AIPDFPrivateData1` and `AIPDFPrivateData2`. These key names were seen in the PDF attached to /// #868, and nothing else of that file is used; ExifTool's PDF tag table lists them too @@ -354,6 +360,11 @@ pub fn pdf_with_content(private: &[u8], page: &str, content: &str) -> Vec { /// The file of [`ai`] and [`pdf`], with `private` in the streams `{key}1` and `{key}2`, `entries` /// more in the page dictionary and `content` more in its content stream's dictionary. fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: &str) -> Vec { + with_private_streams(private, page, key, entries, content, "") +} + +/// [`with_private`] with `streams` more in each private data stream's dictionary. +fn with_private_streams(private: &[u8], page: &str, key: &str, entries: &str, content: &str, streams: &str) -> Vec { let (first, second) = private.split_at(private.len() / 2); let stream = |part: &[u8], more: &str| { let mut s = format!("<< /Length {} {more}>>\nstream\n", part.len()).into_bytes(); @@ -371,8 +382,8 @@ fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: & ) .into_bytes(), stream(page.as_bytes(), content), - stream(first, ""), - stream(second, ""), + stream(first, streams), + stream(second, streams), ]; let mut out = b"%PDF-1.5\n".to_vec(); let mut offsets = vec![]; From 08c1684cd567dc263d60d447008472033eef9529 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:49:03 -0800 Subject: [PATCH 19/21] Symbols: hit tests keep measured symbol art boxes until the symbols change Every click, hover, Select Behind list and marquee made new symbol boxes and measured the art of each symbol its instances show again, and so did the locked-artboard check each of them made. With 20,000 instances of 8,000 different symbols a click took 27 to 33 ms. Hit tests now start from the art boxes, nesting depths and name index that earlier hit tests measured on the same thread, for the last two sets of symbols. The locked-artboard check of a hit test starts from the same art boxes, and what it measures is kept with the rest. The boxes are measured again when a symbol's name or art, the 9-slice guides or the inputs of clipping-path effects change. The kept list holds a weak pointer to each symbol's art, so it does not keep a closed document's art alive, and art changed in place no longer matches. Art boxes of symbols whose art holds 9-slice instances are measured on each call, as before. --- crates/doc/src/document.rs | 16 +- crates/doc/src/hit.rs | 30 ++- crates/doc/src/symbols.rs | 374 ++++++++++++++++++++++++++++++++++++- 3 files changed, 407 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 54130788e1..f4a307cd5c 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -752,6 +752,18 @@ impl Document { /// [`Document::locked_artboards`] leaving out artboard `index`. pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> { + self.locks_except(index, false) + } + + /// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept + /// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too + /// ([`crate::symbols::KeptBoxes::keeping`]). + pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> { + self.locks_except(usize::MAX, true) + } + + /// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes. + fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> { // Art flush with an edge from outside can overlap it by a rounding error, as in // `art_bounds_on` (#1295). let rects: Vec = @@ -770,7 +782,9 @@ impl Document { if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) { objects(layer, &mut pattern_art); } - LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() } + // Nothing is measured without a locked artboard. + let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() }; + LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() } } /// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none. diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index ab571e50b2..3b415ef1ed 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -451,8 +451,9 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip /// outline, as a click there hits it. pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option { let _walk = ArtWalk::open(); - let symbols = doc.symbol_boxes(); - let locks = doc.locked_artboards(); + // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let locks = doc.locked_artboards_kept(); + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); selected.iter().rev().copied().find(|&id| { let Some(chain) = doc.ancestry(id) else { return false }; let nodes: Vec<&Node> = chain.iter().filter_map(|a| doc.node(*a)).collect(); @@ -520,7 +521,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option Vec { let _walk = ArtWalk::open(); - let symbols = doc.symbol_boxes(); + let symbols = doc.kept_symbol_boxes(); let mut out = Vec::new(); if let Some(scope) = opt.scope && let Some(isolated) = doc.node(scope) @@ -725,7 +727,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); h }; - let locks = doc.locked_artboards(); + let locks = doc.locked_artboards_kept(); let on_locked = |id: NodeId| { editable_only && !locks.is_empty() @@ -733,7 +735,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && doc.node(id).is_some_and(|n| locks.holds(n)) }; let skip = &|id| skip(id) || on_locked(id); - let symbols = doc.symbol_boxes(); + // `locks` copies the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); // Isolation mode: only what is inside the isolated container hits. The art around it is // locked, and clicks pass through it (#833). if editable_only @@ -801,6 +804,12 @@ pub fn set_clip_region(f: ClipRegion) { let _ = CLIP_REGION.set(f); } +/// What the regions of clipping paths with live effects depend on outside the document: the +/// registered [`LiveInputs`] now, and whether a [`ClipRegion`] is registered. +pub(crate) fn clip_region_inputs() -> (u64, bool) { + (live_inputs(), CLIP_REGION.get().is_some()) +} + /// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { @@ -1620,7 +1629,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { let _walk = ArtWalk::open(); let art = InstanceArt::of(doc, inst)?; - let symbols = doc.symbol_boxes(); + let symbols = doc.kept_symbol_boxes(); let mut path = vec![]; let outline = opt.outline || below_preview_off(doc, inst, opt.scope); let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false }; @@ -2042,7 +2051,9 @@ fn previews_off(n: &Node) -> bool { fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let _walk = ArtWalk::open(); let mut out = Vec::new(); - let symbols = doc.symbol_boxes(); + // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let locks = doc.locked_artboards_kept(); + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); // The objects the marquee may touch ([`Top`]). let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the @@ -2284,7 +2295,6 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } } } - let locks = doc.locked_artboards(); for (t, r, outline, edge, drawn) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 99a65ae1f7..a1d34e6adb 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> { consulted: RefCell>>, } +/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and +/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and +/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]). +/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's +/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else +/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art +/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`. +struct KeptKey { + symbols: Vec<(String, std::sync::Weak)>, + guides: Option, + inputs: (u64, bool), +} + +impl KeptKey { + /// The key of the document's 9-slice guides. + const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE; + + fn of(doc: &Document, inputs: (u64, bool)) -> Self { + KeptKey { + symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), + guides: doc.unknown.get(Self::GUIDES).cloned(), + inputs, + } + } + + /// Does this describe `doc`'s symbols as they are now, with inputs `inputs`? + fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool { + self.inputs == inputs + && self.symbols.len() == doc.symbols.len() + && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name) + && self.guides.as_ref() == doc.unknown.get(Self::GUIDES) + } + + fn same(&self, other: &KeptKey) -> bool { + self.inputs == other.inputs + && self.symbols.len() == other.symbols.len() + && self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m) + && self.guides == other.guides + } +} + +/// Art boxes, nesting depths and the name index measured by boxes made by +/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols. +struct Kept { + key: KeptKey, + names: Option>, + measured: HashMap>, + depths: HashMap>, +} + +/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread: +/// clicks can alternate between two open documents. +const KEPT_SETS: usize = 2; + +thread_local! { + /// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first. + static KEPT: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the +/// next ones when dropped. +pub(crate) struct KeptBoxes<'a> { + boxes: SymbolBoxes<'a>, + /// What the measurements depend on, under which they are kept. + key: Option, + /// Other boxes of the same document whose measurements are kept with these + /// ([`Self::keeping`]). + also: Option<&'a SymbolBoxes<'a>>, +} + +impl<'a> std::ops::Deref for KeptBoxes<'a> { + type Target = SymbolBoxes<'a>; + + fn deref(&self) -> &SymbolBoxes<'a> { + &self.boxes + } +} + +impl<'a> KeptBoxes<'a> { + /// These boxes, which also keep the art boxes and nesting depths `other` has measured when + /// dropped. `other` measures the same document, as the boxes of + /// [`Document::locked_artboards_kept`] do. + pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self { + self.also = Some(other); + self + } +} + +impl Drop for KeptBoxes<'_> { + /// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive + /// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice + /// guides are left out: measuring them places art within a budget the boxes share + /// ([`SymbolBoxes::sliced_visual`]). + fn drop(&mut self) { + let Some(key) = self.key.take() else { return }; + let b = &self.boxes; + let mut measured = b.measured.take(); + let mut depths = b.depths.take(); + if let Some(other) = self.also { + for (name, a) in other.measured.borrow().iter() { + measured.entry(name.clone()).or_insert(*a); + } + for (name, d) in other.depths.borrow().iter() { + depths.entry(name.clone()).or_insert(*d); + } + } + measured.retain(|_, a| a.is_none_or(|a| !a.sliced)); + let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths }; + // Nothing is kept while the thread ends or the list is in use. + let _ = KEPT.try_with(|k| { + if let Ok(mut k) = k.try_borrow_mut() { + if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) { + let other = k.remove(i); + kept.names = kept.names.or(other.names); + for (name, a) in other.measured { + kept.measured.entry(name).or_insert(a); + } + for (name, d) in other.depths { + kept.depths.entry(name).or_insert(d); + } + } + k.insert(0, kept); + k.truncate(KEPT_SETS); + } + }); + } +} + impl Document { /// [`SymbolBoxes`] for this document's symbols, none measured yet. pub fn symbol_boxes(&self) -> SymbolBoxes<'_> { @@ -131,6 +259,56 @@ impl Document { } } + /// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured + /// by the last such boxes made on this thread for the same symbols, and keep theirs for the next + /// ones when dropped. The measurements are made again when a symbol's name or art, the symbols' + /// 9-slice guides, or the inputs of the live geometry effects of clipping paths have + /// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept. + pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> { + self.kept_boxes(false) + } + + /// [`Self::symbol_boxes`] that start with a copy of the measurements + /// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves. + pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> { + let mut kept = self.kept_boxes(true); + kept.key = None; + std::mem::replace(&mut kept.boxes, self.symbol_boxes()) + } + + /// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them. + fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> { + let mut boxes = self.symbol_boxes(); + let inputs = crate::hit::clip_region_inputs(); + let found = KEPT + .try_with(|k| { + let mut k = k.try_borrow_mut().ok()?; + let i = k.iter().position(|e| e.key.is_of(self, inputs))?; + if copy { + let e = k.get(i)?; + let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs }; + Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() }) + } else { + Some(k.remove(i)) + } + }) + .ok() + .flatten(); + let key = match found { + Some(e) => { + if let Some(names) = e.names { + // The boxes were just made, so no index is set yet. + let _ = boxes.names.set(names); + } + *boxes.measured.get_mut() = e.measured; + *boxes.depths.get_mut() = e.depths; + e.key + } + None => KeptKey::of(self, inputs), + }; + KeptBoxes { boxes, key: Some(key), also: None } + } + /// Each symbol name of this document → the index of the first symbol of that name (the one a /// name finds). pub(crate) fn symbol_names(&self) -> SymbolNames { @@ -148,6 +326,8 @@ impl Document { thread_local! { /// How many symbols [`Document::symbol_names`] has read on this thread. pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; + /// How many art boxes [`SymbolBoxes::art`] has measured on this thread. + static ART_BOXES_MEASURED: Cell = const { Cell::new(0) }; } impl<'a> SymbolBoxes<'a> { @@ -218,6 +398,8 @@ impl<'a> SymbolBoxes<'a> { pub(crate) fn art(&self, name: &str) -> Option { let cached = self.measured.borrow().get(name).copied(); let b = cached.unwrap_or_else(|| { + #[cfg(test)] + ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1)); let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); self.measured.borrow_mut().insert(name.to_string(), b); b @@ -584,10 +766,10 @@ fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { #[cfg(test)] mod tests { use vectorcraft_color::{Color, Paint}; - use vectorcraft_geom::shapes; + use vectorcraft_geom::{Point, shapes}; use super::*; - use crate::{Appearance, Symbol}; + use crate::{Appearance, NodeId, Symbol}; /// A rectangle filled black, with a `stroke` pt black stroke (0: none). fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node { @@ -911,4 +1093,192 @@ mod tests { assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0); assert_eq!(runs.get(), MAX_REACHES + 2); } + + /// How many art boxes `f` measures on this thread. + fn art_boxes_measured(f: impl FnOnce()) -> usize { + let before = ART_BOXES_MEASURED.with(Cell::get); + f(); + ART_BOXES_MEASURED.with(Cell::get) - before + } + + /// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an + /// instance of each at (40 i + 20, 20). + fn ten_symbols() -> Document { + let mut d = Document::new(400.0, 100.0); + let layer = d.layers.first().map(|l| l.id); + for i in 0..10 { + let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0); + symbol(&mut d, &format!("S {i}"), vec![square]); + let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0))); + d.insert(layer, usize::MAX, at).unwrap(); + } + d + } + + #[test] + fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit"); + assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1); + } + assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10); + }; + let first = art_boxes_measured(clicks); + assert_eq!(first, 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_measure_a_symbol_again_after_it_changes() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + // Past the square of "S 1" at (60, 20). + let past = Point::new(71.0, 20.0); + assert!(hit::hit_test(&d, past, HitOptions::default()).is_none()); + // The art grows 3 times in place: no other copy of it is held in the document. + Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false); + let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit")); + assert!(measured > 0); + // New art for "S 2", 40 wide. + let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0); + d.symbols[2].art = Arc::new(wide); + assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit"); + // "S 3" renamed: its instance now shows the 20 × 20 square. + d.symbols[3].name = "Renamed".into(); + assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + } + + /// What clicks on a grid over `d` hit, and what a marquee over it selects. + fn hits(d: &Document) -> (Vec>>, Vec) { + use crate::hit::{self, HitOptions}; + let mut clicks = Vec::new(); + for y in (0..400).step_by(5) { + for x in (0..400).step_by(5) { + let p = Point::new(f64::from(x), f64::from(y)); + clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry)); + } + } + (clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false)) + } + + /// [`hits`] with no measurements kept from earlier hit tests. + fn fresh_hits(d: &Document) -> (Vec>>, Vec) { + KEPT.with_borrow_mut(Vec::clear); + hits(d) + } + + /// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is + /// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without + /// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150. + fn sliced_holder(guides: bool) -> Document { + let mut d = Document::new(400.0, 400.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + if guides { + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + } + let panel = instance(&mut d, "Panel", Affine::IDENTITY); + symbol(&mut d, "Holder", vec![panel]); + let layer = d.layers.first().map(|l| l.id); + let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0)); + d.insert(layer, usize::MAX, holder).unwrap(); + d + } + + #[test] + fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() { + use crate::hit::{self, HitOptions}; + let mut d = sliced_holder(false); + // Left of the frame, where only the bar placed through the guides draws. + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_none()); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + let before = hits(&d); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] })); + let after = hits(&d); + assert_ne!(after, before, "the size moves the guides"); + assert_eq!(after, fresh_hits(&d)); + } + + #[test] + fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() { + use crate::hit::{self, HitOptions}; + let d = sliced_holder(true); + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()); + // The holder's art holds an instance of a symbol with guides; the panel's art holds none. + KEPT.with_borrow(|k| { + let measured = &k[0].measured; + assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys()); + }); + let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some())); + assert!(again > 0, "the holder's art box measured again"); + } + + #[test] + fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() { + let d = ten_symbols(); + let key = KeptKey::of(&d, (0, false)); + assert!(key.is_of(&d, (0, false))); + assert!(!key.is_of(&d, (1, false)), "live inputs changed"); + assert!(!key.is_of(&d, (0, true)), "a clip region registered"); + } + + #[test] + fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard"); + assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty()); + } + }; + assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + // A marquee passes over the objects on a locked artboard without measuring them itself: only + // its locks measure their art. + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty()); + assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_hold_no_symbol_art() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default())); + assert!(KEPT.with_borrow(|k| !k.is_empty())); + assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art"); + } + + #[test] + fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() { + use crate::hit::{self, HitOptions}; + let docs = [ten_symbols(), ten_symbols(), ten_symbols()]; + let p = Point::new(20.0, 20.0); + for d in &docs { + drop(hit::hit_test(d, p, HitOptions::default())); + } + assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS); + // The last two are kept, the first is measured again. + let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default())))); + assert_eq!(kept, 0); + let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default()))); + assert!(first > 0); + } } From a187449f7cf343c20c2087d25df5aff345267a56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 08:02:35 -0800 Subject: [PATCH 20/21] Legacy .ai: gradient and spot color names are numbered with a set and a counter per name Saving a legacy .ai file numbered a gradient definition whose name was taken by searching every definition written so far for each number it tried, so a document with many distinct gradients without a swatch name spent time cubic in their count naming them. Spot color names were numbered the same way. Both now keep the names given in a set and, for each name, the number to try next. Names are never given back, so every number below that counter is still taken, and the file is the same as before: the first free "Name 2", "Name 3" and so on, with equal gradients sharing a definition. - New tests compare the counters with a search of the names given over 3,000 names, and the whole written file both ways for colliding gradient and spot color names. - An ignored timing test writes 1,504 gradient definitions: in release on Linux, the median of 7 runs took 23 ms of thread CPU time against 1,163 ms for the search. --- crates/eps/src/legacy_ai/tests.rs | 147 +++++++++++++++++++++++++++++ crates/eps/src/legacy_ai/writer.rs | 67 ++++++++++--- 2 files changed, 201 insertions(+), 13 deletions(-) diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index b35eb94fc0..d8a81461cb 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1413,6 +1413,153 @@ fn names_outside_windows_1252_are_replaced_and_kept_apart() { assert_eq!(inks(&read), want); } +/// `doc` written with [`Numbered::take`](super::writer::Numbered::take) numbering names by its +/// counters (`scanned` false) or by searching the names given for each number it tries. +fn export_numbering(doc: &Document, scanned: bool) -> LegacyAiOutput { + let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() }; + super::writer::SCANNED_NAMES.with(|s| s.set(scanned)); + let out = export_legacy_ai(doc, &o); + super::writer::SCANNED_NAMES.with(|s| s.set(false)); + out.unwrap() +} + +/// A linear gradient from `color` to white, named `swatch`. +fn gradient_from(color: Color, swatch: Option<&str>) -> Paint { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, color), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]); + let mut paint = GradientPaint::new(g); + paint.swatch = swatch.map(String::from); + Paint::Gradient(Box::new(paint)) +} + +/// A name the counters give is the first free `name 2`, `name 3`… for every order of names, those +/// already numbered (`Sky 2`, `Gradient 2 2`) and the empty name included. +#[test] +fn numbered_names_are_the_first_free_number() { + let bases = ["Gradient", "Gradient 2", "Gradient 3", "Gradient 2 2", "Sky", "Sky 2", "Sky 4", "?", "? 2", ""]; + let mut seed = 7u32; + let order: Vec<&str> = (0..3000) + .map(|_| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + bases[(seed >> 16) as usize % bases.len()] + }) + .collect(); + let names = |scanned: bool| { + super::writer::SCANNED_NAMES.with(|s| s.set(scanned)); + let mut numbered = super::writer::Numbered::default(); + let names: Vec = order.iter().map(|b| numbered.take((*b).to_string())).collect(); + super::writer::SCANNED_NAMES.with(|s| s.set(false)); + names + }; + let (counted, scanned) = (names(false), names(true)); + for (i, (c, s)) in counted.iter().zip(&scanned).enumerate() { + assert_eq!(c, s, "name {i}, {:?}", order[i]); + } + let given: std::collections::HashSet<&String> = counted.iter().collect(); + assert_eq!(given.len(), counted.len(), "every name is given once"); +} + +/// Gradient definitions and spot colors whose names collide are numbered as the file has always +/// numbered them: a gradient's swatch name or `Gradient`, then the first free number, with equal +/// gradients sharing a definition. The whole file is the same either way. +#[test] +fn colliding_gradient_and_spot_names_are_numbered_as_before() { + let mut doc = spots_and_gradient(&["\u{8d64}", "?", "\u{9752}", "? 2"], "Gradient 3"); + let layer = doc.layers[0].id; + let swatches = [None, None, Some("Gradient"), None, Some("\u{6e10}"), Some("?"), None, Some("Gradient 2"), Some("")]; + for (i, swatch) in swatches.into_iter().enumerate() { + let c = i as f32 / 10.0; + for repeat in 0..2 { + let x = 10.0 + 15.0 * i as f64; + let r = Rect::new(x, 60.0 + 15.0 * f64::from(repeat), x + 10.0, 70.0 + 15.0 * f64::from(repeat)); + let n = shape(&mut doc, shapes::rectangle(r), gradient_from(Color::cmyk(c, 1.0 - c, 0.5, 0.0), swatch), Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + } + let out = export_numbering(&doc, false); + let before = export_numbering(&doc, true); + let text = String::from_utf8(out.bytes).unwrap(); + assert_eq!(text, String::from_utf8(before.bytes).unwrap()); + assert_eq!(out.warnings, before.warnings); + let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect(); + let want = [ + "(Gradient 3)", + "(Gradient)", + "(Gradient 2)", + "(Gradient 4)", + "(Gradient 5)", + "(?)", + "(? 2)", + "(Gradient 6)", + "(Gradient 2 2)", + "(Gradient 7)", + ]; + assert_eq!(defined, want); + for name in want { + assert_eq!(text.matches(&format!("1 {name} ")).count(), if name == "(Gradient 3)" { 1 } else { 2 }, "{name}"); + } + assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}"); +} + +/// The time this thread has run, and how it was measured. +fn thread_time() -> (std::time::Duration, &'static str) { + if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + return (std::time::Duration::from_nanos(ns), "thread CPU time"); + } + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time") +} + +/// The time to write 1,500 objects that each have a gradient of their own and no swatch name, +/// with a few named ones that collide, numbering names by counters and by searching the names +/// given: the median of 7 runs of each, alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture many_unnamed_gradients`. +#[test] +#[ignore = "timing"] +fn many_unnamed_gradients_are_named_quickly() { + let mut doc = Document::new(1000.0, 1000.0); + let layer = doc.layers[0].id; + let count = 1500u16; + for i in 0..count + 4 { + let swatch = match i { + 0 => Some("Gradient 3"), + 1 => Some("Gradient"), + 2 | 3 => Some("Sky"), + _ => None, + }; + let t = f32::from(i) / f32::from(count + 4); + let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40) * 25.0); + let paint = gradient_from(Color::rgb(t, 1.0 - t, (t * 7.0).fract()), swatch); + let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let mut times = [vec![], vec![]]; + let mut files: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [false, true].into_iter().enumerate() { + let (start, h) = thread_time(); + let out = export_numbering(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + let defs = String::from_utf8_lossy(&out.bytes).lines().filter(|l| l.ends_with(" Bd")).count(); + assert_eq!(defs, usize::from(count) + 4); + files[k].get_or_insert(out.bytes); + } + } + assert_eq!(files[0], files[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("{} gradient definitions, median of 7 runs ({how}):", count + 4); + println!("| naming | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["counters", "search of the names given"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// #6502: the legacy writer gives Yellow, Magenta and Cyan (presets 4, 5 and 6) the file's /// indexes 6, 4 and 5, and they open as the same presets. #[test] diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 0551d1821c..536940b9f6 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -15,6 +15,9 @@ use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPP thread_local! { /// How many times [`Writer::coverage`] has worked out an image's coverage on this thread. pub(super) static COVERAGE_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`Numbered::take`] numbers names on this thread by searching the names given so + /// far, one number at a time, for each number it tries. + pub(super) static SCANNED_NAMES: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel. @@ -66,6 +69,10 @@ pub(super) struct Writer<'a> { whole_images: std::collections::HashMap>>, /// Writing a graph's art with its records: a graph inside it is written as its art. in_graph: bool, + /// The names of [`Self::gradients`]. + gradient_names: Numbered, + /// The names spot colors are written with ([`Self::spot`]). + spot_written: Numbered, } impl<'a> Writer<'a> { @@ -94,6 +101,8 @@ impl<'a> Writer<'a> { last_coverage: None, whole_images: std::collections::HashMap::new(), in_graph: false, + gradient_names: Numbered::default(), + spot_written: Numbered::default(), } } @@ -155,12 +164,7 @@ impl<'a> Writer<'a> { Some((_, w)) => w.clone(), None => { let base = self.latin_name(name, TITLE_AND_COLOR_NAMES); - let mut written = base.clone(); - let mut i = 1; - while self.spot_names.iter().any(|(_, w)| *w == written) { - i += 1; - written = format!("{base} {i}"); - } + let written = self.spot_written.take(base); self.spot_names.push((name.to_string(), written.clone())); written } @@ -823,14 +827,8 @@ impl<'a> Writer<'a> { if let Some((name, _)) = self.gradients.iter().find(|(_, d)| d == g) { return name.clone(); } - let taken = |n: &str, defs: &[(String, Gradient)]| defs.iter().any(|(m, _)| m == n); let base = self.latin_name(swatch.filter(|s| !s.is_empty()).unwrap_or("Gradient"), TITLE_AND_COLOR_NAMES); - let mut name = base.clone(); - let mut i = 1; - while taken(&name, &self.gradients) { - i += 1; - name = format!("{base} {i}"); - } + let name = self.gradient_names.take(base); self.gradients.push((name.clone(), g.clone())); name } @@ -1244,3 +1242,46 @@ impl<'a> Writer<'a> { s.push_str("%AI5_EndRaster\nF\n"); } } + +/// Names kept apart: a name already given is numbered, as the first free `name 2`, `name 3`… +#[derive(Default)] +pub(super) struct Numbered { + taken: std::collections::HashSet, + /// The number to try first for each name already given, after the numbers it was given. + next: std::collections::HashMap, + /// The names given, in order, for [`SCANNED_NAMES`]. + #[cfg(test)] + given: Vec, +} + +impl Numbered { + /// `base`, or the first free `base 2`, `base 3`… when `base` is taken; it is then taken. + pub(super) fn take(&mut self, base: String) -> String { + #[cfg(test)] + if SCANNED_NAMES.with(std::cell::Cell::get) { + let mut name = base.clone(); + let mut i = 1; + while self.given.contains(&name) { + i += 1; + name = format!("{base} {i}"); + } + self.given.push(name.clone()); + return name; + } + let name = if self.taken.contains(&base) { + // Names are never given back, so every number below `from` is still taken. Of the + // numbers `from..=tries`, at least one is free. + let from = self.next.get(&base).copied().unwrap_or(2); + let tries = from.saturating_add(self.taken.len()); + let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries); + self.next.insert(base.clone(), i.saturating_add(1)); + format!("{base} {i}") + } else { + base + }; + self.taken.insert(name.clone()); + #[cfg(test)] + self.given.push(name.clone()); + name + } +} From dc6f1d2c699e8332d27a9ba93ff1f21b2efd2b66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 08:11:07 -0800 Subject: [PATCH 21/21] Task bar: the Recolor check stops at the first color The Contextual Task Bar and the Control bar check, each time they are drawn, whether the selection holds a color that Recolor Artwork can change. The check walked the whole subtree of each selected object even after the first color, so with one large group selected, the check read every paint in the group. - Node::try_walk visits in walk's order and ends at a ControlFlow::Break. - swatches::node_has_colors stops at the first color node_colors would visit; node_colors now runs the same visitor without stopping, so the two read the same nodes and paints in the same order. - has_colors in the task bar uses node_has_colors. The result is the same for every selection. On one group of 100,000 paths, the check takes 16 ns instead of 14.5 ms when the first path is filled; when only the last path is filled, or none is, it costs about what the full walk costs. --- crates/doc/src/node/ops.rs | 12 ++ crates/doc/src/node/tests.rs | 28 +++ crates/doc/src/swatches.rs | 244 +++++++++++++++++++++++++- crates/ui-egui/src/canvas/task_bar.rs | 6 +- crates/ui-egui/src/canvas/tests.rs | 22 +++ 5 files changed, 302 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index cd4798c76c..a616080bce 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -608,6 +608,18 @@ impl Node { } } + /// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no + /// node after it is visited, and the break is returned. + pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow) -> std::ops::ControlFlow { + f(self)?; + if let Some(ch) = self.children() { + for c in ch { + c.try_walk(f)?; + } + } + std::ops::ControlFlow::Continue(()) + } + /// Count of nodes in this subtree, ruler guides left out. pub fn count(&self) -> usize { let mut n = 0; diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index db21762f61..789e0f66b2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -805,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() { assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice)); assert_eq!(calls, 0); } + +/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its +/// children, its later siblings or its ancestors' later siblings. +#[test] +fn try_walk_ends_at_the_break() { + use std::ops::ControlFlow; + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]); + let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]); + let mut all = vec![]; + root.walk(&mut |n| all.push(n.id)); + let mut seen = vec![]; + assert_eq!( + root.try_walk(&mut |n| { + seen.push(n.id); + ControlFlow::<()>::Continue(()) + }), + ControlFlow::Continue(()) + ); + assert_eq!(seen, all, "without a break it visits what walk visits, in the same order"); + seen.clear(); + let flow = root.try_walk(&mut |n| { + seen.push(n.id); + if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) } + }); + assert_eq!(flow, ControlFlow::Break(NodeId(3))); + assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); +} diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 6d2c14a102..9c25427846 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -8,6 +8,7 @@ //! change; [`Document::map_paints`] replaces whole paints of any kind in the same places. use std::collections::{HashMap, HashSet}; +use std::ops::ControlFlow; use std::sync::Arc; use vectorcraft_color::swatch::REGISTRATION; @@ -340,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map, key: /// and gradient stops (with their link), a dynamic symbol instance's own paints /// ([`override_paints`]), then mesh points (unlinked), in paint order. pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { - n.walk(&mut |m| { + let _ = try_node_colors::<()>(n, &mut |c, s| { + f(c, s); + ControlFlow::Continue(()) + }); +} + +/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one. +pub fn node_has_colors(n: &Node) -> bool { + try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break() +} + +/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no +/// paint or node after it is visited. +fn try_node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow) -> ControlFlow { + n.try_walk(&mut |m| { for p in node_paints(m).chain(override_paints(m)) { match p { - Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?, + Paint::Gradient(g) => { + for s in &g.gradient.stops { + f(&s.color, s.swatch.as_deref())?; + } + } _ => {} } } if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| f(&p.color, None)); + for p in &mesh.points { + f(&p.color, None)?; + } } - }); + ControlFlow::Continue(()) + }) } fn item_paint(it: &AppearanceItem) -> &Paint { @@ -821,4 +843,216 @@ mod tests { node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string)))); assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. + fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { + n.walk(&mut |m| { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| f(&p.color, None)); + } + }); + } + + /// Whether [`full_walk`] finds a color in `n`. + fn full_walk_has_colors(n: &Node) -> bool { + let mut found = false; + full_walk(n, &mut |_, _| found = true); + found + } + + /// The colors of `n` by [`full_walk`], in order. + fn full_walk_colors(n: &Node) -> Vec<(Color, Option)> { + let mut out = vec![]; + full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string)))); + out + } + + fn square(id: u64, fill: Paint, stroke: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0)) + } + + fn holder(id: u64, kind: fn(Vec>) -> NodeKind, children: Vec) -> Node { + Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect())) + } + + /// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color. + fn color_cases() -> Vec<(&'static str, Node, bool)> { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let gradient = |stops: usize| { + let mut g = vectorcraft_color::Gradient::default(); + g.stops.truncate(stops); + Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))) + }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap(); + let mut empty_mesh = mesh.clone(); + empty_mesh.points.clear(); + let text = |fill: Paint| { + let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() }; + let mut n = + Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style)))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n + }; + let image = |colorize: Option| { + let im = crate::ImageObject { + key: "k".into(), + width: 2, + height: 2, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n.extras_mut().colorize = colorize.map(Box::new); + n + }; + let overridden = |fill: Option| { + let mut n = square(22, Paint::None, Paint::None); + n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }]; + n + }; + let masked = { + let mut n = square(23, Paint::None, Paint::None); + n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true))); + n + }; + let group = |children| NodeKind::Group { children, clip: false }; + let clip = |children| NodeKind::Group { children, clip: true }; + let compound = |children| NodeKind::Compound { children, rule: Default::default() }; + let blend = |children| NodeKind::Blend { children, spec: Default::default() }; + let blank = |id| square(id, Paint::None, Paint::None); + vec![ + ("no paint", blank(1), false), + ("solid fill", square(2, red.clone(), Paint::None), true), + ("solid stroke", square(3, Paint::None, red.clone()), true), + ("pattern only", square(4, pattern.clone(), pattern.clone()), false), + ("gradient without stops", square(5, gradient(0), Paint::None), false), + ("gradient with stops", square(6, gradient(2), Paint::None), true), + ("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true), + ("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false), + ("text run fill", text(red.clone()), true), + ("text without paint", text(Paint::None), false), + ("image colorize", image(Some(red.clone())), true), + ("image without colorize", image(None), false), + ("image with a pattern colorize", image(Some(pattern.clone())), false), + ("symbol override fill", overridden(Some(red.clone())), true), + ("symbol override without paint", overridden(None), false), + ("color only in the opacity mask", masked, false), + ("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true), + ("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true), + ("group without color", holder(38, group, vec![blank(39), blank(40)]), false), + ("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true), + ("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true), + ("blend", holder(47, blend, vec![blank(48), blank(49)]), false), + ( + "nested groups, color deepest", + holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]), + true, + ), + ] + } + + #[test] + fn has_colors_matches_the_full_walk() { + for (label, n, expected) in color_cases() { + let all = full_walk_colors(&n); + assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}"); + assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}"); + assert_eq!(node_has_colors(&n), expected, "{label}"); + let mut listed = vec![]; + node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string)))); + assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order"); + } + } + + #[test] + fn has_colors_stops_at_the_first_color() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut stops = vectorcraft_color::Gradient::default(); + stops.stops.push(stops.stops[0].clone()); + let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops))); + let mut later = vec![square(2, gradient, red.clone())]; + later.extend((3..100).map(|id| square(id, red.clone(), red.clone()))); + let n = holder(1, |children| NodeKind::Group { children, clip: false }, later); + let (mut colors, mut nodes) = (0, 0); + let flow = try_node_colors(&n, &mut |_, _| { + colors += 1; + ControlFlow::Break(()) + }); + assert!(flow.is_break()); + assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read"); + let flow = n.try_walk(&mut |m| { + nodes += 1; + if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }); + assert!(flow.is_break()); + assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it"); + } + + /// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in + /// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`. + #[test] + #[ignore = "a timing, not a check"] + fn has_colors_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let count = 100_000u64; + let group = |colored: &dyn Fn(u64) -> bool| { + let children = + (0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) }); + holder(0, |children| NodeKind::Group { children, clip: false }, children.collect()) + }; + let cases = [ + ("every path filled", group(&|_| true)), + ("only the last path filled", group(&|i| i == count - 1)), + ("no path filled", group(&|_| false)), + ]; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + // The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms. + let per_call = |f: fn(&Node) -> bool, n: &Node| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(std::hint::black_box(n))); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 30 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + for (label, n) in &cases { + assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}"); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(full_walk_has_colors, n)); + new.push(per_call(node_has_colors, n)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, nw) = (old[3], new[3]); + println!( + "{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs", + o.0, o.1, nw.0, nw.1 + ); + } + } } diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 9c6bcadd71..e49fa9bfc7 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -22,11 +22,7 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { - ids.iter().filter_map(|id| doc.node(*id)).any(|n| { - let mut found = false; - vectorcraft_doc::swatches::node_colors(n, &mut |_, _| found = true); - found - }) + ids.iter().filter_map(|id| doc.node(*id)).any(vectorcraft_doc::swatches::node_has_colors) } /// The bounds of the artboards the Artboard tool has selected ([`crate::panels::artboards::picked`]). diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 75d7e5fd75..99218607ca 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11045,6 +11045,28 @@ fn the_task_bar_recolors_coloured_art() { assert!(app.ui.dialog.is_none(), "no Recolor button without colours"); } +/// Recolor Artwork shows in the bars when any selected object has a color, whichever of them it is, +/// and not for an empty selection or ids that are gone. +#[test] +fn has_colors_looks_at_every_selected_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x: i32| { + vectorcraft_doc::NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()) + }; + let (blank, colored) = (rect(10), rect(80)); + s.execute("paint.setFill", &json!({"ids": [blank.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [blank.0], "none": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [colored.0], "color": "#cc3322"})).unwrap(); + let doc = &s.active().unwrap().doc; + let gone = vectorcraft_doc::NodeId(u64::MAX); + assert!(!has_colors(doc, &[]), "nothing selected"); + assert!(!has_colors(doc, &[gone]), "an id that is gone"); + assert!(!has_colors(doc, &[blank, gone])); + assert!(has_colors(doc, &[blank, colored]), "the color is on the second object"); + assert!(has_colors(doc, &[colored, blank, gone]), "the color is on the first object"); +} + /// The Contextual Task Bar's Lock button locks the selected member in isolation mode and the /// selected group outside isolation mode. #[test]