diff --git a/Cargo.lock b/Cargo.lock index b53df9115b..65c0466fa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1255,7 +1255,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-automation", "craft-behavior", @@ -1297,7 +1297,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "crc32fast", "flate2", @@ -1318,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1330,7 +1330,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "rustix 1.1.6", ] @@ -1338,7 +1338,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1363,7 +1363,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-docpath", @@ -1399,7 +1399,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "crc32fast", "flate2", @@ -1408,7 +1408,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "egui", ] @@ -1416,7 +1416,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "md-5", "rayon", @@ -1425,12 +1425,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-cms", @@ -1450,7 +1450,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1466,7 +1466,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1476,7 +1476,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "rayon", ] @@ -1484,7 +1484,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1510,7 +1510,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "blake3", "craft-ecproj-format", @@ -1526,7 +1526,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", ] @@ -1534,7 +1534,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "acadrust", "log", @@ -1562,7 +1562,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-codepage", "encoding_rs", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", "serde_json", @@ -1584,12 +1584,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-atomic", "dirs", @@ -1599,7 +1599,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1614,7 +1614,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1633,7 +1633,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1642,7 +1642,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "cap-primitives", "craft-atomic", @@ -1665,12 +1665,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "gif", ] @@ -1678,7 +1678,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", ] @@ -1686,7 +1686,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1699,7 +1699,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1729,7 +1729,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-dds", "craft-jpeg", @@ -1756,7 +1756,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1774,7 +1774,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "thiserror 2.0.21", ] @@ -1782,7 +1782,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-host", "craft-i18n", @@ -1808,7 +1808,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-i18n", @@ -1822,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -1840,7 +1840,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1852,7 +1852,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "encoding_rs", "image", @@ -1863,7 +1863,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "chrono", "craft-codepage", @@ -1873,7 +1873,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "uds_windows", "winsafe", @@ -1882,7 +1882,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-keymap", @@ -1898,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1907,7 +1907,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", "serde", @@ -1918,7 +1918,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1930,7 +1930,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "async-channel", "async-io", @@ -1963,7 +1963,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1972,7 +1972,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2007,7 +2007,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-eps", "flate2", @@ -2021,7 +2021,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "encoding_rs", "flate2", @@ -2032,7 +2032,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "dispatch2", "egui", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2054,7 +2054,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2073,7 +2073,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-atomic", "craft-host", @@ -2090,7 +2090,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "fax", "hayro-ccitt", @@ -2101,7 +2101,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-keymap", @@ -2134,7 +2134,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2159,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "thiserror 2.0.21", ] @@ -2167,7 +2167,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-atomic", "craft-behavior", @@ -2197,7 +2197,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", "thiserror 2.0.21", @@ -2207,7 +2207,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", "thiserror 2.0.21", @@ -2216,7 +2216,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-keymap", @@ -2231,12 +2231,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2250,7 +2250,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2267,7 +2267,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "accesskit", "craft-behavior", @@ -2305,7 +2305,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2316,7 +2316,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2334,7 +2334,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2355,7 +2355,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2376,7 +2376,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2395,7 +2395,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.22.1", "chrono", @@ -2427,7 +2427,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", "serde", @@ -2438,7 +2438,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2448,7 +2448,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "js-sys", "serde_json", @@ -2459,7 +2459,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "winsafe", ] @@ -2467,7 +2467,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-appkit", "craft-atomic", @@ -2499,7 +2499,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3859,7 +3859,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3868,7 +3868,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3886,7 +3886,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3904,12 +3904,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", "hayro-ccitt", @@ -4892,7 +4892,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5049,7 +5049,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -7615,8 +7615,7 @@ dependencies = [ [[package]] name = "skrifa" version = "0.44.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bytemuck", "read-fonts 0.41.0", diff --git a/Cargo.toml b/Cargo.toml index 89a8feda76..03de727454 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). -craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. -craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -200,13 +200,15 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). +skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 70aae32f73..0d227adb15 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index dc1e082ac0..7fdcf3a784 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -318,7 +318,7 @@ impl Document { /// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as /// [`Document::index_path`] finds it. pub fn node(&self, id: NodeId) -> Option<&Node> { - if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) { + if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id).or_else(|| cached.added_node_in(&self.layers, id))) { crate::id_index::note_path_lookup(); return Some(n); } @@ -365,10 +365,21 @@ impl Document { Some(None) => return self.walk_index_path(id), _ => {} } + let stale = cached.contains_key(&id); + // An id the table doesn't have, at the path an earlier walk found for it, while the node + // there still has the id. + if !stale + && let Some(p) = cached.added(&id) + && self.node_at(&p).is_some_and(|n| n.id == id) + { + return Some(p); + } // A stale path (the tree changed) or an id the cache doesn't have (deleted or added // since): walk, and rebuild now and then. let found = self.walk_index_path(id); - let stale = cached.contains_key(&id); + if !stale && let Some(p) = &found { + cached.note_added(id, p); + } if (stale || found.is_some()) && self.index.missed() { self.index.rebuild(&self.layers); } @@ -425,23 +436,37 @@ impl Document { // Cached paths that still check out ([`id_index`]); the rest take one walk. For a good // share of the document, one walk is quicker than checking each cached path. if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { - want.retain(|id| match cache.get(id) { - Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + want.retain(|id| match self.cached_path(&cache, *id) { + Some(p) => { out.insert(*id, p); false } - _ => true, + None => true, }); } if !want.is_empty() { crate::id_index::note_tree_walk(); let mut rest = HashMap::with_capacity(want.len()); walk(&self.layers, &want, &mut Vec::new(), &mut rest); + // The cache keeps the paths of found ids it doesn't have, for the next lookup. + if let Some(cache) = self.index.get().filter(|_| rest.len() <= crate::id_index::ADDED_PATHS) { + rest.iter().for_each(|(id, p)| cache.note_added(*id, p)); + } out.extend(rest); } out } + /// The path the lookup cache `cache` has for `id`, while the node there has the id: the table's + /// path, or for an id the table doesn't have, the path an earlier walk found ([`id_index`]). + fn cached_path(&self, cache: &crate::id_index::Paths, id: NodeId) -> Option> { + let p = match cache.get(&id) { + Some(p) => p?, + None => cache.added(&id)?, + }; + self.node_at(&p).is_some_and(|n| n.id == id).then_some(p) + } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still @@ -452,7 +477,8 @@ impl Document { let want: std::collections::HashSet> = ids.into_iter().collect(); // As in `index_paths`, one walk is quicker than checking the cached paths of a good share // of the document. - if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let cache = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()); + if let Some(cache) = &cache { let mut paths = Vec::with_capacity(want.len()); let cached = want.iter().all(|id| match cache.get(id) { Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { @@ -476,6 +502,10 @@ impl Document { out.push(n); } }); + // Found ids the table doesn't have count toward a rebuild for later ordered lookups. + if cache.is_some_and(|cache| out.iter().any(|n| !cache.contains_key(&n.id))) && self.index.missed() { + self.index.rebuild(&self.layers); + } } out } @@ -584,10 +614,14 @@ impl Document { /// Remove a node and return it. pub fn remove(&mut self, id: NodeId) -> Result, DocError> { - let parent = self.parent_of(id); let path = self.index_path(id).ok_or(DocError::NoNode(id))?; - let idx = *path.last().ok_or(DocError::NoNode(id))?; - let ch = self.children_mut(parent)?; + self.remove_at(id, &path) + } + + /// Remove the node at `path`, the index path [`Document::index_path`] gave for `id`, and return it. + fn remove_at(&mut self, id: NodeId, path: &[usize]) -> Result, DocError> { + let (&idx, up) = path.split_last().ok_or(DocError::NoNode(id))?; + let ch = self.children_at(up).ok_or(DocError::NoNode(id))?; if idx >= ch.len() { return Err(DocError::NoNode(id)); } @@ -602,10 +636,11 @@ impl Document { { return Err(DocError::Invalid("cannot move an object into itself".into())); } - if let Some(n) = self.node(id) { + let path = self.index_path(id).ok_or(DocError::NoNode(id))?; + if let Some(n) = self.node_at(&path) { self.check_ruler_guide_place(n, parent)?; } - let n = self.remove(id)?; + let n = self.remove_at(id, &path)?; let ch = self.children_mut(parent)?; let i = Node::insert_index(ch, index, &n); ch.insert(i, n); @@ -623,9 +658,15 @@ impl Document { /// Position of `id` within its parent: (parent, index, sibling count). pub fn position(&self, id: NodeId) -> Option<(Option, usize, usize)> { - let parent = self.parent_of(id); - let idx = *self.index_path(id)?.last()?; - let n = self.children(parent)?.len(); + let path = self.index_path(id)?; + let (&idx, up) = path.split_last()?; + let (parent, n) = match up { + [] => (None, self.layers.len()), + _ => { + let parent = self.node_at(up)?; + (Some(parent.id), parent.children()?.len()) + } + }; Some((parent, idx, n)) } diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 0e1673580a..05f899efac 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -4,10 +4,15 @@ //! The tree is edited in many places through public fields, so the cache can't be kept in step //! with it. It is checked instead: a cached path is used only while the node at that path still //! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache, -//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before. +//! and an id the cache doesn't have (added since, or removed) is looked up by walking. //! An id that appears more than once (a damaged file) is never cached, so lookups keep returning //! its first place in tree order. //! +//! The path a walk finds for an id the table doesn't have is kept beside the table, shared by every +//! document that reads it, and checked the same way before it is used. Documents that each start +//! from the same copy and add the same object (every preview of a drag starts from the document as +//! it was at the press) then find that object without walking the tree. +//! //! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache //! places each node after a removed sibling one lower and finds no path for a removed node or one //! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first @@ -16,8 +21,10 @@ //! The one case a cached lookup can answer differently from a walk: a second node with an //! existing id put in the tree *after* the cache was built, earlier in tree order than the first. //! The lookup then returns the original node (also one with that id) instead of the new one. The -//! app never makes such a node (paste and duplicate give new ids, undo restores whole trees); -//! duplicated ids come from damaged files, which are cached afresh when opened. +//! same holds for an id the table doesn't have: once a walk in one document has found it, a copy +//! that holds a second node with that id earlier in tree order gets the node at the path the walk +//! found. The app never makes such a node (paste and duplicate give new ids, undo restores whole +//! trees); duplicated ids come from damaged files, which are cached afresh when opened. use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hasher}; @@ -65,8 +72,15 @@ type Gaps = HashMap>; pub(crate) struct Paths { table: Arc, gaps: Arc, + /// The index paths that walks found for ids the table doesn't have, at most [`ADDED_PATHS`] of + /// them. Every document that reads the table reads them too, and checks a path against its own + /// tree before using it. + added: Arc>>>, } +/// The most paths [`Paths`] keeps for ids its table doesn't have; one more lets the kept ones go. +pub(crate) const ADDED_PATHS: usize = 4096; + /// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level /// layer) and its index among its siblings. One flat table, so building it allocates nothing per /// node. @@ -152,6 +166,36 @@ impl Paths { Err(k) => Some(i - k as u32), } } + /// The index path a walk found for `id`, an id the table doesn't have ([`Paths::note_added`]); + /// the caller checks that the node there has the id. + pub(crate) fn added(&self, id: &NodeId) -> Option> { + let path = self.added.read().ok()?.get(id)?.clone(); + note_path_copy(); + Some(path) + } + /// The node with `id` in `layers` at the path [`Paths::added`] has for it, found without copying + /// the path: `None` when there is none or the node there does not have the id. + pub(crate) fn added_node_in<'a>(&self, layers: &'a [Arc], id: NodeId) -> Option<&'a Node> { + let added = self.added.read().ok()?; + let (first, rest) = added.get(&id)?.split_first()?; + let mut node: &Node = layers.get(*first)?; + for &i in rest { + node = node.children()?.get(i)?; + } + (node.id == id).then_some(node) + } + /// Keep `path`, which a walk found for `id`, when the table doesn't have `id`. Past + /// [`ADDED_PATHS`] ids, the kept paths are let go first. + pub(crate) fn note_added(&self, id: NodeId, path: &[usize]) { + if self.table.ids.contains_key(&id) { + return; + } + let Ok(mut added) = self.added.write() else { return }; + if added.len() >= ADDED_PATHS && !added.contains_key(&id) { + added.clear(); + } + added.insert(id, path.to_vec()); + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -297,7 +341,7 @@ impl IdIndex { note_tree_walk(); let mut table = Table::default(); walk(layers, u32::MAX, &mut table); - let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() }); + let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default(), added: Arc::default() }); if let Ok(mut g) = self.0.write() { *g = Some(out.clone()); } diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 4a8f6a9d71..1bc90a68b0 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -608,3 +608,89 @@ fn node_lookups_copy_no_index_path() { agree(&d, &ids[..200], "after remove_many"); agree(&d, &nested, "nested"); } + +/// Copies of one document that each add the same object, as the previews of a drag do from the document at the press, +/// find that object where a walk finds it. The first copy walks the tree once for it and the later copies do not walk, +/// and [`Document::node`] finds it without copying an index path. +/// A copy that adds the object elsewhere, adds an object below it, groups it or deletes it, and the document they +/// were copied from, still find what a walk finds. A copy that adds it twice finds one node with its id, and +/// [`Document::nodes_in_order`] finds both. +#[test] +fn copies_that_add_an_object_find_it_without_walking_again() { + let (mut base, ids) = squares(2_000); + let layer = base.layers[0].id; + let added = base.alloc_id(); + let new = || Node::path(added, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()); + base.drop_lookup_cache(); + base.node(layer); + let walks = tree_walks(); + let mut node_copies = 0; + for copy in 0..20 { + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + let copies = path_copies(); + assert!(d.node(added).is_some_and(|n| n.id == added), "copy {copy}"); + node_copies += path_copies() - copies; + assert_eq!(d.index_path(added), Some(vec![0, ids.len()]), "copy {copy}"); + assert_eq!(d.index_paths([added, ids[5]]).get(&added), Some(&vec![0, ids.len()]), "copy {copy}"); + assert_eq!(d.ancestry(added), Some(vec![layer, added]), "copy {copy}"); + } + assert_eq!(tree_walks() - walks, 1, "walks of the tree for 20 copies"); + assert_eq!(node_copies, 0, "index paths copied by node for 20 copies"); + + // A copy that adds the object twice: lookups give one node with its id, and nodes_in_order, + // which reads only the table's paths, gives both. + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + d.insert(Some(layer), 3, new()).unwrap(); + agree_except(&d, &[added, ids[3], ids[0]], Some(added), "added twice"); + assert_eq!(d.nodes_in_order([ids[7], added]).iter().map(|n| n.id).collect::>(), [added, ids[7], added], "added twice"); + let gone = d.index_path(added).unwrap(); + assert_eq!(d.remove(added).unwrap().id, added); + assert_eq!(d.walk_index_path(added).filter(|p| *p != gone).map(|_| ()), Some(()), "the other one stays"); + assert_eq!(d.layers[0].children().unwrap().len(), ids.len() + 1, "removed one node"); + + // The object lower in the layer, with another object below it, and the next copy back at the top. + let mut d = base.clone(); + d.insert(Some(layer), 10, new()).unwrap(); + agree(&d, &[added, ids[9], ids[10]], "added at 10"); + let below = square(&mut d); + let below = d.insert(Some(layer), 0, below).unwrap(); + agree(&d, &[added, below, ids[9]], "an object below it"); + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + agree(&d, &[added], "back at the top"); + + // Grouped with the object below it, then deleted. + let gid = d.alloc_id(); + let members = vec![d.remove(ids[ids.len() - 1]).unwrap(), d.remove(added).unwrap()]; + d.insert(Some(layer), usize::MAX, Node::group(gid, members)).unwrap(); + assert_eq!(d.index_path(added), Some(vec![0, ids.len() - 1, 1])); + agree(&d, &[added, gid, ids[ids.len() - 1]], "grouped"); + d.remove(gid).unwrap(); + assert!(d.node(added).is_none() && d.index_path(added).is_none(), "deleted with its group"); + agree(&d, &[added, gid], "deleted"); + + // The document the copies came from has no such object, and a copy that adds it again finds it. + assert!(base.node(added).is_none() && base.index_path(added).is_none() && base.index_paths([added]).is_empty()); + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + agree(&d, &[added, ids[0]], "added again"); +} + +/// Repeated ordered lookups of an added object rebuild the table and then use its cached path. +#[test] +fn ordered_lookups_of_an_added_object_stop_walking() { + let (mut d, _) = squares(2_000); + let layer = d.layers[0].id; + d.drop_lookup_cache(); + d.node(layer); + let new = square(&mut d); + let added = d.insert(Some(layer), usize::MAX, new).unwrap(); + assert!(d.node(added).is_some_and(|n| n.id == added)); + let walks = tree_walks(); + for lookup in 0..20 { + assert_eq!(d.nodes_in_order([added]).iter().map(|n| n.id).collect::>(), [added], "lookup {lookup}"); + } + assert!(tree_walks() - walks <= 5, "walks of the tree for 20 ordered lookups"); +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index b6131adb53..7a6663b603 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -262,7 +262,7 @@ pub fn effect_catalog() -> Vec { ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 883366a97f..6a9ddfbbff 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1013,6 +1013,12 @@ fn solid_items(shape: &Profile) -> impl Iterator { shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i) } +/// The fills and strokes 3D effect `id` draws for `shapes`: every one for Rotate, which draws a +/// plane for each ([`meshes_for`]), and [`solid_items`] for the other effects. +fn drawn_items<'a>(id: &str, shapes: &'a [Profile]) -> Box + 'a> { + if is_plane(id) { Box::new(shapes.iter().flat_map(|s| s.items.iter())) } else { Box::new(shapes.iter().flat_map(solid_items)) } +} + /// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes, /// a group's members from the back up, each with its shape's opacity, the region it paints and its /// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any): @@ -2086,7 +2092,7 @@ fn art_for( { let image = if rendered::reshapes_paths_only(later) { Err(rendered::PATHS_ONLY.into()) - } else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(solid_items), has_masks(shapes)) { + } else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) { meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { let lighting = rendered::lighting(&fx.id, &p); let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 275a747edc..403991b6ca 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -70,7 +70,7 @@ const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::IN fn rendered_eligibility_ignores_fills_below_the_top_fill() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let doc = vectorcraft_doc::Document::new(400.0, 400.0); - for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + for id in [super::super::EXTRUDE, super::super::INFLATE] { let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new( @@ -85,6 +85,28 @@ fn rendered_eligibility_ignores_fills_below_the_top_fill() { } } +/// Rotate draws a plane for every fill and stroke, so a gradient fill below the top fill keeps it +/// from rendering, as a gradient top fill does. +#[test] +fn rotate_rendered_eligibility_checks_every_fill() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + assert_eq!(crate::rendered_warning(&doc, &n), None); + assert_eq!(images(&drawn(&n)).len(), 1); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + stops, + )))))); + for at in [0, 1] { + let mut n = n.clone(); + n.appearance.items.insert(at, lower.clone()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "gradient fill at {at}"); + assert!(images(&drawn(&n)).is_empty(), "gradient fill at {at}"); + } +} + #[test] fn later_pathfinder_uses_shaded_faces_and_reports_the_fallback() { let doc = vectorcraft_doc::Document::new(400.0, 400.0); diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 67e9b4d68d..ba09a537a7 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -31,8 +31,8 @@ use super::super::edit::selected_roots; use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; use super::super::object::{ - aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, object_bounds_transform_keeping, - refit_drawn, scaling, transform_node, transform_patterns, + aligned_symbol_transforms, aligned_symbols, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, + object_bounds_transform_keeping, refit_drawn, scaling, snaps_after_edit, transform_node, transform_patterns, }; use super::super::objects_on_path; use super::super::typecmd::refresh_bounds_of; @@ -102,7 +102,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into or out of a locked layer or group, take a target out of the blend input it is in (to restack the blend itself, select the whole blend), put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -526,6 +526,11 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { }; let angle = s.doc()?.doc.bbox_angle(&[source]); let mut xfs = Vec::with_capacity(targets.len()); + // Where each turned target's reference point is before the match; it stays there. + let mut pinned: HashMap = HashMap::new(); + // The turned targets whose reference point is checked after pixel snapping. + let mut checked: HashMap = HashMap::new(); + let symbols = if rotate { aligned_symbols(&s.doc()?.doc) } else { HashMap::new() }; for &id in &targets { let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 }; let Some(b) = s.transform_box(&[id]) else { @@ -551,6 +556,16 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let turned = Affine::rotate_about(-turn.to_radians(), at); if turn.abs() > 1e-9 { xf = turned * xf; + let preview = s.bounds_measure().preview; + let d = &s.doc()?.doc; + if preview && d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) { + pinned.insert(id, at); + } + // Pixel snapping after the turn can move a pixel-aligned target: its point is checked + // too, but not put back, since that would move its aligned art off the grid. + if pinned.contains_key(&id) || d.node(id).is_some_and(|n| snaps_after_edit(n, &symbols)) { + checked.insert(id, at); + } } if wanted.is_some() { let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners }; @@ -571,6 +586,32 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "a clipping path can't change its place in the stacking order")); } let parent = d.parent_of(source); + // Each target leaves its own container, so a target's locked container refuses too. + let locked = |p: Option| p.is_some_and(|p| crate::cmd::layer::locked_within(d, p)); + if locked(parent) || targets.iter().any(|t| locked(d.parent_of(*t))) { + return Err(bad(C, "the layer or group is locked")); + } + // A blend's input objects, and art inside them, stay in the blend: the whole blend can still be + // restacked, and art can still move within the blend's input it is in. + let is_blend = |a: &NodeId| d.node(*a).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })); + let destination = parent.and_then(|p| d.ancestry(p)).unwrap_or_default(); + let leaves_blend = |t: &NodeId| { + let chain = d.ancestry(*t).unwrap_or_default(); + chain.windows(2).filter(|w| is_blend(&w[0])).any(|w| !destination.windows(2).any(|v| v == w)) + }; + if targets.iter().any(leaves_blend) { + return Err(bad(C, "a blend's input objects can't leave their blend input: to restack the blend, select the whole blend")); + } + // Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place. + let in_live_paint = + |id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint)); + if parent.is_some_and(in_live_paint) || targets.iter().any(|t| d.parent_of(*t).is_some_and(in_live_paint)) { + return Err(bad(C, "Live Paint art can't be restacked here: use the Layers panel")); + } + // The source's container takes each target only as the Layers panel would (not a blend's inputs). + if let Some(n) = targets.iter().filter_map(|id| d.node(*id)).find(|n| !crate::cmd::layer::accepts(d, parent, n)) { + return Err(bad(C, format!("{} can't go beside the source object", n.display_name()))); + } if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -585,11 +626,26 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &q); sc.patterns = transform_patterns(s, &q, &ids)?; + let measure = s.bounds_measure(); + let before = s.doc()?.doc.clone(); s.edit("Match Objects", |d, _| { for (id, xf) in &xfs { if let Some(n) = d.node_mut(*id) { transform_node(n, *xf, sc, true); } + // A live effect that moves the art in page space (a Transform effect's offset) does + // not turn with it: the measured reference point is put back where it was. + if let Some(at) = pinned.get(id) + && let Some(b) = effects::preview::oriented_bounds_with(d, &[*id], measure) + { + let now = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + let off = *at - now; + if off.hypot() > 1e-9 + && let Some(n) = d.node_mut(*id) + { + transform_node(n, Affine::translate(off), sc, true); + } + } } if restack { let moved = d.remove_many(&targets)?; @@ -597,6 +653,26 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { // Targets moved out of an Intertwine group leave it as ordinary art. crate::cmd::intertwine::settle_members(d, &placed, &left)?; } + if !checked.is_empty() { + // Measured on a snapped copy: the edit itself snaps once, after Global Edit. + let mut snapped = d.clone(); + crate::cmd::refresh_pixel_aligned(&before, &mut snapped); + for (id, _) in &xfs { + let Some(at) = checked.get(id) else { continue }; + let ob = effects::preview::oriented_bounds_with(&snapped, &[*id], measure); + let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6); + let misses = !kept + || ob.is_none_or(|b| match size { + "none" => false, + "width" => (b.rect.width() - w).abs() > 1e-6, + "height" => (b.rect.height() - h).abs() > 1e-6, + _ => (b.rect.width() - w).abs() > 1e-6 || (b.rect.height() - h).abs() > 1e-6, + }); + if misses { + return Err(bad(C, format!("object {} can't keep its size and reference point as it turns", id.0))); + } + } + } Ok(()) })?; Ok(count) diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index b951bbacc2..b98d45ae0a 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -525,6 +525,67 @@ fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() { } } +#[test] +fn match_rotation_refuses_when_pixel_snapping_would_move_the_reference_point() { + for wrap in ["path", "group", "compound"] { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 11.0); + if wrap != "compound" { + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + } + let target = match wrap { + "group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()), + "compound" => NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()), + _ => target, + }; + select(&mut s, &[target]); + if wrap == "compound" { + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + } + let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + // Turned a quarter about its center (5, 5.5), the 10 x 11 path's edges land on half points, + // and snapping them back to the grid would move that center. + let e = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string(); + assert!(e.contains("reference point"), "{wrap}: {e}"); + assert_eq!(steps(&s), n, "{wrap}: no undo step"); + assert!(*s.doc().unwrap().doc == *before, "{wrap}"); + } +} + +#[test] +fn match_rotation_keeps_a_mixed_group_in_one_piece_or_refuses() { + let mut s = session(); + let aligned = rect(&mut s, 0.0, 0.0, 10.0, 11.0); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let loose = rect(&mut s, 20.0, 0.0, 10.0, 11.0); + select(&mut s, &[aligned, loose]); + let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let gap = |s: &Session| { + let (a, b) = (s.transform_box(&[aligned]).unwrap().center(), s.transform_box(&[loose]).unwrap().center()); + b - a + }; + let before = s.doc().unwrap().doc.clone(); + match s.execute("addon.arrange.match", &json!({"rotate": true})) { + // Turned a quarter, the members' centers keep their distance and only change direction. + Ok(_) => assert!((gap(&s).hypot() - 20.0).abs() < 1e-6, "the members moved apart: {:?}", gap(&s)), + Err(e) => { + assert!(e.to_string().contains("reference point"), "{e}"); + assert!(*s.doc().unwrap().doc == *before); + } + } +} + #[test] fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() { for angle in [0, 30] { @@ -811,6 +872,234 @@ fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() { assert!(*s.doc().unwrap().doc == *before); } +#[test] +fn match_refuses_restacking_into_a_locked_container() { + for lock_ancestor in [false, true] { + let mut s = session(); + let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[source]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[group]); + let ancestor = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let locked = if lock_ancestor { ancestor } else { group }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(locked).unwrap().locked = true; + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"size": "both", "stacking": true})).unwrap_err(); + assert!(e.to_string().contains("the layer or group is locked"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + } +} + +#[test] +fn match_refuses_restacking_among_a_blends_inputs() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let target = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, target]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("can't go beside the source object"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn match_refuses_taking_a_target_out_of_a_locked_container() { + let mut s = session(); + let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + select(&mut s, &[target]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().locked = true; + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("the layer or group is locked"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn match_refuses_taking_a_target_out_of_a_blend_but_restacks_the_whole_blend() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let blend = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let source = rect(&mut s, 250.0, 0.0, 20.0, 20.0); + assert_eq!(layer_order(&s), [blend, between, source]); + select(&mut s, &[a, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("a blend's input objects"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + select(&mut s, &[blend, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [between, source, blend]); +} + +#[test] +fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let target = rect(&mut s, 250.0, 0.0, 20.0, 20.0); + assert_eq!(layer_order(&s), [g, between, target]); + let member = s.doc().unwrap().doc.children(Some(g)).unwrap()[0].id; + select(&mut s, &[member, target]); + s.execute("select.key", &json!({"id": member.0})).unwrap(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("Live Paint art"), "{e}"); + assert_eq!(steps(&s), n); + select(&mut s, &[g, target]); + s.execute("select.key", &json!({"id": g.0})).unwrap(); + let before = s.doc().unwrap().doc.node(g).unwrap().clone(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [g, target, between]); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap(), &before); +} + +#[test] +fn match_turns_art_with_a_moving_effect_about_its_measured_point() { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + s.execute("effect.apply", &json!({"ids": [b.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let center = |s: &Session| { + let bx = s.transform_box(&[b]).unwrap(); + bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4) + }; + let before = center(&s); + select(&mut s, &[a, b]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap(); + let after = center(&s); + assert!((after - before).hypot() < 1e-6, "{before:?} -> {after:?}"); +} + +#[test] +fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() { + for size in ["none", "both"] { + for dx in [0.0, 0.25] { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0); + let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + select(&mut s, &[art]); + let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("object.move", &json!({"dx": dx})).unwrap(); + s.execute("effect.apply", &json!({"ids": [target.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let center = |s: &Session| { + let b = s.transform_box(&[target]).unwrap(); + b.to_doc() * vectorcraft_geom::reference_point(b.rect, 4) + }; + let at = center(&s); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let result = s.execute("addon.arrange.match", &json!({"rotate": true, "size": size})); + if dx == 0.0 { + result.unwrap(); + assert!((center(&s) - at).hypot() < 1e-6, "{size}"); + let b = s.transform_box(&[target]).unwrap(); + assert!(b.angle.abs() < 1e-6, "{size}: {b:?}"); + if size == "both" { + let wanted = s.transform_box(&[source]).unwrap(); + assert!((b.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {b:?}"); + assert!((b.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {b:?}"); + } + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + } else { + let error = result.unwrap_err().to_string(); + assert!(error.contains("can't keep its size and reference point as it turns"), "{size}: {error}"); + } + assert_eq!(steps(&s), n, "{size}, dx={dx}"); + assert!(*s.doc().unwrap().doc == *before, "{size}, dx={dx}"); + } + } +} + +#[test] +fn match_refuses_when_snapping_moves_a_pixel_aligned_symbol_instance_without_preview_bounds() { + let mut s = session(); + s.prefs.use_preview_bounds = false; + let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0); + let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + select(&mut s, &[art]); + let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("object.move", &json!({"dx": 0.25})).unwrap(); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + // Turned back to its natural angle, the instance snaps to whole points, which moves its center. + let error = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string(); + assert!(error.contains("can't keep its size and reference point as it turns"), "{error}"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() { + for grouped in [false, true] { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + s.execute("effect.apply", &json!({"ids": [b.0], "item": 0, "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let b = if grouped { + select(&mut s, &[b]); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + } else { + b + }; + let center = |s: &Session| { + let bx = s.transform_box(&[b]).unwrap(); + bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4) + }; + let before = center(&s); + select(&mut s, &[a, b]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap(); + let after = center(&s); + assert!((after - before).hypot() < 1e-6, "grouped={grouped}: {before:?} -> {after:?}"); + let d = &s.doc().unwrap().doc; + assert!((d.bbox_angle(&[b]) - d.bbox_angle(&[a])).abs() < 1e-6); + } +} + #[test] fn match_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index 7e82b25903..35e47de772 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -150,6 +150,14 @@ pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String) for run in &mut text.runs { visit(&mut run.style.font_family); } + // The fonts the file carried for this type are found by the family its runs name. + for font in text.file_fonts.iter_mut().flat_map(|fonts| fonts.fonts.iter_mut()) { + visit(&mut font.family); + } + } + // A live dimension makes its label again from its options. + if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_deref_mut()) { + visit(&mut dimension.options.font_family); } // A dimension redraws its label from its own options, so they follow the label's family. // A spelling that already names the same font, or one too long for the options, is kept. @@ -234,6 +242,20 @@ pub(super) fn plan_import( target_taken.insert(font.name.to_lowercase()); target_taken.extend(font.part_fonts().map(str::to_lowercase)); } + // Families the source names without defining them as composite fonts, which the target does + // define: they stay undefined under a free name instead of taking the target's meaning. + let undefined: Vec = source_families + .iter() + .filter(|family| !source_names.contains(*family) && !FontDb::global().has_installed_family(family)) + .filter_map(|family| CompositeFont::named(&target.composite_fonts, family).map(|font| font.name.clone())) + .collect(); + // Their alias may be a family the target's art already names without defining it, as an + // earlier placement of the same art left it, so that placement and this one share resources. + let mut alias_reserved = source_families.clone(); + for font in source.iter().chain(target.composite_fonts.iter()) { + alias_reserved.insert(font.name.to_lowercase()); + alias_reserved.extend(font.part_fonts().map(str::to_lowercase)); + } let mut reserved = source_families; reserved.extend(target_families); for font in source.iter().chain(target.composite_fonts.iter()) { @@ -264,12 +286,18 @@ pub(super) fn plan_import( combined.push(CompositeFont { name, ..font }); } } + alias_reserved.extend(names.values().map(|name| name.to_lowercase())); + for family in undefined { + let name = composite_alias(&family, &alias_reserved, cmd)?; + alias_reserved.insert(name.to_lowercase()); + names.insert(family.to_lowercase(), name); + } // A source document may currently lend fonts to the database. Validate the prospective // document, not composite names temporarily registered by a different document. if combined.len() > COMPOSITE_FONTS_MAX { return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); } - if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) { + if let Some(font) = combined.iter().skip(target.composite_fonts.len()).find(|font| db.has_installed_family(&font.name)) { return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name))); } if CompositeFont::usable(&combined).is_some() { diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 4dee23bcda..9a52df4dbb 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -377,6 +377,11 @@ impl DocSettings { /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); + // The columns that rows give the artboards as they are now, which a layout that replaces the + // rows without its own `columns` keeps. + if self.grid_rows().is_some() { + self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); + } if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; if self.layout != ArtboardLayout::GridByColumn { diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 257136055c..f9c30205f0 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -37,8 +37,8 @@ pub(crate) use bounds::{bounds_rewrite, object_bounds_transform, object_bounds_t pub use commands::specs; pub(super) use compound::{as_clipping_path, copy_transparency, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ - align_new_object, aligned_symbol_transforms, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned, keep_pixel_aligned, - keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art, + align_new_object, aligned_symbol_transforms, aligned_symbols, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned, + keep_pixel_aligned, keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art, snaps_after_edit, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 72fc1a93da..523e4d79f1 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -492,6 +492,18 @@ pub(crate) fn snap_if_aligned(n: &mut Node) { } } +/// Whether the pixel-grid snap after an edit ([`refresh`]) can move object `n`: `n` holds +/// pixel-aligned art ([`holds_aligned`]) or an instance of a symbol in `symbols`, the document's +/// pixel-aligned symbols ([`aligned_symbols`]). +pub(crate) fn snaps_after_edit(n: &Node, symbols: &HashMap) -> bool { + holds_aligned(n) || !symbols.is_empty() && holds_instance(n, symbols) +} + +/// The pixel-aligned symbols of `d`, keyed by name, for [`snaps_after_edit`]. +pub(crate) fn aligned_symbols(d: &Document) -> HashMap { + d.pixel_aligned_symbols().into_iter().map(|name| (name, Affine::IDENTITY)).collect() +} + /// Whether `n` or an object in it, or in the art of a linked opacity mask in it, is pixel-aligned. /// It goes only where a transform of `n` goes: not into unlinked masks. fn holds_aligned(n: &Node) -> bool { diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index daa5277633..b5f46c025b 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -102,7 +102,7 @@ pub fn specs() -> Vec { /// The Objects on Path groups of `ids`: the ones among them, and the innermost one around each /// object in one. -fn groups_of(d: &Document, ids: &[NodeId]) -> Vec { +pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec { let mut out = vec![]; for id in ids { let group = d.ancestry(*id).unwrap_or_default().into_iter().rev().find(|a| d.node(*a).is_some_and(is_objects_on_path)); diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index b340052962..889a83a3be 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; +use vectorcraft_doc::{AppearanceItem, CompositeFont, Document, Node, NodeKind, PatternDef, Symbol}; use super::super::Result; use super::super::clipboard::SymbolOptions; @@ -545,9 +545,8 @@ fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, bru /// Discover the incoming resource frontier and its composite-font users before planning /// names or changing either document. Resource order and the no-composite fast path stay shared. -fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec, BTreeSet, BTreeSet) { +fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec, BTreeSet, BTreeSet) { let mut used = Used::default(); - let composites = !src.composite_fonts.is_empty(); let mut families = BTreeSet::new(); let mut dimension_families = BTreeSet::new(); let mut note_families = |node: &mut Node| { @@ -602,10 +601,16 @@ fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec, B /// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point /// `nodes` at the names they got. pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> { - let (used, mut src_brushes, families, dimension_families) = collect_resources(src, nodes); + let composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty(); + let (used, mut src_brushes, families, dimension_families) = collect_resources(src, nodes, composites); let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::>(); + // A family the source does not define as a composite font, which the destination defines as + // one, would draw in the destination's composite font after placement. + let undefined_clash = families + .iter() + .any(|family| CompositeFont::named(&src.composite_fonts, family).is_none() && CompositeFont::named(&dst.composite_fonts, family).is_some()); // All representability/validation errors precede incoming or destination mutation. - let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dimension_families, dst, cmd)?) }; + let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dimension_families, dst, cmd)?) }; let staged; let mut aliased = false; let src = if let Some(plan) = &plan { diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 2011a61729..41b50dbeca 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -402,6 +402,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)), p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool), p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool), + p!("smoothBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images", bool), p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool), p!( "updateLinks", diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index ee2f3fcc5d..42bbb65c5c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with both the color and its model unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; when a waiting event's run cannot begin in the app, the status bar shows the error and the events in line wait until the next input in the window, another script.palette.event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the recoveryFolder or recoveryOffForComplex preference; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7b6b840682..814990daba 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -458,6 +458,13 @@ pub struct Session { /// The pointer button is held: the last pointer event was a press or a drag, not a release or /// a move ([`Session::pointer_held`]). pub(crate) pointer_held: bool, + /// While [`Session::pointer_samples`] feeds a pass's samples to the tool, the tool's previews are + /// held in [`Self::sampled_preview`] instead of being applied. + pub(crate) holds_previews: bool, + /// The last preview the tool asked for during [`Session::pointer_samples`], not yet applied. It is + /// applied before any other action of the tool, before a preview of another command, and when the + /// samples end. + pub(crate) sampled_preview: Option<(String, serde_json::Value)>, /// The id and persistent options of the tool when the press under way began, which a dropped /// press puts back ([`Session::drop_tool_press`]). pub(crate) press_options: Option<(String, serde_json::Map)>, diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index e72a20c6c1..0cb1cf613f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -306,7 +306,16 @@ pub struct Prefs { /// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the /// fallback font with the missing-font warning (#4568). pub pdf_import_embedded_fonts: bool, + /// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: smooths images + /// (except images marked pixelated, such as envelope images made with Anti-Alias off) while Pixel Preview draws its own pixel raster (the view zoomed above one screen pixel per + /// document pixel and the region within the largest texture side); otherwise + /// `smooth_bitmaps` applies, in Pixel Preview too. pub anti_aliased_bitmaps: bool, + /// File Handling › Display Bitmaps as Anti-aliased Images: placed and embedded bitmaps drawn + /// larger than their pixels are smoothed (on by default); off, each of their pixels shows as a + /// hard-edged square (#10712). It applies whenever Pixel Preview does not draw its own pixel + /// raster; while it does, `anti_aliased_bitmaps` applies. + pub smooth_bitmaps: bool, pub update_links: String, /// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app /// becomes when the open or place does not say (`text`: editable type in the file's fonts; @@ -698,6 +707,7 @@ impl Default for Prefs { low_res_proxy_eps: false, pdf_import_embedded_fonts: true, anti_aliased_bitmaps: false, + smooth_bitmaps: true, update_links: s("askWhenModified"), pdf_text_as: s("text"), copy_as_svg: true, diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 86b3030f9a..7264290717 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -5,12 +5,14 @@ //! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the //! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and //! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and +//! returns the color picked for OK, or a new object of the color it was given for Cancel. //! //! In the app the run waits at the call for the person's answer, and spends no fuel while it -//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with -//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no -//! answer left, or with the next answer for another kind of dialog, ends the run. The report's -//! `dialogs` lists each dialog and its answer. +//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts +//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s +//! `answers`; a call with no answer left, or with the next answer for another kind of dialog, +//! ends the run. The report's `dialogs` lists each dialog and its answer. //! //! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], //! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and @@ -21,6 +23,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind}; use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; @@ -51,22 +54,34 @@ pub enum DialogKind { Prompt, /// A ScriptUI dialog's `show()` ([`super::scriptui`]). Window, + /// `app.showColorPicker`. + ColorPicker, } impl DialogKind { - /// The function's name, which is also the `kind` of an answer and of a report's dialog. + /// The `kind` of an answer and of a report's dialog, which is also the function's name for + /// `alert`, `confirm` and `prompt`. pub fn id(self) -> &'static str { match self { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", Self::Window => "window", + Self::ColorPicker => "colorPicker", + } + } + + /// The function's name, as its errors give it. + fn function(self) -> &'static str { + match self { + Self::ColorPicker => "showColorPicker", + k => k.id(), } } } /// A dialog a script opened, which waits for its answer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub struct ScriptDialog { pub kind: DialogKind, pub message: String, @@ -78,10 +93,15 @@ pub struct ScriptDialog { pub no_as_default: bool, /// `prompt`: the text its field starts with. pub preset: String, + /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. + pub color: Option, + /// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app + /// gives an RGB pick back as CMYK. False for the other dialogs. + pub cmyk_document: bool, } /// The answer to a [`ScriptDialog`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub enum DialogAnswer { /// OK, for `alert`. Ok, @@ -91,6 +111,8 @@ pub enum DialogAnswer { Prompt(Option), /// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask. Window(Vec), + /// OK with the color picked, or Cancel (`None`), for `showColorPicker`. + ColorPicker(Option), } impl DialogAnswer { @@ -100,30 +122,101 @@ impl DialogAnswer { Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, Self::Window(_) => DialogKind::Window, + Self::ColorPicker(_) => DialogKind::ColorPicker, } } - /// What the function returns. - fn data(&self) -> Data { + /// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it + /// started with. + fn data(&self, d: &ScriptDialog) -> Data { match self { Self::Ok | Self::Window(_) => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, + Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data), } } - /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + /// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands + /// take it, or `null`. fn json(&self) -> Value { match self { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), Self::Window(steps) => json!(steps.len()), + Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json), } } } +/// `c` as the paint commands take it. +fn color_json(c: &Color) -> Value { + serde_json::to_value(c).unwrap_or(Value::Null) +} + +/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from +/// -128 to 128, as a script's `LabColor` takes them? +fn in_range(c: &Color) -> bool { + let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x)); + match *c { + Color::Rgb { r, g, b } => unit(&[r, g, b]), + Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]), + Color::Gray { k } => unit(&[k]), + Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)), + } +} + +/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key +/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components +/// into their ranges. An array or object is checked as written too, in f64 and with the scale +/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded +/// onto it when it narrows to f32. +fn answer_color(v: &Value) -> Option { + // Parsed as f64, so that a value just past a limit is not rounded onto it. + let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); + let num = |o: &serde_json::Map, key: &str| o.get(key).and_then(Value::as_f64); + let written_in_range = match v { + Value::String(s) if Color::from_hex(s).is_none() => { + let mut it = s.split_whitespace(); + let model = it.next()?.to_ascii_lowercase(); + let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; + match (model.as_str(), n.as_slice()) { + ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), + ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), + ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), + _ => return None, + } + } + Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0), + Value::Object(o) => { + if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) { + let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 }; + within(&[c, m, y, k], 0.0, scale) + } else if let Some(g) = o.get("gray") { + let g = g.as_f64()?; + within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0) + } else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) { + within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0) + } else { + match o.get("model").and_then(Value::as_str) { + Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0), + Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0), + Some("gray") => within(&[num(o, "k")?], 0.0, 1.0), + Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0), + _ => true, + } + } + } + _ => true, + }; + if !written_in_range { + return None; + } + crate::cmd::color_value(v).filter(in_range) +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -156,9 +249,10 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}` -/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an -/// empty list. +/// true | false}`, `{kind: "prompt", value: text | null}`, `{kind: "window", value: [step, ...]}` +/// ([`super::scriptui`]) and `{kind: "colorPicker", value: color | null}`, the color in any form +/// the paint commands take. An empty object, which the parameter took before dialogs existed, is +/// an empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { None => return Ok(Vec::new()), @@ -196,7 +290,12 @@ fn known_answer(o: &Map) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm, prompt or window"), + (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), + (Some("colorPicker"), v) => match answer_color(v) { + Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), + None => Err("is a color picker's answer, whose `value` must be a color or null"), + }, + _ => Err("must have `kind` alert, confirm, prompt, window or colorPicker"), } } @@ -465,9 +564,10 @@ impl Dialogs { } let Some(d) = waiting.take() else { return false }; drop(waiting); + let data = answer.data(&d); let on_yes = self.on_yes.take(); // A confirm the app opened returns `undefined` to the call that opened it. - let data = if on_yes.is_some() { Data::Undefined } else { answer.data() }; + let data = if on_yes.is_some() { Data::Undefined } else { data }; if answer == DialogAnswer::Confirm(true) { self.approved.set(on_yes); } @@ -523,13 +623,16 @@ impl Dialogs { fn record(&self, d: &ScriptDialog, answer: Value) { let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); - r.insert("message".into(), json!(d.message)); - r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + if d.kind != DialogKind::ColorPicker { + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + } match d.kind { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), DialogKind::Window => None, + DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)), }; r.insert("answer".into(), answer); self.push_record(Value::Object(r)); @@ -584,7 +687,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result host.charge_call(args.iter().map(super::data_size).sum())?; let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; let (title, error_icon, no_as_default, preset) = match kind { - DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + // `showColorPicker` opens through `show_color_picker`, not here. + DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()), DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), DialogKind::Prompt => { let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; @@ -601,7 +705,33 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false }) +} + +/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, +/// and a new object of `color` for Cancel. +pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + // During a slice the session holds the run's working copy, whose active document may be one + // the script made; between slices the app sees the documents as they were before the run. + let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk); + let dialog = ScriptDialog { + kind: DialogKind::ColorPicker, + message: String::new(), + title: None, + error_icon: false, + no_as_default: false, + preset: String::new(), + color: Some(color), + cmyk_document, + }; + wait_or_answer(host, dialog) +} + +/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of +/// `answers`. +fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result { + let kind = dialog.kind; + let name = kind.function(); let d = &host.dialogs; if d.framed { if !d.can_wait.get() { @@ -616,11 +746,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result match next { Some(a) if a.kind() == kind => { d.record(&dialog, a.json()); - Ok(a.data()) + Ok(a.data(&dialog)) } Some(a) => { d.record(&dialog, json!("missing")); - Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id()))) } None => { d.record(&dialog, json!("missing")); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1dda97ad95..c8aab4149c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -117,6 +117,7 @@ mod tracing; mod transform; mod variables; +pub(super) use colors::of_color as color_data; #[cfg(test)] pub(crate) use paths::POINT_LOOKS; @@ -1155,6 +1156,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`, +/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]). +fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { + let color = colors::solid(arg(a, 1), "showColorPicker's color")?; + super::dialogs::show_color_picker(h, color) +} + /// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts /// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a /// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files. @@ -3381,6 +3389,7 @@ fn classes(link: &Link) -> Vec { ("selection", property(l, app_selection, app_set_selection), typed("*")), ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), + ("showColorPicker", method(l, app_show_color_picker), returns("Color", &[("color", "Color")])), ("redraw", method(l, app_redraw), returns("undefined", &[])), ("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])), ("undo", method(l, app_undo), returns("undefined", &[])), diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 4de02e881b..137902ab14 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -13,7 +13,10 @@ //! VectorCraft's own rules, which the help pages do not state: components left out count as 0; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page -//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! says. A color read from an object gives that object the same color when it is assigned back. +//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it +//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to +//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not //! assigned yet. use std::rc::Rc; @@ -66,7 +69,7 @@ fn shown(v: f32, scale: f64) -> f64 { } /// The color object for a solid color. -fn of_color(c: &Color) -> Data { +pub(in crate::script) fn of_color(c: &Color) -> Data { match *c { Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), Color::Cmyk { c, m, y, k } => color_object( @@ -149,6 +152,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result std::result::Result { + let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor")); + match assigned(d, what) { + Ok(Some(c)) => Ok(c), + // A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error. + Ok(None) | Err(HostError::Error(_)) => Err(not_solid()), + Err(e) => Err(e), + } +} + /// `color` as `paint.setFill` and `paint.setStroke` take it. pub(super) fn param(color: &Color) -> Value { serde_json::to_value(color).unwrap_or(Value::Null) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index efe237d02c..6a4c0e1d08 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -839,7 +839,8 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { /// `removeAll()`: deletes every object the collection lists (those inside another listed one go /// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or /// one on a locked artboard stops it before anything is deleted, as the document's -/// `pageItems.removeAll()` is stopped. +/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an +/// ordinary group named as a tracing. fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index da8ac4c6b0..1aa8615574 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -170,6 +170,8 @@ fn path_ref(h: &super::Host, item: Item) -> Data { /// The index of the first point of each subpath of `subs`, followed by the number of points. fn starts(subs: &[SubPath]) -> Vec { + #[cfg(test)] + crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1)); let mut out = Vec::with_capacity(subs.len() + 1); let mut n = 0; for sp in subs { @@ -1902,18 +1904,17 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { .filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())])) .flatten() .collect(); - let partial = sel.partial(item.id).filter(|_| !held); - let mut picked = Vec::new(); - let mut offset = 0; - for (s, sp) in pd.subpaths.iter().enumerate() { - for j in 0..sp.anchors.len() { - if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) { - picked.push(offset + j); - } - } - offset += sp.anchors.len(); + let firsts = starts(&pd.subpaths); + match sel.partial(item.id).filter(|_| !held) { + // Direct-selected anchors that no selected segment ends at, in subpath and anchor + // order, which is the order of `pathPoints`. + Some(anchors) => anchors + .iter() + .filter(|&&(s, j)| pd.subpaths.get(s).is_some_and(|sp| j < sp.anchors.len()) && !ends.contains(&(s, j))) + .filter_map(|(s, j)| firsts.get(*s).map(|first| first + j)) + .collect(), + None => (0..firsts.last().copied().unwrap_or(0)).collect(), } - picked })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index c4308efba2..cec96feeec 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -279,6 +279,8 @@ fn set_warning(h: &Host, on: bool) -> Answer { error_icon: false, no_as_default: true, preset: String::new(), + color: None, + cmyk_document: false, }; if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) { return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into())); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d5dbbc1bb8..285c338a2a 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -3188,6 +3188,9 @@ thread_local! { pub(crate) static TEST_GROWTH_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; + /// Tests: how many times the object model worked out where the points of each subpath of a + /// path start. + pub(crate) static LAYOUTS_BUILT: Cell = const { Cell::new(0) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index a63a712918..7d3c2eaf9e 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -236,6 +236,17 @@ impl Palettes { None } + /// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the + /// line is empty or starts with an event that can still run. + fn drop_stale(&mut self) { + while let Some(q) = self.waiting.front() { + if self.resolved(q.clone()).is_some() { + break; + } + self.waiting.pop_front(); + } + } + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other /// engines' palettes keep their places in line. Events whose file access scopes do not cover /// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest @@ -252,7 +263,13 @@ impl Palettes { /// The taken event `q` given to its control in its palette, and that palette, or `None` when it /// is dropped ([`Palettes::next`]). - fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> { + let (p, q) = self.resolved(q)?; + Some((p.clone(), q)) + } + + /// [`Palettes::checked`] without the copy of the palette. + fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> { let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; if let Some(c) = control_of(&mut q.event) { *c = p.dialog.index_of(q.element?)?; @@ -271,7 +288,7 @@ impl Palettes { } else { q.event = scriptui::check_event(&p.dialog, q.event).ok()?; } - Some((p.clone(), q)) + Some((p, q)) } /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` @@ -414,6 +431,12 @@ impl Session { self.script_palettes.waiting.len() } + /// The number of the last palette event put in line, which an event added, or merged into a + /// waiting one, changes. + pub fn script_palette_last_ticket(&self) -> u64 { + self.script_palettes.last_ticket + } + /// The changes that wait for a run, as (palette id, the id of the control they change). pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> { self.script_palettes @@ -456,7 +479,12 @@ impl Session { /// run is going or no event waits; otherwise the run's name, or the error that ended it before /// it began. An open edit that cannot be settled gives its error, and the events keep waiting. pub fn script_palette_start(&mut self) -> Option> { - if self.script_running() || self.script_palettes.waiting.is_empty() { + if self.script_running() { + return None; + } + // Events that can no longer run do not settle the open edit. + self.script_palettes.drop_stale(); + if self.script_palettes.waiting.is_empty() { return None; } // An event waits while a drag or an undo group is open, which a run cannot start in. @@ -507,6 +535,9 @@ impl Session { let want = self.script_palettes.last_ticket; let mut mine = None; loop { + if !self.script_running() { + self.script_palettes.drop_stale(); + } if !self.script_running() && !self.script_palettes.waiting.is_empty() && let Err(e) = self.settle_for_script() diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e48a8f6f38..c18d895ad3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -14,3 +14,6 @@ mod documents; mod edit; mod execute; mod undo; + +#[cfg(test)] +pub(crate) use edit::previews_run; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 367334a008..03584189f1 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,6 +165,8 @@ impl Session { liquify_stroke: None, plane_widget_press: false, pointer_held: false, + holds_previews: false, + sampled_preview: None, press_options: None, press_options_stored: false, press_type_selection: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 12f8cbe879..604ca822df 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -4,6 +4,18 @@ use super::{ }; use crate::doc_state::{kept_from, objects_only}; +#[cfg(test)] +thread_local! { + /// How many times [`Session::preview`] ran on this thread. + static PREVIEWS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`Session::preview`] has run on this thread. +#[cfg(test)] +pub(crate) fn previews_run() -> usize { + PREVIEWS.get() +} + impl Session { /// Takes committed swatch renames as (document uid, old name, new name) in execution order and leaves the record empty. /// The uid identifies the originating document through [`crate::DocState::uid`]. @@ -583,6 +595,8 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { + #[cfg(test)] + PREVIEWS.set(PREVIEWS.get() + 1); self.put_back_interaction(); if self.script_running() { return Err(EngineError::Busy); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 3be402bb94..8f81f57e6e 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -320,6 +320,192 @@ fn pencil_continues_selected_open_path() { assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 100.0)); } +/// The document without its creation time, the selection and the new-art paints. +type Drawn = (vectorcraft_doc::Document, vectorcraft_doc::Selection, vectorcraft_tools::PaintDefaults); + +fn drawn(s: &Session) -> Drawn { + let st = s.doc().unwrap(); + let mut doc = (*st.doc).clone(); + // `file.new` stamps the time in seconds, which differs between two sessions made a second apart. + doc.metadata.created = None; + (doc, st.selection.clone(), s.paint.clone()) +} + +/// Draws `pts` with the Pencil in a session that `setup` prepared, handing the drag's samples and the release to the +/// session in groups of 4, the release in the last group: through [`Session::pointer_samples`] with `by_frame`, else +/// one at a time through [`Session::pointer`]. What [`drawn`] gives after each group, the previews each group ran, +/// and the previews a group runs when its drags preview once: one for its drags and one for its release. +fn pencil_in_frames(setup: &dyn Fn(&mut Session), pts: &[(f64, f64)], by_frame: bool) -> (Vec, Vec, Vec) { + let mut s = session(); + setup(&mut s); + let v = view(); + s.select_tool("pencil", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap(); + let mut samples: Vec = pts[1..].iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)).collect(); + let l = pts[pts.len() - 1]; + samples.push(PointerEvent::new(PointerKind::Up, l.0, l.1)); + let (mut states, mut previews, mut once) = (vec![], vec![], vec![]); + for group in samples.rchunks(4).rev() { + let has = |kind| usize::from(group.iter().any(|ev| ev.kind == kind)); + once.push(has(PointerKind::Drag) + has(PointerKind::Up)); + let before = crate::session::previews_run(); + if by_frame { + let (fed, r) = s.pointer_samples(group, v); + r.unwrap(); + assert_eq!(fed, group.len(), "every sample fed"); + } else { + for ev in group { + s.pointer(ev, v).unwrap(); + } + } + previews.push(crate::session::previews_run() - before); + states.push(drawn(&s)); + } + (states, previews, once) +} + +/// The drag samples of a frame of up to 4 Pencil samples run one preview, the last sample's, before the release when +/// the frame ends with it, and leave the document, the selection and the new-art paints as handing the samples over one +/// by one does, after every frame: for a new stroke, for strokes that continue a selected path at its end and at its +/// start, and with New Art Has Basic Appearance off and an empty starting selection. Every sample is previewed when +/// inheriting a selected gradient, with two selected paths in a group, during a Global Edit, or with Objects on Path selected. +#[test] +fn pencil_samples_of_one_frame_run_one_preview() { + let none = |_: &mut Session| {}; + let selected_line = |s: &mut Session| { + line(s, 100.0, 100.0, 200.0, 100.0); + }; + let not_basic = |s: &mut Session| { + rect(s, 400.0, 400.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + }; + let selected_gradient = |s: &mut Session| { + rect(s, 400.0, 400.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.select_tool("pencil", view()).unwrap(); + s.set_tool_option("fill", &json!(true)); + s.set_tool_option("keepSelected", &json!(true)); + }; + let grouped_paths = |s: &mut Session| { + let a = line(s, 100.0, 100.0, 200.0, 100.0); + let b = line(s, 400.0, 200.0, 420.0, 200.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + }; + let new_stroke = wave(100.0, 180.0, 300.0); + let wavy = + |x0: f64, step: f64| -> Vec<(f64, f64)> { (0..=40).map(|i| (x0 + step * f64::from(i), 101.0 + 10.0 * (f64::from(i) / 6.0).sin())).collect() }; + let (past_end, before_start) = (wavy(202.0, 2.0), wavy(99.0, -2.0)); + // A Global Edit preview also changes the other members, which the tool reads for its next sample. + let global_edit = |s: &mut Session| { + let a = line(s, 100.0, 100.0, 200.0, 100.0); + line(s, 100.0, 140.0, 200.0, 140.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.execute("select.globalEdit", &json!({})).unwrap()["active"], true); + }; + // Continuing the spine of an Objects on Path group moves the attached art, so every sample is previewed. + let objects_on_path = |s: &mut Session| { + let spine = line(s, 100.0, 100.0, 200.0, 100.0); + let attached = line(s, 400.0, 200.0, 420.0, 200.0); + s.execute("object.objectsOnPath.attach", &json!({"path": spine.0, "ids": [attached.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [spine.0]})).unwrap(); + }; + // The name, the setup, the stroke, the paths after the release, and whether a frame previews once. + type Case<'a> = (&'a str, &'a dyn Fn(&mut Session), &'a [(f64, f64)], usize, bool); + let cases: [Case; 8] = [ + ("new stroke", &none, &new_stroke, 1, true), + ("continues the end", &selected_line, &past_end, 1, true), + ("continues the start", &selected_line, &before_start, 1, true), + ("basic appearance off", ¬_basic, &new_stroke, 2, true), + ( + "inherits a selected gradient", + &selected_gradient, + &[(100.0, 180.0), (120.0, 180.0), (140.0, 180.0), (160.0, 200.0), (180.0, 220.0), (200.0, 230.0)], + 2, + false, + ), + ("two selected paths in a group", &grouped_paths, &past_end, 2, false), + ("global edit", &global_edit, &past_end, 2, false), + ("objects on path", &objects_on_path, &past_end, 2, false), + ]; + for (name, setup, pts, path_count, once) in cases { + let (one_by_one, each, _) = pencil_in_frames(setup, pts, false); + let (by_frames, previews, expected) = pencil_in_frames(setup, pts, true); + if once { + assert_eq!(previews, expected, "{name}: one preview for the drags of a frame, and one for its release"); + } else { + assert_eq!(previews, each, "{name}: a preview per sample"); + } + assert_eq!(by_frames.len(), one_by_one.len(), "{name}"); + for (k, (a, b)) in by_frames.iter().zip(&one_by_one).enumerate() { + assert!(a == b, "{name}: state {k} differs from handing the samples over one by one"); + } + let mut paths = 0; + by_frames[by_frames.len() - 1].0.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(paths, path_count, "{name}: paths after the release"); + } +} + +/// One call that carries a Pencil release and the next stroke's press and drags previews every drag of the second +/// stroke when that stroke begins with the first one selected and New Art Has Basic Appearance off, and leaves the +/// document, the selection and the new-art paints as handing the events over one by one does. +#[test] +fn pencil_samples_spanning_two_strokes_decide_again_after_the_press() { + let v = view(); + let setup = || { + let mut s = session(); + rect(&mut s, 400.0, 400.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("pencil", v).unwrap(); + s.set_tool_option("fill", &json!(true)); + s.set_tool_option("keepSelected", &json!(true)); + assert!(s.doc().unwrap().selection.is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + for (x, y) in [(120.0, 100.0), (140.0, 120.0), (160.0, 130.0)] { + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + } + s + }; + let mut batched = setup(); + let mut individual = setup(); + let mut samples = vec![PointerEvent::new(PointerKind::Up, 160.0, 130.0), PointerEvent::new(PointerKind::Down, 100.0, 220.0)]; + let drags = [ + (120.0, 220.0), + (140.0, 220.0), + (160.0, 220.0), + (180.0, 220.0), + (200.0, 220.0), + (220.0, 240.0), + (240.0, 260.0), + (260.0, 280.0), + (280.0, 290.0), + (300.0, 300.0), + ]; + samples.extend(drags.iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y))); + let before = crate::session::previews_run(); + let (fed, result) = batched.pointer_samples(&samples, v); + result.unwrap(); + let batched_previews = crate::session::previews_run() - before; + assert_eq!(fed, samples.len(), "every sample fed"); + let before = crate::session::previews_run(); + individual.pointer(&samples[0], v).unwrap(); + let release_previews = crate::session::previews_run() - before; + assert!(!individual.doc().unwrap().selection.is_empty()); + for ev in &samples[1..] { + individual.pointer(ev, v).unwrap(); + } + let individual_previews = crate::session::previews_run() - before; + assert_eq!(individual_previews, drags.len() + release_previews, "each drag runs a preview"); + assert_eq!(batched_previews, individual_previews, "the batch runs every preview"); + assert!(drawn(&batched) == drawn(&individual), "document, selection and new-art paints match"); +} + /// Connect two paths: with two open paths selected, a Pencil stroke from an end of one to an end /// of the other joins them into one path, the first one's, in one undo step. A path that is not /// selected is not joined. diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 19cbe75c56..c61257c614 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -443,6 +443,55 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() { undo_gives_back(&mut s, &before); } +/// A Pencil stroke of 100 moves over 20,000 squares previews the path at every move. Each preview +/// starts again from the document as it was at the press, whose lookup cache does not hold the new +/// path; the first preview finds the path by walking the tree, and the later ones find it at the +/// place that walk found. The release leaves one new path, selected, as one undo step; Group puts it +/// in a group, and Undo puts it back and then removes it. A stroke canceled part way leaves no path. +#[test] +fn pencil_previews_find_the_new_path_without_walking_the_tree() { + let mut s = session(20_000, square); + s.execute("select.none", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let first = before.peek_next_id(); + let v = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("pencil", v).unwrap(); + let at = |kind, i: usize| PointerEvent::new(kind, 10.0 + 3.0 * i as f64, 50.0 + 20.0 * (i as f64 / 10.0).sin()); + s.pointer(&at(PointerKind::Down, 0), v).unwrap(); + s.pointer(&at(PointerKind::Drag, 1), v).unwrap(); + let (walks, revision) = (vectorcraft_doc::tree_walks(), s.doc().unwrap().revision); + for i in 2..=100 { + s.pointer(&at(PointerKind::Drag, i), v).unwrap(); + } + let (walks, previews) = (vectorcraft_doc::tree_walks() - walks, (s.doc().unwrap().revision - revision) / 2); + assert!(previews >= 99, "{previews} previews for 99 moves"); + assert!(walks <= 2, "{previews} previews walked the tree {walks} times"); + s.pointer(&at(PointerKind::Up, 100), v).unwrap(); + let path = NodeId(first); + assert_eq!(layer(&s, 0).len(), 20_001); + assert!(s.doc().unwrap().doc.node(path).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); + assert!(selected(&s, &[path])); + let layer_id = before.layers[0].id; + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.ancestry(path), Some(vec![layer_id, group, path])); + assert_eq!(children(&s, group), [path]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.ancestry(path), Some(vec![layer_id, path])); + assert!(s.doc().unwrap().doc.node(group).is_none()); + undo_gives_back(&mut s, &before); + assert!(s.doc().unwrap().doc.node(path).is_none()); + + // The same stroke, canceled after 50 moves. + s.pointer(&at(PointerKind::Down, 0), v).unwrap(); + for i in 1..=50 { + s.pointer(&at(PointerKind::Drag, i), v).unwrap(); + } + assert!(s.doc().unwrap().doc.node(path).is_some(), "the preview holds the path"); + s.cancel_interaction().unwrap(); + assert!(*s.doc().unwrap().doc == *before, "Cancel gives back the document"); + assert!(s.doc().unwrap().doc.node(path).is_none() && s.doc().unwrap().doc.index_path(path).is_none()); +} + /// The ids under `n`: a child that can hold children is a list of its id and theirs. fn outline(n: &Node) -> Value { let ids = n.children().into_iter().flatten().map(|c| match c.children() { diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index 0ebb346fe7..3bd15e3fa8 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -177,6 +177,8 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, + cmyk_document: false, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); @@ -343,3 +345,103 @@ fn a_dialog_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); assert_eq!(r["dialogCount"], 0); } + +/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns. +const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() { + let mut s = one_doc(); + let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());"); + let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})])) + .unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}"); + let dialogs = r["dialogs"].as_array().unwrap(); + assert_eq!(dialogs.len(), 2); + assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}"); + assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null"); + let cmyk = headless( + &mut s, + "var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);", + answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]), + ) + .unwrap(); + assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}"); +} + +#[test] +fn the_color_picker_ends_the_run_when_no_answer_is_left() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] { + let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}"); + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains("showColorPicker") && e.contains(says), "{e}"); + assert_eq!(art(&s), before, "the run's edit goes back"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } + let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string(); + assert!(a.contains("is for colorPicker, not alert"), "{a}"); +} + +#[test] +fn the_color_picker_refuses_what_is_not_a_solid_color() { + let mut s = one_doc(); + let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\ + try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\ + try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());"; + let r = headless(&mut s, source, json!([])).unwrap(); + assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); + assert_eq!(r["dialogCount"], 0, "no picker opened"); + for bad in [ + json!("not a color"), + json!([255, 0, 0]), + json!({"model": "lab", "l": 120, "a": 0, "b": 0}), + json!(true), + json!("rgb 300 0 0"), + json!("cmyk 0 0 0 101"), + json!("gray -1"), + json!("lab 50 200 0"), + json!("rgb 255.000001 0 0"), + json!([1.00000001, 0, 0]), + json!({"c": 100.000001, "m": 0, "y": 0, "k": 0}), + json!({"gray": 100.000001}), + json!({"l": 100.000001, "a": 0, "b": 0}), + json!({"model": "rgb", "r": 1.00000001, "g": 0, "b": 0}), + json!({"model": "lab", "l": 50, "a": -128.000001, "b": 0}), + ] { + let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); + assert!(e.contains("color picker's answer"), "{bad}: {e}"); + } + for good in [ + json!("rgb 255 0 0"), + json!("cmyk 0 100 100 0"), + json!("gray 100"), + json!("lab 50 -128 128"), + json!([1, 0, 0]), + json!({"c": 0, "m": 100, "y": 100, "k": 0}), + json!({"gray": 100}), + json!({"l": 100, "a": -128, "b": 128}), + json!({"model": "rgb", "r": 1, "g": 0, "b": 0}), + ] { + assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}"); + } +} + +#[test] +fn a_framed_run_waits_at_the_color_picker() { + let mut s = one_doc(); + framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);")); + let d = s.script_dialog().unwrap(); + assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))))); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given"); + assert!(s.script_answer(DialogAnswer::ColorPicker(None))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 61f0b8d6dc..1af3310d61 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1541,6 +1541,22 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); } +/// A layout that replaces the rows keeps the columns the rows gave the artboards there are now, +/// whether or not the change of artboards came with a layout of its own. +#[test] +fn replacing_rows_keeps_the_columns_of_the_artboards_there_are_now() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + for change in [json!({"artboards": 9}), json!({"artboards": 9, "artboardLayout": {"spacing": 20}})] { + let more = settings.clone().with_params(&change, "file.new").unwrap(); + for layout in [json!("gridByRow"), json!({"layout": "gridByRow"})] { + let by_row = more.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!(by_row.grid_columns(), 3, "{change} then {layout}"); + } + } +} + #[test] fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 7486a07d33..df15b5c6ea 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::Point; use vectorcraft_geom::path::AnchorKind; use crate::*; @@ -420,6 +421,9 @@ fn path_point_setters_edit_one_anchor() { for i in [0, 2, 3] { assert_eq!(anchors[i], anchors_before[i], "point {i} did not change"); } + // The 300 pt tall document's y runs down, so script y 285 is document y 15. + let edited = &anchors[1]; + assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0))); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite")); @@ -2385,6 +2389,95 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } +/// Reading and moving each point of a path with many subpaths works out where the subpaths' points +/// start a few times for the whole loop, not once or more for each point. +#[test] +fn reading_and_moving_points_counts_the_subpaths_a_few_times() { + let (mut s, _, _) = doc(); + let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect(); + let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + crate::script::LAYOUTS_BUILT.with(|n| n.set(0)); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\ + vc.log(pp.length);", + ); + assert_eq!(out, vec![json!(1000)]); + let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get); + assert!(built < 10, "{built} layouts for 1000 points"); + let n = node(&s, id); + let ys: Vec = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect(); + assert_eq!(ys.len(), 1000); + assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up"); +} + +/// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the +/// order of `pathPoints`, whatever order they were selected in. +#[test] +fn selected_path_points_follow_the_order_of_path_points_across_subpaths() { + let (mut s, _, _) = doc(); + let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\ + for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);", + ); + assert_eq!(out, vec![json!([0, 10, 30])]); +} + +/// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a +/// key that nothing has reads as `undefined`. +#[test] +fn collections_find_names_that_read_as_numbers() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\ + vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\ + vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);", + ); + assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]); +} + +/// `typename` of a point or a point list throws for one that is stale, as the other members do. +#[test] +fn stale_points_throw_on_typename() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\ + try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\ + var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\ + try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]); +} + +/// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose +/// id a double rounds to. +#[test] +fn made_paths_keep_ids_past_two_to_the_53() { + let (mut s, _, _) = doc(); + let big = 1u64 << 53; + s.edit("Raise Ids", |d, _| { + d.raise_next_id(big); + Ok(()) + }) + .unwrap(); + let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + assert_eq!(old.0, big); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';"); + assert_eq!(node(&s, old).name, None); + assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made")); + assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed")); +} + /// A point change made before a call that fails and is put back, here a new document whose /// profile cannot be read, is kept. #[test] diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index e8826c13b9..1eaff02d45 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -104,6 +104,8 @@ fn yes_to_the_confirm_turns_the_warning_off() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, + cmyk_document: false, }; assert_eq!(s.script_dialog(), Some(want)); assert!(s.script_dialog_turns_warning_off()); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index ede881af0d..4d25502a28 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -135,6 +135,45 @@ fn added_group_named_as_seam_fills_is_counted() { let _ = std::fs::remove_dir_all(base); } +/// `groupItems.removeAll()` of a group and the document's `compoundPathItems.removeAll()` refuse +/// to leave an image at the bottom of an ordinary group named as a tracing, before the document +/// changes. +#[test] +fn group_and_compound_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let compound = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\ + vc.run('object.compoundPath.make'); return d.pageItems[0]; })()"; + let group = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); return d.pageItems[0]; })()"; + for (name, bottom, list) in + [("group-remove-all-groups", group, "groupItems[0].groupItems"), ("remove-all-compounds", compound, "compoundPathItems")] + { + let base = folder(name); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(d.pageItems[0].typename);" + ), + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}"); + assert!(traces(&s).is_empty(), "{list}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}"); + assert_eq!(undo_steps(&s), steps, "{list}"); + let _ = std::fs::remove_dir_all(base); + } +} + #[test] fn trace_image_resolution_is_one_number_or_none() { let base = folder("resolution"); diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index cf873ec324..6908ef08ea 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -563,6 +563,32 @@ fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { assert_eq!(s.script_palette_events_waiting(), 0); } +#[test] +fn a_line_of_clicks_that_can_no_longer_run_does_not_settle_the_open_edit() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + // Settling would fail here, so a start that tries to settle gives an error. + SETTLE_FAILS.with(|f| f.set(true)); + let started = s.script_palette_start(); + SETTLE_FAILS.with(|f| f.set(false)); + assert!(started.is_none(), "the stale click does not settle the open edit: {:?}", started.map(|r| r.map_err(|e| e.to_string()))); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 27b8d22078..4655bbaa61 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -753,6 +753,94 @@ impl Session { r } + /// [`Self::pointer`] for each of `evs`, the samples one frame delivers to a tool that builds its + /// stroke from every position the pointer passed ([`Self::tool_wants_samples`]), and the release + /// when it comes in that frame. The tool gets every sample, but of a run of previews of one + /// command only the last is applied, since each preview replaces the one before it. Every other + /// action of the tool runs in its order, after the preview held before it. The held preview is + /// applied before the release or any other event that is not a drag, since the release reads the + /// document as the drag's preview left it. Every preview is applied during a Global Edit, with + /// Objects on Path selected, or with multiple objects selected, since a preview can change other + /// paths or their eligibility for joins. Every preview is also applied with New Art Has Basic + /// Appearance off when the interaction began with a selection, since previews then carry the + /// inherited new-art paints forward. The decision is made again after each event that is not a drag. + /// Feeding stops after a sample that fails, that asks the frontend for more than a status + /// message, or that leaves the tool computing an edit on another thread, so the frontend acts + /// on it before the samples after it. + /// Returns how many of `evs` were fed (at least one unless `evs` is empty) and what they ask of + /// the frontend. + pub fn pointer_samples(&mut self, evs: &[PointerEvent], view: ViewInfo) -> (usize, Result>) { + let mut ui = vec![]; + let mut failed = None; + let mut fed = 0; + let mut holds = self.holds_previews || !self.preview_affects_later_samples(); + let outer = std::mem::replace(&mut self.holds_previews, holds); + for ev in evs { + fed += 1; + if ev.kind != PointerKind::Drag && !outer { + self.holds_previews = false; + match self.apply_sampled_preview() { + Ok(asks) => ui.extend(asks), + Err(e) => { + failed.get_or_insert(e); + } + } + self.holds_previews = holds; + } + let result = self.pointer(ev, view); + if ev.kind != PointerKind::Drag { + holds = outer || !self.preview_affects_later_samples(); + self.holds_previews = holds; + } + match result { + Ok(asks) => { + let stop = asks.iter().any(|a| !matches!(a, UiRequest::Status(_))); + ui.extend(asks); + if stop || self.tool_edit_pending() { + break; + } + } + Err(e) => { + failed = Some(e); + break; + } + } + } + self.holds_previews = outer; + let held = if outer { Ok(vec![]) } else { self.apply_sampled_preview() }; + let r = match (failed, held) { + (Some(e), _) | (None, Err(e)) => Err(e), + (None, Ok(more)) => { + ui.extend(more); + Ok(ui) + } + }; + (fed, r) + } + + /// Whether each preview must run because it can change other paths, their eligibility for joins, + /// or the new-art paints inherited by later previews: with more than one object selected now or + /// when the interaction began, since the tool reads the other selected paths for joins. Before an + /// interaction opens, its starting selection is the active document's current selection. + fn preview_affects_later_samples(&self) -> bool { + self.active().is_some_and(|st| { + let selection = st.interaction.as_ref().map_or(&st.selection, |it| it.selection.as_ref()); + (!self.prefs.new_art_basic && !selection.is_empty()) + || selection.objects.len() > 1 + || st.selection.objects.len() > 1 + || st.global_edit.is_some() + || !crate::cmd::objects_on_path::groups_of(&st.doc, &st.selection.objects).is_empty() + }) + } + + /// Applies the preview [`Self::pointer_samples`] held, if any, as the tool's own action. + fn apply_sampled_preview(&mut self) -> Result> { + match self.sampled_preview.take() { + Some((cmd, p)) => self.apply_actions(vec![Action::Preview(cmd, p)]), + None => Ok(vec![]), + } + } + /// The number of the next pointer or key event handed to the session. fn next_input(&mut self) -> u64 { let n = self.input_count; @@ -1868,9 +1956,23 @@ impl Session { r } + /// [`Self::run_tool_actions`], holding the previews while [`Self::pointer_samples`] runs. Actions + /// that these actions lead to run with nothing held. fn apply_tool_actions(&mut self, acts: Vec) -> Result> { + let holds = std::mem::take(&mut self.holds_previews); + let r = self.run_tool_actions(acts, holds); + self.holds_previews = holds; + r + } + + /// Runs the tool's actions in order. With `holds`, a preview is kept in [`Self::sampled_preview`] + /// in place of the one kept before it, and the kept preview is applied before any other action. + fn run_tool_actions(&mut self, acts: Vec, holds: bool) -> Result> { let mut ui = vec![]; for a in acts { + if let Some((cmd, p)) = self.sampled_preview.take_if(|(held, _)| !matches!(&a, Action::Preview(cmd, _) if *cmd == *held)) { + self.run_preview(&cmd, &p, &mut ui); + } match a { Action::Begin(label) => { // The snapshot of the interaction open before, which the tool's drag then joins. @@ -1896,17 +1998,13 @@ impl Session { } continue; } - self.clear_deferred_overlay_cache(); - match self.preview(&cmd, &p) { - Ok(v) => { - if let Some(w) = v.get("warning").and_then(Value::as_str) - && !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w)) - { - ui.push(UiRequest::Status(w.to_string())); - } - } - Err(e) => log::warn!("preview {cmd}: {e}"), + if holds { + self.sampled_preview = Some((cmd, p)); + continue; } + // This preview replaces a held preview of the same command. + self.sampled_preview = None; + self.run_preview(&cmd, &p, &mut ui); } // The drag is over: the dabs of a Liquify stroke have no further use. Action::Commit => { @@ -1968,6 +2066,22 @@ impl Session { Ok(ui) } + /// Applies the tool's preview of `cmd` with `p`. Its warning goes to `ui` once; a failed preview + /// is logged and leaves the interaction open. + fn run_preview(&mut self, cmd: &str, p: &Value, ui: &mut Vec) { + self.clear_deferred_overlay_cache(); + match self.preview(cmd, p) { + Ok(v) => { + if let Some(w) = v.get("warning").and_then(Value::as_str) + && !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w)) + { + ui.push(UiRequest::Status(w.to_string())); + } + } + Err(e) => log::warn!("preview {cmd}: {e}"), + } + } + /// With Real-time Drawing off, the selection's transform box ([`Session::transform_box`]) as the /// pending preview of a handle resize or of a shape being drawn leaves it, measured once per /// preview step, with the layer color of the first object it measures; `None` when no such diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1b959de54d..28448679d2 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -112,7 +112,8 @@ const INSIDE: &[(&str, &str)] = &[ concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \ executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \ invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \ - printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \ + printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \ + unloadAction= \ userInteractionLevel \ userInteractionLevel=", ), diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 0a8e63b3db..38f32cd1eb 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -1162,6 +1162,33 @@ fn native_source_without_composites_ignores_front_font_meaning() { // The file's undefined family is not given a new alias or post-adoption policy by this query test. } +#[test] +fn placed_family_undefined_in_its_source_keeps_its_measured_size_beside_a_destination_composite() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-undefined-family-placed"); + let path = dir.join("undefined-family.vectorcraft"); + let font = CompositeFont::new("NativePlacedUndefinedFamily", "Source Sans 3", "Regular"); + let mut source = font_document(&font); + source.composite_fonts = Vec::new().into(); + write_native(&path, &source); + let mut larger = font.clone(); + larger.parts.roman.size = 125.0; + let mut placed = Vec::new(); + for front_fonts in [Vec::new(), vec![larger]] { + let mut session = destination(&front_fonts); + let reply = session.execute("file.place", &json!({"path": path, "link": false, "crop": "bounding", "at": [30, 25]})).unwrap(); + let id = NodeId(reply["ids"][0].as_u64().unwrap()); + let again = place(&mut session, &path, false); + assert_eq!(placed_family(&session, again), placed_family(&session, id), "placing the same art again gives its family the same name"); + // Opening the saved result measures its type again in the fonts it draws with. + let bytes = vectorcraft_format::save_with(document(&session), &vectorcraft_format::SaveOptions::default()).unwrap(); + session.add_document(vectorcraft_format::load(&bytes).unwrap(), None); + let doc = document(&session); + placed.push(doc.node(id).unwrap().geometric_bounds_with(&doc.symbol_boxes()).unwrap()); + } + assert_eq!(placed[0], placed[1], "placed type keeps the size it was measured at, whatever composite the destination gives its family name"); +} + fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, classic: bool, mixed: bool) -> (Session, Document) { use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Effect}; diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 8864fc1911..ba8e7f69f3 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1802,7 +1802,13 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if !slot(i, win, SHOWN)?.truthy() { return Ok(()); } + let hides = number_slot(i, win, HIDES)?; let (desc, ..) = describe(i, win)?; + // A getter that hid or closed the palette leaves the host the controls it had then. + let same = matches!(slot(i, win, PALETTE_ID)?, Value::Number(now) if now == id); + if !same || !slot(i, win, SHOWN)?.truthy() || number_slot(i, win, HIDES)? != hides { + return Ok(()); + } let f = host_fn(i, "paletteUpdate")?; i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; Ok(()) diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 11bde4ca26..7468e82cfd 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1250,6 +1250,22 @@ fn a_hidden_palette_is_not_described_after_the_run() { assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); } +#[test] +fn a_palette_a_title_getter_hides_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); var hiding = false; \ + Object.defineProperty(p, 'text', {get: function () { if (hiding) { hiding = false; p.hide(); return 'New'; } return 'T'; }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.run("hiding = true;").unwrap(); + r.refresh_script_ui().expect("the refresh reads the title"); + assert_eq!(r.run("[hiding, p.visible].join()").unwrap(), JsValue::String("false,false".into()), "the getter ran and hid the palette"); + assert_eq!(updates(&calls), before, "the host keeps the controls the palette had when it was hidden"); +} + #[test] fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); @@ -1339,19 +1355,24 @@ fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_th #[test] fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() { - let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); // The second read of the second item's text, which compares it with the items the person saw, - // changes the first item's text, which that comparison already took. - r.run( - "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ - l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ - Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \ - p.show();", - ) - .unwrap(); - let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); - assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); - assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); + // changes the first item's text, which that comparison already took. It also puts back a plain + // `b` in place of its getter, so that only the first item's change can end the choice: without + // that change, the same choice reaches `onChange`. + for (mutate, error, got) in [(true, "a palette's list changed before the person's choice was taken", ""), (false, "none", "a")] { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); + r.run(&format!( + "var mutate = {mutate}; var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; var second = l.items[1]; \ + Object.defineProperty(second, 'text', {{configurable: true, get: function () {{ if (reads >= 0 && ++reads == 2) {{ \ + if (mutate) {{ l.items[0].text = 'z'; }} Object.defineProperty(second, 'text', {{value: 'b', writable: true, configurable: true}}); }} \ + return 'b'; }}}}); p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(error.into()), "mutate: {mutate}"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String(got.into()), "mutate: {mutate}"); + } } #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 391c861e66..62d9ac97f8 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1144,7 +1144,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; 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 end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; 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 end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index da169f4d68..d57c34a315 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -563,7 +563,8 @@ impl Renderer { f.doc.setup.highlight_substituted_glyphs, o.highlight_alternate_glyphs, )); - (vectorcraft_text::layout_inputs(), crate::proof::overprints(f.opts), highlights).hash(&mut h); + // Color bitmap glyphs are sampled as images are (`draw_glyph_image`). + (vectorcraft_text::layout_inputs(), crate::proof::overprints(f.opts), highlights, o.smooth_images).hash(&mut h); } if reads.plugins || (doc.plugins && (reads.symbols || reads.patterns)) { (effects::plugin_revision(), doc.names, doc.patterns).hash(&mut h); diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 6f0f7cde99..e185504d05 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -285,11 +285,14 @@ fn area_spans(from: usize, to: usize) -> Vec> { .collect() } -/// A rendered image (premultiplied RGBA8, row-major). -pub struct Rendered { +/// A rendered image (premultiplied RGBA8, row-major). Its pixels are bytes, or, from +/// [`crate::Renderer::render_words`], words of four bytes that hold each pixel's bytes in memory +/// in the same order: a buffer aligned to four bytes, which a 4-byte pixel type can take over +/// without a copy. +pub struct Rendered

> { pub width: u32, pub height: u32, - pub pixels: Vec, + pub pixels: P, } impl Rendered { diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 9e44f5c655..80a5cb4b01 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -34,8 +34,8 @@ use crate::{Frame, RenderOptions, Rendered, Renderer}; const MAX_TILE_PX: f64 = 2048.0; /// What a tile is kept under: the pattern's name, the bits of its raster scale -/// ([`raster_scale`]), ink plane and undecoded-image mark setting. -type TileKey = (String, u64, Ink, bool); +/// ([`raster_scale`]), ink plane, and the undecoded-image mark and image smoothing settings. +type TileKey = (String, u64, Ink, (bool, bool)); /// What a tile was drawn from besides its pattern's own art, for art that shows more than itself: /// the art of every pattern and symbol and the pixels of every image in the document, the @@ -177,13 +177,13 @@ fn rasterize( region: Rect, size: (u16, u16), ink: Ink, - mark_undecoded_images: bool, + (mark_undecoded_images, smooth_images): (bool, bool), ) -> (Pixmap, bool) { let (w, h) = (size.0.max(1), size.1.max(1)); let mut ctx = crate::single_threaded_context(w, h); let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9)) * Affine::translate(-region.origin().to_vec2()); - let opts = RenderOptions { mark_undecoded_images, ..Default::default() }; + let opts = RenderOptions { mark_undecoded_images, smooth_images, ..Default::default() }; r.image_left_out = Some(false); let pattern_images_left_out = images_left_out(); r.check_plugins(doc); @@ -268,7 +268,8 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine, let (pw, ph) = def.period(); let scale = raster_scale(s, (pw, ph)); let params = (def.tile, def.tile_type, def.overlap); - let key = (name.to_string(), scale.to_bits(), ink, f.opts.mark_undecoded_images); + let images = (f.opts.mark_undecoded_images, f.opts.smooth_images); + let key = (name.to_string(), scale.to_bits(), ink, images); let cms = vectorcraft_color::cms::active(); let hit = CACHE.with(|c| { let mut c = c.borrow_mut(); @@ -297,9 +298,7 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine, let w = (pw * scale).ceil().clamp(1.0, 4096.0) as u16; let h = (ph * scale).ceil().clamp(1.0, 4096.0) as u16; let before = crate::paint::decode_failures(); - let Some((pm, image_left_out)) = - with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), (w, h), ink, f.opts.mark_undecoded_images)) - else { + let Some((pm, image_left_out)) = with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), (w, h), ink, images)) else { ctx.set_paint(missing()); return true; }; @@ -325,7 +324,9 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine, (pm, sx, sy) } }; - let sampler = ImageSampler { x_extend: Extend::Repeat, y_extend: Extend::Repeat, quality: ImageQuality::Medium, alpha: 1.0 }; + // With image smoothing off the tile is drawn with hard pixel edges, as its images were. + let quality = if f.opts.smooth_images { ImageQuality::Medium } else { ImageQuality::Low }; + let sampler = ImageSampler { x_extend: Extend::Repeat, y_extend: Extend::Repeat, quality, alpha: 1.0 }; ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler }); ctx.set_paint_transform(xf * Affine::scale_non_uniform(1.0 / sx, 1.0 / sy)); true @@ -338,7 +339,7 @@ pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option= 4, "smoothed: a ramp from black to white"); + assert_eq!(greys(false), 0, "not smoothed again: the smoothed tile is not shown"); +} + #[test] fn missing_pattern_is_grey() { let mut d = doc_with_pattern(TileType::Grid); diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index db565e982d..fab8122af4 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -49,9 +49,14 @@ const MAX_BYTES: usize = 4 * BUDGET; /// The smallest zoom step (device pixels per point). const MIN_STEP: f64 = 1.0 / 64.0; -/// A bitmap's identity: the file shown (its key), the zoom step's bits, and whether images whose -/// pixels can't be decoded are marked ([`crate::RenderOptions::mark_undecoded_images`]). -type BitmapKey = (String, u64, bool); +/// A bitmap's identity: the file shown (its key), the zoom step's bits, and how its images are +/// drawn: whether images whose pixels can't be decoded are marked +/// ([`crate::RenderOptions::mark_undecoded_images`]) and whether images are smoothed +/// ([`crate::RenderOptions::smooth_images`]). +type BitmapKey = (String, u64, Images); + +/// How a bitmap's images are drawn: (marked when undecoded, smoothed). +type Images = (bool, bool); struct Bitmap { pm: Arc, @@ -160,14 +165,16 @@ pub(crate) fn scheduled(key: &str) -> usize { #[cfg(test)] pub(crate) fn mark_unkept(key: &str, step: f64) { for mark in [false, true] { - lock(&UNKEPT).insert((key.to_string(), step.to_bits(), mark)); + for smooth in [false, true] { + lock(&UNKEPT).insert((key.to_string(), step.to_bits(), (mark, smooth))); + } } } /// `object`'s file (`blob`) as a bitmap of `step` device pixels per point, made here and now. #[cfg(test)] pub(crate) fn bitmap(object: &PlacedDocument, blob: &ImageBlob, step: f64, mark_undecoded_images: bool) -> Option { - make(&mut Renderer::new(), object, blob, step, mark_undecoded_images) + make(&mut Renderer::new(), object, blob, step, (mark_undecoded_images, true)) } /// The zoom step for `scale` device pixels per point: the power of two at or above it. @@ -184,9 +191,9 @@ impl Bitmaps { Some(b.pm.clone()) } - /// The bitmap of another step of the same file, with the same marks on undecoded images, the + /// The bitmap of another step of the same file, with its images drawn the same way, the /// nearest to `step`. - fn nearest(&self, key: &str, step: f64, mark: bool) -> Option<(Arc, f64)> { + fn nearest(&self, key: &str, step: f64, mark: Images) -> Option<(Arc, f64)> { self.map .iter() .filter(|((k, _, m), _)| k == key && *m == mark) @@ -368,11 +375,12 @@ pub(crate) fn enter_layer(n: &Node) -> Option { /// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent /// pixels through `view`, the placed documents inside it one level deeper. pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc, w: u16, h: u16, view: Affine) -> Option { - render_inside_marked(r, doc, art, w, h, view, false) + render_inside_marked(r, doc, art, w, h, view, (false, true)) } /// [`render_inside`], drawing images whose pixels can't be decoded as crossed boxes when -/// `mark_undecoded_images` is set ([`crate::RenderOptions::mark_undecoded_images`]). +/// `mark_undecoded_images` is set ([`crate::RenderOptions::mark_undecoded_images`]), and images +/// smoothed when `smooth_images` is set ([`crate::RenderOptions::smooth_images`]). fn render_inside_marked( r: &mut Renderer, doc: &vectorcraft_doc::Document, @@ -380,18 +388,18 @@ fn render_inside_marked( w: u16, h: u16, view: Affine, - mark_undecoded_images: bool, + (mark_undecoded_images, smooth_images): Images, ) -> Option { let _inside = Inside::enter(); - let opts = crate::RenderOptions { mark_undecoded_images, ..Default::default() }; + let opts = crate::RenderOptions { mark_undecoded_images, smooth_images, ..Default::default() }; r.render_node_with(doc, art, w, h, view, &opts) } /// `object`'s file (`blob`) as a bitmap of `step` device pixels per point of its box: from its /// preview when that is all there is and is fine enough, else from the file (read again when /// needed; the preview when it can't be). Images whose pixels can't be decoded are drawn as -/// crossed boxes when `mark_undecoded_images` is set. -fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64, mark_undecoded_images: bool) -> Option { +/// crossed boxes when its first flag is set, and images are smoothed when its second is. +fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64, images: Images) -> Option { let (w, h) = (pixels(object.width * step), pixels(object.height * step)); let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() }; let full = match blob.is_proxy() { @@ -404,7 +412,7 @@ fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64, let f = e.frame; let (sx, sy) = (w as f64 / f.width(), h as f64 / f.height()); let view = Affine::scale_non_uniform(sx, sy) * Affine::translate((-f.x0, -f.y0)); - let img = render_inside_marked(r, &e.doc, &e.art, w, h, view, mark_undecoded_images)?; + let img = render_inside_marked(r, &e.doc, &e.art, w, h, view, images)?; let data = img.pixels.as_chunks::<4>().0.iter().map(|&[r, g, b, a]| vello_cpu::color::PremulRgba8 { r, g, b, a }).collect(); Some(Pixmap::from_parts(data, w, h)) } @@ -514,7 +522,7 @@ fn run_here(job: Job) { /// does where no worker starts, inside `scope`. #[cfg(test)] pub(crate) fn make_here(object: &PlacedDocument, blob: ImageBlob, step: f64, scope: Scoped) { - let key = (object.key.clone(), step.to_bits(), false); + let key = (object.key.clone(), step.to_bits(), (false, true)); lock(&PENDING).insert(key.clone()); run_here(Job { key, object: object.clone(), blob, step, keep: 0, scope: Some(scope) }); } @@ -608,7 +616,8 @@ impl Renderer { return false; } let Some(blob) = f.doc.images.get(&p.key).cloned() else { return true }; - let key = (p.key.clone(), step.to_bits(), f.opts.mark_undecoded_images); + let images = (f.opts.mark_undecoded_images, f.opts.smooth_images); + let key = (p.key.clone(), step.to_bits(), images); // Not kept past [`MAX_BYTES`]: drawn exactly. if lock(&UNKEPT).contains(&key) { return false; @@ -618,7 +627,7 @@ impl Renderer { // The clock when this frame first drew a placed document's bitmap. let keep = *self.placed_frame.get_or_insert(b.clock); let found = b.get(&key); - let nearest = if found.is_none() { b.nearest(&p.key, step, f.opts.mark_undecoded_images) } else { None }; + let nearest = if found.is_none() { b.nearest(&p.key, step, images) } else { None }; (found, nearest, keep) }; let shown = match found { @@ -629,14 +638,18 @@ impl Renderer { schedule(Job { key, object: p.clone(), blob, step, keep, scope: SCOPE_CAPTURE.get().map(|capture| capture()) }); // Made here and now (no threads) or meanwhile another step's. let mut b = lock(&BITMAPS); - b.get(&(p.key.clone(), step.to_bits(), f.opts.mark_undecoded_images)).or(nearest.map(|n| n.0)) + b.get(&(p.key.clone(), step.to_bits(), images)).or(nearest.map(|n| n.0)) } }; let rect = Rect::new(0.0, 0.0, p.width, p.height); match shown { Some(pm) => { let (sx, sy) = (p.width / pm.width().max(1) as f64, p.height / pm.height().max(1) as f64); - ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler: peniko::ImageSampler::default() }); + // With image smoothing off a bitmap (or a saved preview standing in for the file) + // keeps hard pixel edges when it is scaled. + let quality = if f.opts.smooth_images { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low }; + let sampler = peniko::ImageSampler { quality, ..Default::default() }; + ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler }); ctx.set_transform(m); ctx.set_paint_transform(Affine::scale_non_uniform(sx, sy)); ctx.fill_rect(&kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1)); @@ -675,7 +688,7 @@ mod tests { let mut b = Bitmaps::default(); // 400 bytes each: a budget of 1,000 bytes and at most 2,000. let limits = (1000, 2000); - let key = |name: &str| (name.to_string(), 1f64.to_bits(), false); + let key = |name: &str| (name.to_string(), 1f64.to_bits(), (false, true)); for name in ["a", "b", "c"] { assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, 0, limits)); } @@ -696,15 +709,16 @@ mod tests { } /// While a bitmap is made, another step's bitmap stands in only when it has the same marks on - /// undecoded images. + /// undecoded images and the same image smoothing. #[test] fn a_stand_in_bitmap_has_the_same_marks() { let mut b = Bitmaps::default(); let limits = (BUDGET, MAX_BYTES); - assert!(b.insert(("a".into(), 1f64.to_bits(), false), Pixmap::new(10, 10), 1.0, 0, limits)); - assert!(b.insert(("a".into(), 4f64.to_bits(), true), Pixmap::new(40, 40), 4.0, 0, limits)); - assert_eq!(b.nearest("a", 2.0, false).map(|n| n.1), Some(1.0)); - assert_eq!(b.nearest("a", 2.0, true).map(|n| n.1), Some(4.0)); - assert!(b.nearest("b", 2.0, false).is_none()); + assert!(b.insert(("a".into(), 1f64.to_bits(), (false, true)), Pixmap::new(10, 10), 1.0, 0, limits)); + assert!(b.insert(("a".into(), 4f64.to_bits(), (true, true)), Pixmap::new(40, 40), 4.0, 0, limits)); + assert_eq!(b.nearest("a", 2.0, (false, true)).map(|n| n.1), Some(1.0)); + assert_eq!(b.nearest("a", 2.0, (true, true)).map(|n| n.1), Some(4.0)); + assert!(b.nearest("b", 2.0, (false, true)).is_none()); + assert!(b.nearest("a", 2.0, (false, false)).is_none(), "smoothed bitmaps don't stand in for hard-edged ones"); } } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 9eb6082e37..1e32c3657b 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -117,9 +117,32 @@ impl Renderer { self.render_document(doc, width, height, view, opts, None) } + /// [`Self::render`] with the pixels in words of four bytes ([`Rendered`]), rendered into + /// that buffer. + pub fn render_words(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered> { + self.render_document(doc, width, height, view, opts, None) + } + /// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen /// group compositing require the full render. pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option { + self.plain_patch(doc, width, height, view, opts) + } + + /// [`Self::render_plain_patch`] with the pixels in words of four bytes, as + /// [`Self::render_words`] returns them. + pub fn render_plain_patch_words( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + ) -> Option>> { + self.plain_patch(doc, width, height, view, opts) + } + + fn plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option> { if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample { return None; } @@ -128,7 +151,7 @@ impl Renderer { (!hit.get()).then_some(image) } - fn render_document( + fn render_document( &mut self, doc: &Document, width: u32, @@ -136,7 +159,7 @@ impl Renderer { view: Affine, opts: &RenderOptions, patch: Option<&std::cell::Cell>, - ) -> Rendered { + ) -> Rendered

{ let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); self.render_as(doc, width, height, view, opts, false, 1, patch) @@ -147,7 +170,7 @@ impl Renderer { /// pixel of the output in pixels of this render: the supersampling factor while an export /// draws its art at several times its size, else 1 ([`Frame::output`]). #[allow(clippy::too_many_arguments)] - fn render_as( + fn render_as( &mut self, doc: &Document, width: u32, @@ -157,16 +180,18 @@ impl Renderer { inks: bool, cell: u32, patch: Option<&std::cell::Cell>, - ) -> Rendered { + ) -> Rendered

{ let start = now(); if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() { let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE)); if let Some(k) = supersample_factor(w, h) { let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() }; let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); - let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch); + let big: Rendered = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch); self.hairline = hairline; let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize); + drop(big); + let pixels = P::from_bytes(pixels); self.stats.micros = now().saturating_sub(start); return Rendered { width: w, height: h, pixels }; } @@ -203,12 +228,13 @@ impl Renderer { self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) { - let pixels = self - .mask_values(&frame, m, w, h) - .unwrap_or_else(|| vec![0; w as usize * h as usize]) - .into_iter() - .flat_map(|v| [v, v, v, 255]) - .collect(); + let pixels = P::from_bytes( + self.mask_values(&frame, m, w, h) + .unwrap_or_else(|| vec![0; w as usize * h as usize]) + .into_iter() + .flat_map(|v| [v, v, v, 255]) + .collect(), + ); self.end_frame(); self.stats.symbol_art = symbols.art_measured(); self.stats.micros = now().saturating_sub(start); @@ -219,23 +245,26 @@ impl Renderer { // proof that preserves the numbers, when one is on: the planes hold the inks as they // are, images included). let planes = if proof::preserving(opts).is_some() { None } else { frame.plates }; - let cmy = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h); + let cmy: Vec = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h); let stats = self.stats; - let k = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h); + let k: Vec = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h); self.stats = stats; - if inks { + let pixels = if inks { ink::amounts(&cmy, &k) } else { let (pixels, composed) = ink::compose(&cmy, &k, opts, threads); self.stats.ink_threads = composed; pixels - } + }; + drop((cmy, k)); + P::from_bytes(pixels) } else { self.draw_frame(&frame, w, h) }; self.end_frame(); - if !inks && !pixels.is_empty() { - proof::post(&mut pixels, opts); + let bytes = pixels.bytes_mut(); + if !inks && !bytes.is_empty() { + proof::post(bytes, opts); } self.stats.symbol_art = symbols.art_measured(); self.stats.micros = now().saturating_sub(start); @@ -325,7 +354,7 @@ impl Renderer { /// Draw frame `f` (`w`×`h` pixels): the artboards and the page's art, then the background /// under them. The art blends only with itself, as it does on the canvas, where the paper is /// drawn apart from it: a Screen glow on the bare page stays visible on a white background (#6125). - fn draw_frame(&mut self, f: &Frame, w: u16, h: u16) -> Vec { + fn draw_frame(&mut self, f: &Frame, w: u16, h: u16) -> P { let (threads, opts) = (self.threads, f.opts); let kept = self.contexts.iter().position(|(t, c)| *t == threads && c.width() == w && c.height() == h); let mut ctx = match kept.map(|i| self.contexts.remove(i)) { @@ -366,20 +395,19 @@ impl Renderer { } else { self.draw_page(&mut ctx, f); } - let pm = if f.patch_rejected() { + let pixels = if f.patch_rejected() { self.picture = None; None } else { - Some(self.finish(&mut ctx, self.raster)) + Some(P::finish(self, &mut ctx)) }; self.contexts.push((threads, ctx)); if self.contexts.len() > 2 { self.contexts.remove(0); } - let Some(pm) = pm else { return Vec::new() }; - let mut pixels = group::into_bytes(pm); + let Some(mut pixels) = pixels else { return P::from_bytes(Vec::new()) }; if let Some(bg) = opts.background { - over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg))); + over_background(pixels.bytes_mut(), f.ink.fixed8(screen_under_art(f, bg))); } pixels } @@ -413,15 +441,24 @@ impl Renderer { /// Render one artboard (or any document rect) at `scale` pixels per point, transparent or on white, /// as exported: template layers and guides are left out. pub fn render_region(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered { - let opts = RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() }; - self.render_region_with(doc, region, scale, &opts) + self.region(doc, region, scale, ®ion_options(white)) + } + + /// [`Self::render_region`] with the pixels in words of four bytes, as [`Self::render_words`] + /// returns them. + pub fn render_region_words(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered> { + self.region(doc, region, scale, ®ion_options(white)) } /// Render a document rect at `scale` pixels per point with `opts`. pub fn render_region_with(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered { + self.region(doc, region, scale, opts) + } + + fn region(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered

{ let (w, h) = region_pixels(region, scale); let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); - self.render(doc, w, h, view, opts) + self.render_document(doc, w, h, view, opts, None) } /// `region` of `doc` as ink amounts in the working CMYK space, 4 bytes a pixel (0 = no ink): @@ -433,7 +470,7 @@ impl Renderer { let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, w, h, view, opts, true, 1, None).pixels + self.render_as::>(doc, w, h, view, opts, true, 1, None).pixels } /// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels. @@ -544,6 +581,11 @@ impl Renderer { } } +/// The options of [`Renderer::render_region`]: as exported, transparent or on white. +fn region_options(white: bool) -> RenderOptions { + RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() } +} + /// The rasterizer settings for `opts`: the quality render mode when [`RenderOptions::precise`] is set. fn raster_settings(opts: &RenderOptions) -> vello_cpu::RasterizerSettings { let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed }; @@ -557,6 +599,58 @@ fn screen_under_art(f: &Frame, rgba: [u8; 4]) -> [u8; 4] { if matches!(f.ink.base(), Ink::Cmy | Ink::K) { rgba } else { proof::under_art(f.opts, rgba) } } +/// The buffer a frame's premultiplied RGBA pixels are returned in ([`Rendered::pixels`]). +pub(crate) trait FramePixels: Sized { + /// The pixels `ctx` holds, rendered by [`Renderer::finish`]'s rules. + fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self; + /// The pixels in `bytes` (four a pixel). + fn from_bytes(bytes: Vec) -> Self; + /// The pixels as bytes, four a pixel. + fn bytes_mut(&mut self) -> &mut [u8]; +} + +impl FramePixels for Vec { + fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self { + group::into_bytes(r.finish(ctx, r.raster)) + } + + fn from_bytes(bytes: Vec) -> Self { + bytes + } + + fn bytes_mut(&mut self) -> &mut [u8] { + self + } +} + +/// Each word holds a pixel's four bytes in memory in the order a byte buffer holds them. +impl FramePixels for Vec { + /// Over transparency, `ctx` renders straight into the words. Over a picture + /// ([`Renderer::finish`]), the rendered pixmap is copied into them. + fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self { + if r.picture.is_none() { + ctx.flush(); + let (w, h) = (ctx.width(), ctx.height()); + let mut words = vec![0u32; usize::from(w) * usize::from(h)]; + if let Some(target) = vello_cpu::PixmapMut::new(w, h, bytemuck::cast_slice_mut(&mut words)) { + ctx.render_with(target, &mut r.resources, r.raster); + #[cfg(test)] + group::FINISHED.with(|p| p.set(words.as_ptr() as usize)); + return words; + } + } + Self::from_bytes(group::into_bytes(r.finish(ctx, r.raster))) + } + + fn from_bytes(bytes: Vec) -> Self { + bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect() + } + + fn bytes_mut(&mut self) -> &mut [u8] { + bytemuck::cast_slice_mut(self) + } +} + /// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight). pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) { let alpha = u32::from(a); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 133e2356aa..afa49188c2 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -41,6 +41,7 @@ mod tileedge; mod typeedges; mod viewraster; mod widthzoom; +mod words; fn rect_node(d: &mut Document, r: Rect, fill: Paint, stroke: Paint, w: f64) -> Node { let id = d.alloc_id(); diff --git a/crates/render/src/tests/bitmapglyphs.rs b/crates/render/src/tests/bitmapglyphs.rs index 184b92bcff..d1a96458ae 100644 --- a/crates/render/src/tests/bitmapglyphs.rs +++ b/crates/render/src/tests/bitmapglyphs.rs @@ -74,6 +74,41 @@ fn bitmap_glyphs_go_with_type_that_a_geometry_effect_reshapes() { assert_eq!(img.pixel(50, 80), [255, 255, 255, 255], "not where it was"); } +/// Bitmap glyphs are sampled as images are (File Handling › Display Bitmaps as Anti-aliased Images, +/// #10712), so a raster kept for type, such as a blur's, is made again when image smoothing changes. +#[test] +fn rasters_of_type_follow_image_smoothing() { + let _adding = crate::tests_fontchange::adding_fonts(); + vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap()); + let mut d = Document::new(160.0, 160.0); + let st = CharStyle { font_family: colour_bitmap_family(false).into(), size: 100.0, ..Default::default() }; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 120.0), &COLOUR_CHAR.to_string(), st)))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n.clone()).unwrap(); + let symbols = d.symbol_boxes().quick(); + let mut r = Renderer::new(); + let mut inputs = |smooth_images: bool| { + let opts = RenderOptions { smooth_images, ..Default::default() }; + let f = Frame { + mt: false, + patch: None, + doc: &d, + symbols: &symbols, + view: Affine::IDENTITY, + visible: vectorcraft_geom::Rect::new(0.0, 0.0, 160.0, 160.0), + px: 1.0, + opts: &opts, + ink: crate::ink::Ink::Display, + output: Affine::IDENTITY, + plates: None, + }; + r.raster_inputs(&f, &n, crate::fx::Reads::of(&n)) + }; + let smoothed = inputs(true); + assert!(inputs(true) == smoothed, "the same settings: the same inputs"); + assert!(inputs(false) != smoothed, "image smoothing changed: the raster is made again"); +} + /// A colour adjustment leaves the emoji of reshaped type in their colours, as it does those of /// type, and as exports and Expand Appearance draw them. #[test] diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 028647c9eb..d7606f3094 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -10,8 +10,9 @@ use crate::*; /// Every file reads as a 40×20 artboard filled blue; a file whose bytes start with `loop` also /// places itself (the same key) in its middle, one whose bytes start with `cut` also shows an /// image whose pixels can't be decoded over its left half, one whose bytes start with `pict` also -/// shows a linked red image over its left half (its own Show Images in Outline Mode off), and one -/// whose bytes start with `bad` can't be read. +/// shows a linked red image over its left half (its own Show Images in Outline Mode off), one +/// whose bytes start with `checker` also shows a 2×2 black and white checker image over all of it, +/// and one whose bytes start with `bad` can't be read. fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { if bytes.starts_with(b"bad") { return None; @@ -49,6 +50,23 @@ fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> }; children.push(Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(im))))); } + if bytes.starts_with(b"checker") { + let raw: Vec = (0..4).flat_map(|i| if i == 0 || i == 3 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }).collect(); + let checker = + craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).ok()?; + let png = craft_image_codecs::encode(&checker, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + d.images.insert("checker-image".into(), ImageBlob::new("image/png", png.to_vec())); + let im = vectorcraft_doc::ImageObject { + key: "checker-image".into(), + width: 2, + height: 2, + xf: Affine::scale_non_uniform(20.0, 10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + children.push(Arc::new(Node::new(NodeId(5), NodeKind::Image(Box::new(im))))); + } if bytes.starts_with(b"loop") { d.images.insert(p.key.clone(), ImageBlob::new("application/json", bytes.to_vec())); let me = PlacedDocument { xf: Affine::translate((10.0, 5.0)) * Affine::scale(0.5), ..p.clone() }; @@ -676,6 +694,28 @@ fn bitmaps_with_and_without_undecoded_marks_are_asked_for_apart() { assert_eq!(placed_document::scheduled("marks-1"), 2, "one for each"); } +/// A placed file's bitmap draws its images as the frame does (File Handling › Display Bitmaps as +/// Anti-aliased Images, #10712): smoothed, a scaled-up 2×2 checker shows greys between its +/// squares; not smoothed, every pixel is one of its own colors. Frames with and without smoothing +/// ask for bitmaps of their own. +#[test] +fn a_bitmap_smooths_its_images_when_the_frame_does() { + let _serial = serial(); + let d = doc_with("checker-1", b"checker"); + let greys = |smooth_images: bool| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, smooth_images, ..Default::default() }; + Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + settle(); + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + // The placed box spans x 10 to 90; the checker's squares meet at x = 50. + (12..88).filter(|x| (16..240).contains(&r.pixel(*x, 20)[0])).count() + }; + assert_eq!(greys(false), 0, "not smoothed: black, then white"); + assert!(greys(true) >= 4, "smoothed: a ramp from black to white"); + assert_eq!(greys(false), 0, "not smoothed again: the smoothed bitmap is not shown"); + assert_eq!(placed_document::scheduled("checker-1"), 2, "one for each"); +} + /// Once bitmaps are ready, drawing again where [`placed_area`] says gives what drawing the whole /// frame again gives. The area of a file covers every object showing it (a group's member and /// an object with a drop shadow too) and no object showing another file; art of a brush or a diff --git a/crates/render/src/tests/words.rs b/crates/render/src/tests/words.rs new file mode 100644 index 0000000000..27b30d9961 --- /dev/null +++ b/crates/render/src/tests/words.rs @@ -0,0 +1,97 @@ +//! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns, +//! rendered straight into the words. + +use std::cell::Cell; + +use vectorcraft_color::{BlendMode as Blend, Color, Paint}; +use vectorcraft_doc::{Appearance, ColorMode, Node}; +use vectorcraft_geom::shapes; + +use crate::group::FINISHED; +use crate::*; + +fn rect(d: &mut Document, r: Rect, c: Color) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0)) +} + +/// A 100 × 100 pt page in `mode` with a page-sized rectangle under the nodes `top` makes. +fn page(mode: ColorMode, top: impl FnOnce(&mut Document) -> Vec) -> Document { + let mut d = Document::new_with_mode(100.0, 100.0, mode); + let below = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.8, 0.6, 0.2)); + let top = top(&mut d); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, below).unwrap(); + for n in top { + d.insert(Some(l), usize::MAX, n).unwrap(); + } + d +} + +fn square(d: &mut Document) -> Node { + rect(d, Rect::new(10.0, 20.0, 60.0, 45.0), Color::rgb(0.1, 0.4, 0.9)) +} + +/// A half-opaque group that blends with the page under it: drawn offscreen over a copy of it. +fn blending_group(d: &mut Document) -> Node { + let mut child = rect(d, Rect::new(20.0, 20.0, 80.0, 80.0), Color::rgb(0.5, 0.5, 1.0)); + child.blend = Blend::Multiply; + let mut g = Node::group(d.alloc_id(), vec![Arc::new(child)]); + g.opacity = 0.5; + g +} + +fn finished() -> usize { + FINISHED.with(Cell::get) +} + +#[test] +fn a_frame_in_words_holds_the_bytes_of_the_same_frame_in_bytes() { + let rgb = |top: fn(&mut Document) -> Node| page(ColorMode::Rgb, |d| vec![top(d)]); + let cases = [ + ("a square", rgb(square), RenderOptions::default()), + ("over no background", rgb(square), RenderOptions { background: None, artboards: false, ..Default::default() }), + ("a blending group", rgb(blending_group), RenderOptions::default()), + ("CMYK blending", page(ColorMode::Cmyk, |d| vec![blending_group(d)]), RenderOptions::default()), + ("supersampled", rgb(square), RenderOptions { supersample: true, ..Default::default() }), + ("outline", rgb(square), RenderOptions { outline: true, ..Default::default() }), + ]; + for (what, d, opts) in cases { + for (w, h, view) in [(100, 100, Affine::IDENTITY), (37, 61, Affine::scale(1.7) * Affine::translate((-5.0, -3.0)))] { + let bytes = Renderer::new().render(&d, w, h, view, &opts); + let words = Renderer::new().render_words(&d, w, h, view, &opts); + assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the frame's size"); + assert_eq!(words.pixels.len() * 4, bytes.pixels.len(), "{what}: a word a pixel"); + assert!(bytemuck::cast_slice::(&words.pixels) == bytes.pixels.as_slice(), "{what} ({w} × {h}): the same bytes"); + } + } +} + +#[test] +fn a_frame_in_words_is_returned_in_the_buffer_it_rendered_into() { + let d = page(ColorMode::Rgb, |d| vec![square(d)]); + let mut r = Renderer::new(); + for background in [None, Some([255, 255, 255, 255])] { + let opts = RenderOptions { background, ..Default::default() }; + let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &opts); + assert_eq!(out.pixels.len(), 64 * 48); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "background {background:?}: the words it rendered into are returned"); + } + let patch = r.render_plain_patch_words(&d, 64, 48, Affine::IDENTITY, &RenderOptions::default()).expect("a plain page renders as a patch"); + assert_eq!(patch.pixels.as_ptr() as usize, finished(), "a patch's words are returned without a copy"); +} + +#[test] +fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() { + let d = page(ColorMode::Rgb, |d| vec![square(d), blending_group(d)]); + let region = Rect::new(5.0, 15.0, 70.0, 90.0); + for white in [false, true] { + let bytes = Renderer::new().render_region(&d, region, 1.3, white); + let mut r = Renderer::new(); + let words = r.render_region_words(&d, region, 1.3, white); + assert_eq!((words.width, words.height), (bytes.width, bytes.height), "white {white}: the region's size"); + assert!(bytemuck::cast_slice::(&words.pixels) == bytes.pixels.as_slice(), "white {white}: the same bytes"); + } + let plain = page(ColorMode::Rgb, |d| vec![square(d)]); + let words = Renderer::new().render_region_words(&plain, region, 1.3, false); + assert_eq!(words.pixels.as_ptr() as usize, finished(), "a region's words are returned without a copy"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5c6dd3510b..cf6cc7a774 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -863,6 +863,8 @@ impl VectorcraftApp { toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32))); } menus::native::sync(self, &ctx); + // A palette event whose start failed tries again after this pass's input. + crate::script_palettes::clear_failed_start(self, &ctx); // A palette event that waited for an undo group this pass ended starts its run next frame. if crate::script_palettes::can_start(self) { ctx.request_repaint(); diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 2fff6194da..dbfa6a578d 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -19,7 +19,7 @@ use serde_json::json; use vectorcraft_geom::{Affine, Point}; use super::BodyKind; -use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, snapped_rect}; +use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, smooth_images, snapped_rect}; use crate::doc_windows::Win; use crate::state::View; use crate::{CacheKey, VectorcraftApp}; @@ -128,10 +128,10 @@ fn render_pane( display: Option<&craft::color_ui::display::DisplayTransform>, cms: Arc, over: Option<(&crate::display_profile::Backdrop, f64)>, -) -> vectorcraft_render::Rendered { - let mut img = vectorcraft_color::cms::with_active(cms, || r.render(doc, w, h, view, opts)); +) -> vectorcraft_render::Rendered> { + let mut img = vectorcraft_color::cms::with_active(cms, || r.render_words(doc, w, h, view, opts)); let width = img.width; - crate::display_profile::convert_over(display, &mut img.pixels, width, view, over); + crate::display_profile::convert_over(display, bytemuck::cast_slice_mut(&mut img.pixels), width, view, over); img } @@ -152,7 +152,7 @@ impl PaneSource { let ppp = frame_ppp(space.size(), ppp, max_side); let side = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)); let (pw, ph) = (side(space.width()), side(space.height())); - let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; + let smooth_images = smooth_images(&app.session.prefs, pixel.is_some()); let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st); let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st); let mut cache = cache_key(app, ctx, st, env.tokens.tokens(), cv, (pw, ph, ppp), (pixel, smooth_images, plugins, placed)); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 480497d7b9..4d0c7a65db 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -32,13 +32,13 @@ pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImag } } -/// Convert an owned [`vectorcraft_render::Rendered`] raster directly into an [`egui::ColorImage`]. -/// Reuses the raster's heap allocation in place via zero-copy buffer casting when size and -/// alignment permit, eliminating redundant multi-megabyte allocations on texture upload. -pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::ColorImage { +/// The raster `img` rendered in words ([`vectorcraft_render::Renderer::render_words`]) as an egui +/// image, in the buffer `img` holds: a word and a [`egui::Color32`] are both four bytes aligned to +/// four, so the pixels are not copied. A raster whose pixels don't match its size gives an empty +/// image of that size. +pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered>) -> egui::ColorImage { let size = [img.width as usize, img.height as usize]; - let expected = size[0].saturating_mul(size[1]).saturating_mul(4); - if expected == img.pixels.len() { + if size[0].saturating_mul(size[1]) == img.pixels.len() { let pixels: Vec = bytemuck::allocation::try_cast_vec(img.pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec()); egui::ColorImage::new(size, pixels) } else { @@ -155,7 +155,7 @@ pub(crate) struct KeptFrame { /// A frame the render worker finished. pub(crate) struct WorkerFrame { - pub(crate) img: vectorcraft_render::Rendered, + pub(crate) img: vectorcraft_render::Rendered>, /// [`vectorcraft_render::FrameStats::moved`] of the renders that made the frame. pub(crate) moved: usize, /// The frame holds pixels copied from the last frame. @@ -214,10 +214,12 @@ fn exposed_parts(w: u32, h: u32, (dx, dy): (i64, i64)) -> Option> } /// `pixels` of a `w`×`h` frame with the art moved by `(dx, dy)` device pixels. The pixels the art -/// does not reach stay transparent. -fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec { +/// does not reach stay transparent. The result holds a pixel a word, as +/// [`vectorcraft_render::Renderer::render_words`] returns a frame. +fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec { let (w, h) = (i64::from(w), i64::from(h)); - let mut out = vec![0; pixels.len()]; + let mut words = vec![0u32; pixels.len() / 4]; + let out: &mut [u8] = bytemuck::cast_slice_mut(&mut words); let (x0, x1) = (dx.max(0), (w + dx).min(w)); if x1 > x0 { for y in dy.max(0)..(h + dy).min(h) { @@ -225,7 +227,7 @@ fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec out[to..to + n].copy_from_slice(&pixels[from..from + n]); } } - out + words } /// The frame of `job` from `pixels`, the last frame's moved by the pan, and the exposed `parts` @@ -233,12 +235,13 @@ fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec /// art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]). fn composed_frame( r: &mut vectorcraft_render::Renderer, - mut pixels: Vec, + mut words: Vec, parts: Vec<[u32; 4]>, job: &crate::render_worker::Job, -) -> Option<(vectorcraft_render::Rendered, usize)> { +) -> Option<(vectorcraft_render::Rendered>, usize)> { let mut moved = 0; let stride = job.w as usize * 4; + let pixels: &mut [u8] = bytemuck::cast_slice_mut(&mut words); for [x0, y0, x1, y1] in parts { let view = Affine::translate((-f64::from(x0), -f64::from(y0))) * job.view; let part = r.render(&job.doc, x1 - x0, y1 - y0, view, &job.opts); @@ -252,7 +255,7 @@ fn composed_frame( pixels[to..to + row].copy_from_slice(line); } } - Some((vectorcraft_render::Rendered { width: job.w, height: job.h, pixels }, moved)) + Some((vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: words }, moved)) } /// Render the frame of `job`. A pan by whole device pixels copies the pixels that stay on screen @@ -276,25 +279,32 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option }); let reused = copied.is_some(); let (mut img, moved) = copied.unwrap_or_else(|| { - let img = r.render(&job.doc, job.w, job.h, job.view, &job.opts); + let img = r.render_words(&job.doc, job.w, job.h, job.view, &job.opts); let moved = r.stats.moved; (img, moved) }); // A copied frame's parts draw nothing that depends on the frame's size ([`composed_frame`]). let view_sized = !reused && r.stats.view_sized > 0; - let keeps = - job.may_keep && moved == 0 && r.stats.view_sized == 0 && img.pixels.len() <= MAX_KEPT_BYTES && (img.width, img.height) == (job.w, job.h); - *kept = - keeps.then(|| KeptFrame { key: job.key.clone(), opts: job.opts.clone(), view: job.view, pixels: holds_pixels.then(|| img.pixels.clone()) }); + let keeps = job.may_keep + && moved == 0 + && r.stats.view_sized == 0 + && img.pixels.len().saturating_mul(4) <= MAX_KEPT_BYTES + && (img.width, img.height) == (job.w, job.h); + *kept = keeps.then(|| KeptFrame { + key: job.key.clone(), + opts: job.opts.clone(), + view: job.view, + pixels: holds_pixels.then(|| bytemuck::cast_slice(&img.pixels).to_vec()), + }); // The kept frame stays sRGB, so the next frame's copied pixels are converted only once. let width = img.width; - crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over()); + crate::display_profile::convert_over(job.display.as_deref(), bytemuck::cast_slice_mut(&mut img.pixels), width, job.view, job.key.over()); WorkerFrame { img, moved, reused, view_sized } } -/// Upload the art's raster directly into the canvas texture without reallocating or copying pixels; -/// Pixel Preview's document pixels keep hard edges when magnified. -pub(super) fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: vectorcraft_render::Rendered, pixel: bool) { +/// Upload the art's raster into the canvas texture in the buffer it was rendered into, without +/// copying its pixels; Pixel Preview's document pixels keep hard edges when magnified. +pub(super) fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: vectorcraft_render::Rendered>, pixel: bool) { let color = color_image_owned(img); let options = if pixel { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; match &mut app.canvas.texture { @@ -325,6 +335,15 @@ pub(super) fn snapped_rect(min: egui::Pos2, size: egui::Vec2, device_ppp: f32) - egui::Rect::from_min_size(pos2(snap(min.x), snap(min.y)), size) } +/// Whether a view smooths the bitmaps it draws larger than their pixels. While Pixel Preview draws +/// its own pixel raster, it follows File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview. +/// This requires a document pixel larger than a screen pixel and a region within the display's texture limit. +/// Otherwise it follows File Handling › Display Bitmaps as Anti-aliased Images. Off, each image pixel shows as +/// a hard-edged square, in pattern tiles and placed documents too. An image marked pixelated is never smoothed (the renderer checks it). +pub(super) fn smooth_images(prefs: &vectorcraft_engine::Prefs, pixel_preview: bool) -> bool { + if pixel_preview { prefs.anti_aliased_bitmaps } else { prefs.smooth_bitmaps } +} + /// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view /// included. None when the view is degenerate, or when a side of the region is more than /// `max_side` pixels, the largest texture side the display supports. @@ -365,9 +384,7 @@ pub(super) fn picture(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace // View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel // is bigger than a screen pixel (below that the screen render already shows it). let pixel = (app.ui.view.pixel_preview && view.zoom * device_ppp as f64 > 1.0).then(|| pixel_region(&view, max_side)).flatten(); - // File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: off, images show - // their pixels as they rasterize, hard-edged. - let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; + let smooth_images = smooth_images(&app.session.prefs, pixel.is_some()); let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st); let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st); let key = cache_key(app, ui.ctx(), st, env.tokens.tokens(), &view, (w, h, ppp), (pixel, smooth_images, plugins, placed)); @@ -785,9 +802,9 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer }; let part = effects.view(|| { if plain_patch { - renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts) + renderer.render_plain_patch_words(doc, x1 - x0, y1 - y0, part_view, opts) } else { - Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)) + Some(renderer.render_words(doc, x1 - x0, y1 - y0, part_view, opts)) } }); let Some(mut part) = part else { @@ -800,8 +817,8 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] return false; } let width = part.width; - crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); - let color = color_image(&part); + crate::display_profile::convert_over(display.as_deref(), bytemuck::cast_slice_mut(&mut part.pixels), width, part_view, key.over()); + let color = color_image_owned(part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); app.canvas.moved |= renderer.stats.moved > 0; @@ -912,10 +929,10 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { _ => { let t0 = monotonic_ms(); let renderer = &mut app.canvas.renderer; - let mut img = effects.view(|| renderer.render(doc, w, h, view, &opts)); + let mut img = effects.view(|| renderer.render_words(doc, w, h, view, &opts)); effects.first_view_done(); let width = img.width; - crate::display_profile::convert_over(display.as_deref(), &mut img.pixels, width, view, key.over()); + crate::display_profile::convert_over(display.as_deref(), bytemuck::cast_slice_mut(&mut img.pixels), width, view, key.over()); upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 1388bf9ef2..af2755f7ea 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1752,7 +1752,8 @@ fn translucent_art_over_the_paper() { }; let worker = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img; let near = |a: &[u8], b: egui::Color32| a.iter().zip(b.to_array()).all(|(x, y)| x.abs_diff(y) <= 1); - assert!(worker.pixels.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches"); + let worker: &[u8] = bytemuck::cast_slice(&worker.pixels); + assert!(worker.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches"); // An edit renders its part again, blended too. app.run("paint.setFill", json!({"ids": [half], "color": "#0000ff"})).unwrap(); let (pos, part_w, part) = upload(&mut app).expect("the edit shows"); @@ -1760,7 +1761,7 @@ fn translucent_art_over_the_paper() { let key = app.canvas.key.clone().unwrap(); let doc = app.session.active().unwrap().doc.clone(); let whole = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img; - let whole = whole.pixels.as_chunks::<4>().0; + let whole = bytemuck::cast_slice::(&whole.pixels).as_chunks::<4>().0; for (i, c) in part.iter().enumerate() { let at = (y0 + i / part_w) * view_w as usize + x0 + i % part_w; assert!(near(&whole[at], *c), "the part matches the whole frame at {at}: {c:?}, {:?}", whole[at]); @@ -2548,7 +2549,7 @@ fn cached_frames_keep_their_scale() { ); } // Deliver the actual replacement and verify that it replaces the cached key. - let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); + let img = app.canvas.renderer.render_words(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); completed .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false, view_sized: false }) @@ -2690,7 +2691,7 @@ fn a_pan_fills_the_area() { assert!(!fill_job.may_copy && !fill_job.may_keep, "the fill worker copies nothing and holds no frame"); assert!(app.canvas.fill.is_none(), "nothing to draw until the fill arrives"); // The fill arrives; the next frame draws it, and asks for no other fill. - let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts); + let img = app.canvas.renderer.render_words(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts); let (doc, opts) = (fill_job.doc, fill_job.opts); fill_completed .send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) @@ -2738,12 +2739,12 @@ fn a_pan_fills_the_area() { assert_eq!(Some(&next.key), app.canvas.worker.as_ref().unwrap().pending.as_ref()); app.view_mut().unwrap().center = Point::new(250.0, 150.0); // That fill finishes after the worker's frame: it is taken and not kept. - let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts); + let img = app.canvas.renderer.render_words(&next.doc, next.w, next.h, next.view, &next.opts); fill_completed .send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) .unwrap(); // The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept. - let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); + let img = app.canvas.renderer.render_words(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); completed .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false, view_sized: false }) @@ -3174,6 +3175,77 @@ fn pixel_preview_smooths_bitmaps_only_when_asked() { assert!(smooth(&mut app), "Pixel Preview, on"); } +/// File Handling › Display Bitmaps as Anti-aliased Images (#10712): on by default, the canvas +/// smooths images out of Pixel Preview as it always has; off, it draws them with each pixel taking +/// its nearest image pixel. Pixel Preview keeps following its own preference. +#[test] +fn every_view_smooths_bitmaps_unless_turned_off() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; // render on this thread + let ctx = crate::testing::ui_context(); + let smooth = |app: &mut VectorcraftApp| { + let (_, mut delta) = frame_output(app, &ctx); + delta.clear(); + app.canvas.key.as_ref().map(|k| k.smooth_images).unwrap() + }; + assert!(smooth(&mut app), "on by default"); + app.run("prefs.set", json!({"key": "smoothBitmaps", "value": false})).unwrap(); + assert!(!smooth(&mut app), "off: nearest sampling in Preview"); + app.run("prefs.set", json!({"key": "antiAliasedBitmaps", "value": true})).unwrap(); + app.ui.view.pixel_preview = true; + app.view_mut().unwrap().zoom = 8.0; + assert!(smooth(&mut app), "Pixel Preview follows its own preference"); + app.ui.view.pixel_preview = false; + app.run("prefs.set", json!({"key": "smoothBitmaps", "value": true})).unwrap(); + assert!(smooth(&mut app), "on again"); +} + +/// File Handling › Display Bitmaps as Anti-aliased Images (#10712), in the canvas's pixels: a 2×2 +/// black and white checker zoomed far in shows only black and white with the setting off, and a +/// ramp of greys between its squares with it on. +#[test] +fn a_zoomed_in_bitmap_shows_hard_pixels_with_smoothing_off() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba(if (x + y) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let data = vectorcraft_format::base64_encode(&png); + app.run("file.place", json!({"name": "checker.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.canvas.worker_started = true; // render on this thread + let ctx = crate::testing::ui_context(); + // How many pixels of the canvas's middle row, across the checker's top row, are neither its + // black nor its white. + let greys = |app: &mut VectorcraftApp| { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref().unwrap().id(); + let (w, h, px) = delta + .set + .iter() + .find(|e| e.0.eq(&art)) + .and_then(|e| e.1.last()) + .map(|d| { + let egui::ImageData::Color(img) = &d.image; + (img.width(), img.height(), img.pixels.clone()) + }) + .expect("the art rendered"); + delta.clear(); + // The checker is centered in the view, 2 pt square at a zoom of 32: 64 pixels a side. + let (cx, y) = (w / 2, h / 2 - 16); + (cx - 28..cx + 28).filter(|x| (16..240).contains(&px[y * w + x].r())).count() + }; + frame_output(&mut app, &ctx).1.clear(); // the first frame fits the view to the artboard + let view = app.view_mut().unwrap(); + (view.zoom, view.center) = (32.0, Point::new(200.0, 150.0)); + assert!(greys(&mut app) >= 8, "on by default: a ramp from black to white"); + app.run("prefs.set", json!({"key": "smoothBitmaps", "value": false})).unwrap(); + assert_eq!(greys(&mut app), 0, "off: each pixel is black or white"); +} + /// Appearance of Black › On Screen (#394): Display All Blacks Accurately (the default) shows /// pure CMYK black through the CMYK profile, a dark grey; Display All Blacks as Rich Black /// shows it as RGB black. A rich black shows the same either way. @@ -5961,7 +6033,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra // It is newer than displayed revision 2: it MUST be accepted and uploaded. let mut rev5_key = initial_key.clone(); rev5_key.revision = 5; - let img5 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }; + let img5 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::from_ne_bytes([200; 4]); 100] }; done_tx .send(crate::render_worker::Done { key: rev5_key, @@ -5985,7 +6057,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra // Worker completes an older revision 3 (out of order). It is older than displayed 5, so discarded. let mut rev3_key = initial_key.clone(); rev3_key.revision = 3; - let img3 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![150; 400] }; + let img3 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::from_ne_bytes([150; 4]); 100] }; done_tx .send(crate::render_worker::Done { key: rev3_key, @@ -6008,7 +6080,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra // Worker completes another intermediate revision 8. Newer than displayed 5, so uploaded. let mut rev8_key = initial_key.clone(); rev8_key.revision = 8; - let img8 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![180; 400] }; + let img8 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::from_ne_bytes([180; 4]); 100] }; done_tx .send(crate::render_worker::Done { key: rev8_key, @@ -6031,7 +6103,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra // Finally, the settling frame at revision 10 completes: it is accepted and uploaded. let mut rev10_key = initial_key; rev10_key.revision = 10; - let img10 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![255; 400] }; + let img10 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::MAX; 100] }; done_tx .send(crate::render_worker::Done { key: rev10_key, @@ -6101,7 +6173,7 @@ fn the_contour_bar_sets_corners_and_bakes() { /// A frame the render worker finished for `job`: white pixels of the job's size. fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { - let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; + let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![u32::MAX; job.w as usize * job.h as usize] }; crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), @@ -6167,9 +6239,9 @@ fn a_whole_pixel_pan() { let frame = render_job(&mut r, &mut kept, &job); assert!(frame.reused, "{pan:?}"); let at = ((64 + pan.1 as i64) * 256 + 128 + pan.0 as i64) as usize * 4; - assert_eq!(frame.img.pixels[at..at + 4], [1, 2, 3, 4], "{pan:?}: the marked pixel moved with the art"); + let mut img = bytemuck::cast_slice::(&frame.img.pixels).to_vec(); + assert_eq!(img[at..at + 4], [1, 2, 3, 4], "{pan:?}: the marked pixel moved with the art"); let whole = vectorcraft_render::Renderer::new().render(&doc, 256, 128, job.view, &job.opts); - let mut img = frame.img.pixels; img[at..at + 4].copy_from_slice(&whole.pixels[at..at + 4]); assert_eq!(img, whole.pixels, "{pan:?}: the same picture as a whole render"); } @@ -6431,11 +6503,12 @@ fn worker_frames_match_a_fresh_render() { let frame = render_job(&mut r, &mut kept, &job); assert_eq!(frame.reused, copies, "{name}"); let whole = vectorcraft_render::Renderer::new().render(&job.doc, job.w, job.h, job.view, &job.opts); + let pixels: &[u8] = bytemuck::cast_slice(&frame.img.pixels); if copies { - let off = frame.img.pixels.iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max(); + let off = pixels.iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max(); assert!(off.is_some_and(|d| d <= 1), "{name}: {off:?}"); } else { - assert_eq!(frame.img.pixels, whole.pixels, "{name}"); + assert!(pixels == whole.pixels.as_slice(), "{name}"); } } } @@ -6494,7 +6567,7 @@ fn a_pan_over_art() { let pan = job(-40.0); let frame = render_job(&mut r, &mut kept, &pan); let whole = vectorcraft_render::Renderer::new().render(&pan.doc, pan.w, pan.h, pan.view, &pan.opts); - let off = frame.img.pixels.iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max(); + let off = bytemuck::cast_slice::(&frame.img.pixels).iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max(); assert!(off.is_some_and(|d| d <= 1), "{name}: a channel differs by {off:?}"); assert!(!frame.reused, "{name}: the pan renders whole"); assert!(kept.is_none(), "{name}: the frame is not kept"); @@ -6965,3 +7038,22 @@ fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() { } assert!(asks() > before, "once the view is still, the tool gives the cursor again"); } + +#[test] +fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_into() { + let (doc, key) = pan_doc(); + let mut r = vectorcraft_render::Renderer::new(); + let job = pan_job(&doc, &key, (0.0, 0.0)); + let frame = render_job(&mut r, &mut None, &job).img; + let at = frame.pixels.as_ptr() as usize; + let color = color_image_owned(frame); + assert_eq!(color.pixels.as_ptr() as usize, at, "the frame's pixels are handed to the image, not copied"); + let bytes = vectorcraft_render::Renderer::new().render(&doc, job.w, job.h, job.view, &job.opts); + assert!(color.pixels == color_image(&bytes).pixels, "the image holds the frame's pixels"); + assert_eq!(color.size, [256, 128]); + // A raster whose pixels don't match its size gives an empty image of that size. + let short = vectorcraft_render::Rendered { width: 3, height: 2, pixels: vec![u32::MAX; 5] }; + let empty = color_image_owned(short); + assert_eq!(empty.pixels.len(), 6, "the empty image has one pixel per position of its size"); + assert!(empty.size == [3, 2] && empty.pixels.iter().all(|c| *c == Color32::TRANSPARENT), "a raster of the wrong length is not shown"); +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 34ef127f95..da1382c27f 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -149,11 +149,40 @@ struct SessionTool<'a> { /// The canvas's context and layer: a window over the canvas (a floating document's) hides it from the pointer. ctx: egui::Context, layer: egui::LayerId, + /// The drag samples of this pass for a tool that takes every position the pointer passed, handed to the session + /// together by [`Self::send_samples`]. + samples: RefCell>, } impl<'a> SessionTool<'a> { fn new(app: &'a mut VectorcraftApp, view: ViewInfo, ui: &Ui) -> Self { - Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } + Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id(), samples: RefCell::new(vec![]) } + } + + /// Keeps `ev`, a drag or the release, for [`Self::send_samples`] when the tool takes every position the pointer + /// passed; otherwise hands the kept samples and then `ev` to the session. + fn send_sample(&self, ev: PointerEvent) { + if self.app().session.tool_wants_samples() { + self.samples.borrow_mut().push(ev); + } else { + self.send_samples(); + dispatch(&mut self.app(), &ev, self.view); + } + } + + /// Hands the drag samples kept in this pass to the session ([`vectorcraft_engine::Session::pointer_samples`]), + /// which applies only the last of the tool's previews, and acts on what they ask of the UI. Each call on the tool + /// other than a drag runs it first, so every other event reaches the tool after the samples before it. + fn send_samples(&self) { + let samples = std::mem::take(&mut *self.samples.borrow_mut()); + let mut rest = samples.as_slice(); + while !rest.is_empty() { + let mut app = self.app(); + let (fed, r) = app.session.pointer_samples(rest, self.view); + sync_artboard(&mut app); + apply_requests(&mut app, r); + rest = rest.get(fed.max(1)..).unwrap_or_default(); + } } /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones @@ -284,6 +313,7 @@ fn engine_key(chord: Chord) -> Option<(EngineKey, bool)> { impl CanvasTool for SessionTool<'_> { fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { + self.send_samples(); let mut app = self.app(); if app.ui.screen_mode == 3 { // Presentation Mode: the tool gets nothing; the release of a click steps to the next artboard. @@ -342,7 +372,7 @@ impl CanvasTool for SessionTool<'_> { if !carried { // The moves of the pass that releases the press came before its release, with the keys held then. let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx)); - dispatch(&mut self.app(), &ev, self.view); + self.send_sample(ev); self.app().canvas.last_drag = Some((pointer.pos, ev)); } self.carrying.set(carried); @@ -367,6 +397,7 @@ impl CanvasTool for SessionTool<'_> { let given_up = cx.over_drop_target() || carried.is_some(); if given_up { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. + self.send_samples(); let _ = self.app().session.cancel_interaction(); } if let Some(art) = carried.filter(|_| !cx.over_drop_target()) { @@ -381,9 +412,11 @@ impl CanvasTool for SessionTool<'_> { // that pass still draws a square. A move that was given up gets none. let last = self.app().canvas.last_drag.map(|(_, ev)| ev); if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) { - dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view); + self.send_sample(PointerEvent { kind: PointerKind::Drag, ..up }); } - dispatch(&mut self.app(), &up, self.view); + // The release goes to the session after the samples of its pass, which preview the stroke once before it. + self.send_sample(up); + self.send_samples(); if self.app().canvas.last_drag.is_some() { // A press that dragged is no click, and the framework counts presses: the next press starts a new run. self.app().ui.trace_pick_clicks = pointer.clicks; @@ -412,10 +445,12 @@ impl CanvasTool for SessionTool<'_> { } fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + self.send_samples(); self.send(PointerKind::Move, pointer, cx); } fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) { + self.send_samples(); let mut app = self.app(); if app.ui.screen_mode == 3 { // The tool had no press of Presentation Mode's. @@ -435,6 +470,7 @@ impl CanvasTool for SessionTool<'_> { } fn claims(&self) -> ToolClaims { + self.send_samples(); let mut app = self.app(); let view = self.view; let claim = |app: &mut VectorcraftApp, key: EngineKey| app.session.tool_claims_key(key, view); @@ -477,6 +513,7 @@ impl CanvasTool for SessionTool<'_> { } fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool { + self.send_samples(); let space = cx.held(Key::Space); let held = tool_mods(cx.mods, space); match key { @@ -564,6 +601,7 @@ impl CanvasTool for SessionTool<'_> { /// While the view moves under the pointer, the cursor the tool last gave for the same tool and keys stays: asking /// the tool again would hit-test the art under the pointer in every frame of a pan or zoom (#2452). fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + self.send_samples(); let Some(space) = cx.space() else { return tool_cursor(vectorcraft_tools::Cursor::Arrow) }; let at = cx.pointer.map_or(Point::ZERO, |p| space.view.to_doc(p.pos)); let mods = tool_mods(cx.mods, cx.held(Key::Space)); @@ -730,6 +768,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too app.canvas.zoom_tool = None; let mut tool = SessionTool::new(app, view_info, ui); let response = host_run_session(&mut tool, ui, pass); + tool.send_samples(); drop(tool); response }; diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index a9c60d1089..1316913433 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -215,3 +215,138 @@ fn the_caps_lock_command_before_the_first_frame_stays_in_place() { frame(&mut app, &ctx, vec![]); assert!(app.session.caps_lock); } + +/// The moves of one pass reach the Pencil together: the pass previews the stroke once, and the path the release draws +/// runs from the press to the last move. +#[test] +fn a_pencil_pass_of_four_moves_previews_once() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("pencil"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let view = app.canvas_view().unwrap(); + let on_wave = |x: f64| Point::new(x, 150.0 + 20.0 * (x / 15.0).sin()); + let at = |x: f64| view.to_screen(on_wave(x)); + let button = + |x: f64, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let moves = |from: f64, n: u32| (1..=n).map(|i| egui::Event::PointerMoved(at(from + 6.0 * f64::from(i)))).collect::>(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(100.0)), button(100.0, true)]); + frame(&mut app, &ctx, moves(100.0, 4)); + // Each preview the pass runs moves the revision by the same amount. + let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision; + let before = revision(&app); + frame(&mut app, &ctx, moves(124.0, 1)); + let one = revision(&app) - before; + assert!(one > 0, "a pass of one move previews the stroke"); + let before = revision(&app); + frame(&mut app, &ctx, moves(130.0, 4)); + assert_eq!(revision(&app) - before, one, "a pass of 4 moves previews the stroke once, as a pass of one move does"); + frame(&mut app, &ctx, vec![button(154.0, false)]); + let mut ends = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(pd) = n.path_data() { + ends.extend(pd.subpaths.iter().filter_map(|sp| Some((sp.anchors.first()?.p, sp.anchors.last()?.p)))); + } + }); + let near = |a: Point, x: f64| a.distance(on_wave(x)) < 0.5; + assert!(matches!(ends.as_slice(), [(first, last)] if near(*first, 100.0) && near(*last, 154.0)), "{ends:?}"); +} + +/// The release reaches the Pencil after the moves of its pass: a pass of 4 moves and the release previews the moves +/// once, as a pass of one move and the release does, and the path runs from the press to the release. +#[test] +fn a_pencil_release_with_moves_previews_once() { + // The revision's change in the pass that releases after `last` moves, and the ends of the paths drawn. + let stroke = |last: u32| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("pencil"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let view = app.canvas_view().unwrap(); + let on_wave = |x: f64| Point::new(x, 150.0 + 20.0 * (x / 15.0).sin()); + let at = |x: f64| view.to_screen(on_wave(x)); + let button = + |x: f64, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let moves = |from: f64, n: u32| (1..=n).map(|i| egui::Event::PointerMoved(at(from + 6.0 * f64::from(i)))).collect::>(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(100.0)), button(100.0, true)]); + frame(&mut app, &ctx, moves(100.0, 4)); + let before = app.session.active().unwrap().revision; + let end = 124.0 + 6.0 * f64::from(last); + let mut pass = moves(124.0, last); + pass.push(button(end, false)); + frame(&mut app, &ctx, pass); + let changed = app.session.active().unwrap().revision - before; + let mut ends = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(pd) = n.path_data() { + ends.extend(pd.subpaths.iter().filter_map(|sp| Some((sp.anchors.first()?.p, sp.anchors.last()?.p)))); + } + }); + let near = |a: Point, x: f64| a.distance(on_wave(x)) < 0.5; + assert!(matches!(ends.as_slice(), [(first, last)] if near(*first, 100.0) && near(*last, end)), "{ends:?}"); + changed + }; + let one = stroke(1); + assert!(one > stroke(0), "a move in the release's pass previews the stroke"); + assert_eq!(stroke(4), one, "a pass of 4 moves and the release previews the moves once, as a pass of one move does"); +} + +/// The Pencil draws the same path when the moves come in passes of 4, the last one with the release, as when each move +/// comes in a pass of its own: the moves inside a pass bend the path. +#[test] +fn a_pencil_stroke_in_passes_of_four_keeps_every_bend() { + let stroke = |grouped: bool| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("pencil"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let view = app.canvas_view().unwrap(); + let start = view.to_screen(Point::new(80.0, 150.0)); + let end = view.to_screen(Point::new(320.0, 150.0)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // Every fourth move lies on the chord: a path made from the last move of each pass alone has no bend. + let moves: Vec<_> = (1..=12) + .zip([90.0, 210.0, 90.0, 150.0, 90.0, 210.0, 90.0, 150.0, 90.0, 210.0, 90.0, 150.0]) + .map(|(i, y)| egui::Event::PointerMoved(view.to_screen(Point::new(80.0 + 20.0 * f64::from(i), y)))) + .collect(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + let pass_size = if grouped { 4 } else { 1 }; + for (i, chunk) in moves.chunks(pass_size).enumerate() { + let mut events = chunk.to_vec(); + if grouped && (i + 1) * pass_size == moves.len() { + events.push(button(end, false)); + } + frame(&mut app, &ctx, events); + } + if !grouped { + frame(&mut app, &ctx, vec![button(end, false)]); + } + let mut paths = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(pd) = n.path_data() { + paths.push(pd.clone()); + } + }); + paths + }; + let separate = stroke(false); + let grouped = stroke(true); + assert_eq!(grouped, separate, "grouping moves with the release preserves every path's data"); + assert_eq!(separate.len(), 1, "the stroke creates one path"); + assert_eq!(separate[0].subpaths.len(), 1, "the stroke creates one subpath"); + let anchors = &separate[0].subpaths[0].anchors; + let first = anchors.first().unwrap().p; + let last = anchors.last().unwrap().p; + let chord = first.distance(last); + assert!(chord > 1.0, "the stroke has distinct endpoints"); + assert!( + anchors.iter().any(|a| { + let cross = (last.x - first.x) * (a.p.y - first.y) - (last.y - first.y) * (a.p.x - first.x); + cross.abs() / chord > 1.0 + }), + "the finished path has a bend more than 1 pt from its chord" + ); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index d9d2fba515..44684cac2a 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -31,6 +31,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; +use vectorcraft_engine::script::DialogAnswer; use super::preview::LivePreview; use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values}; @@ -49,6 +50,9 @@ pub(crate) enum Target { Artboard { document: u64, reverts: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, + /// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`: + /// the run's active document is in CMYK. + Script { color: Color, cmyk: bool }, } impl Target { @@ -60,7 +64,8 @@ impl Target { let (document, reverts) = match self { Self::Fill { document, reverts } | Self::Stroke { document, reverts } => (*document, *reverts), Self::Artboard { document, reverts, .. } => (Some(*document), *reverts), - Self::Answer { .. } => return None, + // A script's picker answers the run whichever document is active. + Self::Answer { .. } | Self::Script { .. } => return None, }; match (app.session.active(), document) { (None, None) => None, @@ -261,28 +266,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let start = srgba(&color); - let mut dialog = ColorPickerDialog::new( - match (artboard, stroke) { - (Some(_), _) => "artboard", - (None, true) => "stroke", - (None, false) => "fill", - }, - tl!("Color Picker"), - start, - ) - .eyedropper(true) - .add_to_swatches(false) - .gamut(gamut(app)) - .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { - dialog = dialog.cmyk(&converter); - } - if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { - dialog = dialog.kept(model_values(&color)); - } + let key = match (artboard, stroke) { + (Some(_), _) => "artboard", + (None, true) => "stroke", + (None, false) => "fill", + }; + let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk); + let mut dialog = picker(app, key, &color, cmyk); // The host replaces a picker only for the same document and artboard. if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); @@ -313,6 +303,69 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's +/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog { + let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); + if cmyk && let Some(converter) = working_cmyk() { + dialog = dialog.cmyk(&converter); + } + if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { + dialog = dialog.kept(model_values(color)); + } + dialog +} + +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`: +/// the run's own active document is in CMYK, which the session does not show between slices. It +/// previews nothing; its OK and Cancel answer the run ([`finish`]). +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) { + let Some(dialogs) = app.dialogs() else { return }; + // The given colour's own values, so that OK can tell an untouched pick from another model's. + // The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given. + let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false); + let id = dialogs.with(|h| h.open(dialog)); + app.color_dialogs.pickers.retain(|o| o.id != id); + let target = Target::Script { color, cmyk }; + app.color_dialogs.pickers.push(Open { + id, + target, + start: srgba(&color), + keep: false, + preview: LivePreview::default(), + view: Vec::new(), + row: None, + }); +} + +/// The key of the Color Picker a script opens. +pub(crate) const SCRIPT_KEY: &str = "script"; + +/// The id of the Color Picker a running script waits at, while it is open or its answer is not +/// yet given. +pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id) +} + +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. A +/// screen pick the picker started ends with it; a pick another owner started keeps running. +pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(id) = script_picker(app) else { return }; + app.color_dialogs.pickers.retain(|o| o.id != id); + screen_color::cancel_for(app, ctx, owner(id)); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| { + h.cancel_by_id(ctx, id); + let _ = h.take_by_id::(id); + }); + } +} + /// The reason `ui.dialog.confirm` with `params` fails, when it would confirm a picker whose Recolor /// Artwork row changed since the picker opened (OK would then answer nothing). The picker stays open. pub(crate) fn check_confirm(app: &VectorcraftApp, host: &craft::ui::dialog::DialogHost, params: &Value) -> Result<(), String> { @@ -394,6 +447,7 @@ fn settle(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &craft::ui::sh }) }); let Some((current, gesture)) = live else { + screen_color::cancel_for(app, ctx, owner(open.id)); let result = dialogs.with(|h| h.take_by_id::(open.id)); finish(app, dialogs, open, result); return false; @@ -448,6 +502,15 @@ fn finish( dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } } + // OK on the colour it opened with, in the model it opened with, gives that colour back. + (Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => { + let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); + let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) }; + app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); + } + (_, Target::Script { .. }) => { + app.session.script_answer(DialogAnswer::ColorPicker(None)); + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); @@ -462,14 +525,19 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })), Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill { .. } | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill { .. } | Target::Answer { .. } | Target::Script { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } } -/// The picked colour as the document takes it: an RGB colour is CMYK in a CMYK document; CMYK, -/// grey and Lab colours stay as they are. +/// The picked colour as the active document takes it ([`in_model`]). fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { - if matches!(c, Color::Rgb { .. }) && app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) { + in_model(app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk), c) +} + +/// The picked colour as a document takes it: an RGB colour is CMYK in a CMYK document (`cmyk`); +/// CMYK, grey and Lab colours stay as they are. +fn in_model(cmyk: bool, c: Color) -> Color { + if cmyk && matches!(c, Color::Rgb { .. }) { let [cy, m, y, k] = c.to_cmyk_managed(cms::active().settings().intent); return Color::cmyk(cy, m, y, k); } @@ -480,8 +548,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// preview. Nothing previews until the colour first changes, nor without a selection (the colour /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { - // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) { + // A picker over a command dialog only fills a row; the dialog previews it. A script's picker + // only answers the script. + if matches!(open.target, Target::Answer { .. } | Target::Script { .. }) || !open.target.in_active_document(app) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs index 10e9ede502..6b7f24ac6f 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs @@ -349,7 +349,7 @@ fn image(f: &CompositeFont, zoom: u64, marks: &[Mark], ppp: f32, ink: Color32) - mark_line(&mut rendered, ((base - y) as f32 * ppp).round(), ppp.ceil().max(1.0) as usize, m.color()); } } - crate::canvas::color_image_owned(rendered) + crate::canvas::color_image(&rendered) } /// Draws a horizontal line `thickness` pixels thick from row `y` across `image`; a row outside it draws nothing. diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 0c2f8503ef..fb23157d9e 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -128,8 +128,8 @@ fn render_page_preview( let region = doc.artboards.first()?.rect; let px = PREVIEW_PX * pixels_per_point as f64; let scale = px / region.width().max(region.height()).max(1.0); - let img = renderer.render_region(doc, region, scale, true); - Some(Arc::new(crate::canvas::color_image(&img))) + let img = renderer.render_region_words(doc, region, scale, true); + Some(Arc::new(crate::canvas::color_image_owned(img))) } /// Everything the dialog asks and shows: the form's value, and what an OK needs to open or place the file. diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 2cbe092f14..69dc0c9b58 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -55,6 +55,7 @@ use std::path::Path; use std::sync::Arc; +use craft::color_ui::ui::ColorPickerDialog; use craft::host::{PickRequest, Picked}; use craft::keymap::Key; use craft::theme::variant::Tone; @@ -78,6 +79,7 @@ use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, Scr use vectorcraft_engine::script::printing::PreparedPrint; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::color_picker; use super::script_window::{self, ScriptWindow}; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -580,6 +582,22 @@ pub(crate) fn forget(app: &VectorcraftApp) { }); } +/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened. +pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if color_picker::script_picker(app).is_none() { + return; + } + let asking = with_host(app, |host, _| host.is_open::()).unwrap_or(false); + color_picker::forget_script(app, &ctx); + if asking { + with_host(app, |host, _| { + let _ = host.take::(); + host.open(close_question()); + }); + } +} + /// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { if p.get("path").is_some() || p.get("source").is_some() { @@ -760,11 +778,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { /// Cancel shows again as it was, with the events a ScriptUI dialog has not given the script yet and /// the text typed in its fields. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let picker = color_picker::script_picker(app); with_host(app, |host, _| { let own = [ host.get::().map(StackDialog::id), host.get::().map(StackDialog::id), host.get::().map(StackDialog::id), + picker.filter(|&id| host.get_by_id::(id).is_some()), ]; match own.into_iter().flatten().find(|id| host.stack().is_top(*id)) { Some(parent) => { @@ -887,6 +907,7 @@ fn answer_close(app: &mut VectorcraftApp, close: Option(app); forget::(app); forget::(app); + forget_color_picker(app); app.sync_views(); } } @@ -1199,6 +1220,8 @@ mod tests { error_icon: false, no_as_default: true, preset: String::new(), + color: None, + cmyk_document: false, }; let ctx = egui::Context::default(); // A script's own confirm with the same text takes Yes. diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 48401c4b57..3c52fae8a3 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -218,6 +218,18 @@ pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap /// as the script in `w` would check it first; when one is refused, every field keeps its text, /// `events` stays as it was and the error is returned. pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap, events: &mut Vec) -> Result<(), String> { + commit_texts_over(w, drafts, events, &[]) +} + +/// [`commit_texts`] for fields whose earlier changes still wait to be delivered: a draft of a field +/// whose id is in `queued` is given even when it matches the field's text, since the script reads the +/// waiting change's text first. +pub(crate) fn commit_texts_over( + w: &ScriptUiDialog, + drafts: &mut BTreeMap, + events: &mut Vec, + queued: &[u64], +) -> Result<(), String> { let mut given = Vec::new(); let mut changes = Vec::new(); for (i, n) in w.nodes.iter().enumerate() { @@ -230,7 +242,7 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap String { /// Draws the visible controls of the ScriptUI window `w` at the places the engine laid them out, /// with the text typed in its edit fields (`drafts`); none can be used unless `usable`. -pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, usable: bool) -> Pass { +pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, usable: bool, queued: &[u64]) -> Pass { let (width, height) = w.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; @@ -432,7 +444,13 @@ pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, + queued_text: bool, } /// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus, @@ -531,7 +550,7 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr shown.event = Some(UiEvent::Click(i)); } } - UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)), + UiKind::EditText => shown = edit(ui, rect, drafts, enabled, place.queued_text, (i, n, prompt)), UiKind::DropDownList => { let entries: Vec>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect); @@ -634,9 +653,15 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { /// accepts, so that a text that is too long can still be typed, refused and shortened. pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; +/// The change an edit field `n` at index `i` gives when its text `text` is committed: none for a +/// read-only field, or for the field's own text unless a change of the field waits (`queued`). +pub(crate) fn text_change(i: usize, n: &UiNode, text: String, queued: bool) -> Option { + (!n.readonly && (text != n.text || queued)).then_some(UiEvent::Change(i, UiValue::Text(text))) +} + /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. -fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { +fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: bool, queued: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) .limit(DRAFT_CHARS) @@ -648,13 +673,15 @@ fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: } let out = field.show_at(ui, rect); let focused = out.response.has_focus(); - let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone())); - let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); - if committed && text != n.text && !n.readonly { - return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) }; + let queued = queued && (drafts.contains_key(&n.id) || out.events.value().is_some()); + let mut draft = (out.events.value().is_some() || text != n.text || queued).then(|| Some(text.clone())); + // The focus is on the field's text part, so the text part's focus loss is the one that counts. + let committed = out.submitted || out.events.committed().is_some() || out.text_lost_focus; + if committed && let Some(event) = text_change(i, n, text.clone(), queued) { + return Shown { event: Some(event), typing: true, container: None, draft: Some(None) }; } // A text the script refused stays in the field until the person changes it. - if !focused && text == n.text { + if !focused && text == n.text && !queued { draft = Some(None); } Shown { event: None, typing: focused || committed, container: None, draft } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 333b56e123..13b7bdf715 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -175,6 +175,43 @@ fn the_document_filter_on_an_empty_document_or_none() { assert!(used(&mut app).is_empty()); } +/// The font list draws each family's sample in its own face, and egui hints text by default, so a TrueType face +/// without hinting instructions goes through the automatic hinter. A Hebrew letter in such a face that is a bar 20 +/// by 700 thousandths of an em lays out. The layout runs on a thread of its own, and the test fails when it has not +/// ended after 300 s. +#[test] +fn a_face_without_hinting_instructions_lays_out_a_tall_hebrew_letter() { + use egui::epaint::text::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, Fonts, TextOptions}; + use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font}; + + let mut glyph = FileGlyph { ch: '\u{5d1}', outline: Default::default(), advance: 300.0 }; + glyph.outline.move_to((0.0, 0.0)); + glyph.outline.line_to((0.0, 700.0)); + glyph.outline.line_to((20.0, 700.0)); + glyph.outline.line_to((20.0, 0.0)); + glyph.outline.close_path(); + let info = FileFontInfo { family: "Unhinted Bar".into(), style: "Regular".into(), ..Default::default() }; + let bytes = build_file_font(&info, &[glyph]).unwrap(); + let family = FontFamily::Name("Unhinted Bar".into()); + let mut definitions = FontDefinitions::empty(); + definitions.font_data.insert("Unhinted Bar".into(), Arc::new(FontData::from_owned(bytes).tweak(FontTweak::default()))); + definitions.families.insert(family.clone(), vec!["Unhinted Bar".into()]); + let options = TextOptions::default(); + assert!(options.font_hinting, "egui hints text by default"); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut fonts = Fonts::new(options, definitions); + let mut view = fonts.with_pixels_per_point(1.0); + let font_id = FontId::new(14.0, family); + let in_face = view.has_glyph(&font_id, '\u{5d1}'); + let galley = view.layout_no_wrap("\u{5d1}".into(), font_id, egui::Color32::BLACK); + tx.send((in_face, galley.size())).ok() + }); + let (in_face, size) = rx.recv_timeout(std::time::Duration::from_secs(300)).unwrap_or_else(|e| panic!("laying out U+05D1: {e}")); + assert!(in_face, "the face maps U+05D1"); + assert!(size.x > 0.0, "the letter is laid out with its advance: {size:?}"); +} + /// A fixed time the Recently Added tests count from. fn clock() -> SystemTime { SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000) diff --git a/crates/ui-egui/src/graphics.rs b/crates/ui-egui/src/graphics.rs index 27cf2c623c..b90827aea0 100644 --- a/crates/ui-egui/src/graphics.rs +++ b/crates/ui-egui/src/graphics.rs @@ -127,13 +127,14 @@ impl VectorcraftApp { /// after losing its graphics), everything uploaded to the old one is made again: the fonts and /// theme, the canvas, the place cursor's thumbnails and every [`TexCache`]. The host hands it /// the window's context when it creates the app, so the first frame's input has the app's - /// commands. + /// commands. Each new context draws its text without hinting ([`crate::ui_fonts::hinting_off`]). pub fn adopt_context(&mut self, ctx: &egui::Context) { let tag = context_tag(ctx); self.ui_ctx = Some(ctx.clone()); if self.context == tag { return; } + crate::ui_fonts::hinting_off(ctx); if self.context != 0 { log::info!("vectorcraft: new graphics context: uploading the UI again"); forget_textures(); @@ -158,16 +159,16 @@ thread_local! { pub(crate) fn doc_image(size_px: [usize; 2], build: impl FnOnce(f64, f64) -> Option) -> Option { let (w, h) = (size_px[0] as f64, size_px[1] as f64); let doc = build(w, h)?; - let img = RENDERER.with(|r| r.borrow_mut().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, w, h), 1.0, false)); - Some(crate::canvas::color_image(&img)) + let img = RENDERER.with(|r| r.borrow_mut().render_region_words(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, w, h), 1.0, false)); + Some(crate::canvas::color_image_owned(img)) } /// `region` of `doc` rendered on white, its longest side `px` pixels (artboard and page /// thumbnails). pub(crate) fn region_image(doc: &vectorcraft_doc::Document, region: vectorcraft_geom::Rect, px: u32) -> egui::ColorImage { let scale = f64::from(px) / region.width().max(region.height()).max(1.0); - let img = RENDERER.with(|r| r.borrow_mut().render_region(doc, region, scale, true)); - crate::canvas::color_image(&img) + let img = RENDERER.with(|r| r.borrow_mut().render_region_words(doc, region, scale, true)); + crate::canvas::color_image_owned(img) } #[cfg(test)] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 84ee5e3ba0..ebdb694870 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1145,7 +1145,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; 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 end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; 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 end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index 6b37957e6f..c8c42fb4c4 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -364,14 +364,15 @@ fn render( overprint_preview: overprints == Overprints::Simulate, ..Default::default() }; - let mut img = r.render(&shot.doc, w, hh, view, &opts); + let mut img = r.render_words(&shot.doc, w, hh, view, &opts); if h != Highlight::None { let mask = shot .report .highlight_art(&shot.doc, h) .map(|art| r.render(&art, w, hh, view, &RenderOptions { skip_templates: true, ..Default::default() })); let red = [color.r(), color.g(), color.b()].map(f32::from); - for (i, p) in img.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let pixels: &mut [u8] = bytemuck::cast_slice_mut(&mut img.pixels); + for (i, p) in pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() { // A light grey of the art, so the highlight stands out. let luma = 0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32; let grey = 96.0 + luma * 0.62; @@ -381,7 +382,7 @@ fn render( } } } - crate::canvas::color_image(&img) + crate::canvas::color_image_owned(img) } const REFRESH: &str = "ui.flattenerPreview.refresh"; diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 9d6088cbd3..ecff1effa3 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -300,10 +300,12 @@ fn selected_mid(app: &VectorcraftApp, stops: usize) -> Option { /// What the panel's number fields edit: the gradient behind the active proxy /// ([`vectorcraft_engine::Session::gradient_owner`], which names the selected part of a symbol instance) on the selected -/// objects. Each field passes it to [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value -/// left unfinished in the field is dropped when another one is selected. +/// objects, with how many times File › Revert and Undo or Redo replaced the document's content (after which the same +/// node id can name another object, or the object another gradient). Each field passes it to +/// [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value left unfinished in the field is +/// dropped when another one is selected or the content is replaced. fn field_target(app: &VectorcraftApp) -> egui::IdSalt { - let objects = app.session.active().map(|st| &st.selection.objects); + let objects = app.session.active().map(|st| (&st.selection.objects, st.reverts, st.history_restores)); egui::IdSalt::new((app.session.gradient_owner(), objects)) } diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 0085caada8..e7f0e2c637 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -424,6 +424,62 @@ fn an_unfinished_aspect_or_repeats_value_does_not_reach_another_object() { assert_eq!(of(&rig, b), (Some(2.0), 2), "the other object takes 2%, not 20+2, and 2 repeats, not 20+2"); } +/// A selected rectangle with a white-to-black gradient at 30°, then a red-to-blue one at 30° set over it. +fn two_gradients() -> VectorcraftApp { + let mut app = app(json!({"gradient": {"angle": 30}})); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"angle": 30, "stops": stops}})).unwrap(); + app +} + +/// File › Revert drops an unfinished Angle value, though the reverted document has the same object, with a gradient at +/// the same angle, selected again before the next frame. +#[test] +fn an_unfinished_angle_value_is_dropped_by_file_revert() { + let mut app = app(json!({"gradient": {"angle": 30}})); + let a = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("gradient-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Gradient.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo: another gradient at the same angle. + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"angle": 30, "stops": stops}})).unwrap(); + let mut rig = Rig::new(app); + rig.type_unfinished("Angle", "20+"); + rig.app().run("file.revert", json!({"confirmed": true})).unwrap(); + rig.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + rig.finish("1"); + assert_eq!(hexes(&rig.app()), ["#ffffff", "#000000"], "the reverted gradient is selected"); + assert_eq!(fill(&rig.app()).angle, 1.0, "Revert drops the unfinished value: 1°, not 20+1"); +} + +/// Undo drops an unfinished Angle value typed for the gradient it takes away, though the gradient it brings back has +/// the same angle on the same selected object. +#[test] +fn an_unfinished_angle_value_is_dropped_by_undo() { + let mut rig = Rig::new(two_gradients()); + rig.type_unfinished("Angle", "20+"); + rig.app().run("edit.undo", json!({})).unwrap(); + rig.finish("1"); + assert_eq!(hexes(&rig.app()), ["#ffffff", "#000000"], "Undo brings back the first gradient"); + assert_eq!(fill(&rig.app()).angle, 1.0, "Undo drops the unfinished value: 1°, not 20+1"); +} + +/// Redo drops an unfinished Angle value typed for the gradient it takes away, though the gradient it brings back has +/// the same angle on the same selected object. +#[test] +fn an_unfinished_angle_value_is_dropped_by_redo() { + let mut app = two_gradients(); + app.run("edit.undo", json!({})).unwrap(); + let mut rig = Rig::new(app); + rig.type_unfinished("Angle", "20+"); + rig.app().run("edit.redo", json!({})).unwrap(); + rig.finish("1"); + assert_eq!(hexes(&rig.app()), ["#ff0000", "#0000ff"], "Redo brings back the second gradient"); + assert_eq!(fill(&rig.app()).angle, 1.0, "Redo drops the unfinished value: 1°, not 20+1"); +} + /// An unfinished value is dropped when another object joins the selection, which keeps the same first object, and when /// another part of the same symbol instance is selected. #[test] diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 7d59220a48..d85933f8cf 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -282,8 +282,8 @@ fn render(paints: Paints, g: &GraphicStyle, look: ThumbLook, px: u32) -> Option< }; let layer = doc.layers[0].id; doc.insert(Some(layer), 0, styled_node(&shape, g, look.override_chars)).ok()?; - let img = RENDERER.with(|r| r.borrow_mut().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, SIDE, SIDE), px as f64 / SIDE, true)); - let mut img = crate::canvas::color_image(&img); + let img = RENDERER.with(|r| r.borrow_mut().render_region_words(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, SIDE, SIDE), px as f64 / SIDE, true)); + let mut img = crate::canvas::color_image_owned(img); if empty { slash(&mut img); } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index c9147ef357..236238ab17 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -100,7 +100,7 @@ impl ThumbSource for SymbolPictures<'_> { render_art(&mut renderer, self.doc, self.name, vectorcraft_geom::Rect::new(x0, y0, x1, y1), (*w, *h)) } }; - img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image_owned(img))) + img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image(&img))) } } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 193ea99ec9..eaacf7880e 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -64,6 +64,9 @@ pub struct PrefsWindow { /// General › Script File Access: the file access kept with Always, read when the window opens; `None` where the /// session keeps none (no settings folder, and the web). script_access: Option, + /// Automation drove the window: a pass that carried injected input showed it. OK then saves no agent setting + /// changed in it until the window closes ([`model::Live`]'s `apply`). + automated: bool, } impl PrefsWindow { @@ -248,6 +251,7 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { reset_asked: None, strings: Default::default(), script_access, + automated: false, }; w.state.selected = selected.to_string(); w.sync_strings(); @@ -257,6 +261,7 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { /// One pass of the window, while it is open. The window leaves `app` for the pass so its model can use the app. pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let Some(mut w) = app.prefs.take() else { return }; + w.automated |= app.automation_is_acting(); // Rows drawn by `PathSetting` edit the draft directly. w.sync_strings(); let mut state = std::mem::take(&mut w.state); diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index dec9066151..39c586ace0 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -347,9 +347,15 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links.", ), ("pdfImportEmbeddedFonts", "Uses a PDF's embedded glyphs for imported text when its font is missing; off, it uses the fallback font."), + ( + "smoothBitmaps", + "Smooths images unless Pixel Preview draws its own pixel raster and uses the setting below. \ + When off, image pixels have hard edges.", + ), ( "antiAliasedBitmaps", - "In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed.", + "Smooths images while Pixel Preview draws its own pixel raster; otherwise the setting above applies. \ + When off, image pixels have hard edges.", ), ( "updateLinks", diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 2cc8b0c387..59b5d9e15f 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -524,6 +524,19 @@ impl PreferencesDraft for Live<'_> { let read = self.w.source.get::>(AGENTS_KEY).unwrap_or_default(); let given: Map = agents.iter().filter(|(k, v)| *k != "allowAgentControl" && read.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect(); + // Agents can't widen the folders they work in. Once automation drove the window, its agent settings are + // put back as they were read for as long as it stays open (a field may still hold injected text), and OK + // applies nothing. An OK automation sends is refused and leaves the draft as it is. + if !given.is_empty() && self.app.automation_is_acting() { + return Err(tl!("Agents can't change the agent settings: the person sets them in Preferences › AI Integrations.").into()); + } + if !given.is_empty() && self.w.automated { + self.w.draft.set(AGENTS_KEY, &read); + return Err(tl!( + "The agent settings were changed while automation used this window, so they were put back: only the person at the keyboard can change them. Close Preferences and open it again to change them." + ) + .into()); + } if !given.is_empty() { self.app.run("prefs.agents", Value::Object(given))?; } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 4e7de7049b..48691220a7 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1616,6 +1616,83 @@ fn ai_integrations_page_saves_the_agent_settings_on_ok() { assert_eq!(saved[0].when_app_closed, craft::automation::agents::WhenAppClosed::Error); } +/// Once input injected through the control channel has reached the open window, OK does not save agent settings +/// changed in it while it stays open: an edit made there (such as a folder typed on AI Integrations that lands in a +/// later pass) is undone and OK says why. In a window the person opens again, OK saves what they enter. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn ok_does_not_save_agent_settings_edited_while_automation_drove_the_window() { + use craft::automation::ControlRequest; + use craft::automation::agents::{AgentSettings, AgentSwitch}; + use std::sync::{Arc, Mutex}; + let saved: Arc>> = Arc::default(); + let into = saved.clone(); + let save: crate::agents::SaveFn = Box::new(move |s| { + into.lock().unwrap().push(s.clone()); + Ok(()) + }); + let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save) + .with_default_folder(None); + let (tx, rx) = std::sync::mpsc::channel(); + let mut a = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx)).with_agents(agents); + let ctx = crate::testing::ui_context(); + open(&mut a, Some(crate::agents::PAGE_TITLE)); + crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default()); + let (req, _reply) = ControlRequest::new("ui.key", json!({"key": "A"})); + tx.send(req).unwrap(); + a.run_control(&ctx); + for _ in 0..3 { + crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default()); + } + assert!(is_open(&a)); + let read_root = |a: &VectorcraftApp| a.prefs.as_ref().and_then(|w| w.draft.get::("integrations.readRoot")); + a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/everything"); + let refused = confirm(&mut a).expect_err("the agent folder edited while automation drove the window is not saved"); + assert!(refused.contains("person at the keyboard"), "{refused}"); + assert!(saved.lock().unwrap().is_empty(), "nothing saved"); + assert!(is_open(&a), "the window stays open"); + assert_ne!(read_root(&a).as_deref(), Some("/everything"), "the edit is undone in the window"); + a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/later"); + a.ui.answering_control = true; + assert!(confirm(&mut a).is_err(), "an OK automation sends"); + a.ui.answering_control = false; + assert_eq!(read_root(&a).as_deref(), Some("/later"), "an OK automation sends leaves the draft as it is"); + assert!(confirm(&mut a).is_err(), "the window stays guarded while it is open"); + assert!(saved.lock().unwrap().is_empty(), "still nothing saved"); + cancel(&mut a); + open(&mut a, Some(crate::agents::PAGE_TITLE)); + a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/chosen"); + confirm(&mut a).unwrap(); + assert_eq!(saved.lock().unwrap().last().map(|s| s.read_root.clone()), Some("/chosen".to_string()), "the person's own edit"); +} + +/// An OK a control request sends saves no agent setting the person changed, and leaves their edit in the window. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn ok_sent_by_automation_keeps_the_persons_agent_edit_unsaved_in_the_window() { + use craft::automation::agents::{AgentSettings, AgentSwitch}; + use std::sync::{Arc, Mutex}; + let saved: Arc>> = Arc::default(); + let into = saved.clone(); + let save: crate::agents::SaveFn = Box::new(move |s| { + into.lock().unwrap().push(s.clone()); + Ok(()) + }); + let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save) + .with_default_folder(None); + let mut a = app().with_agents(agents); + open(&mut a, Some(crate::agents::PAGE_TITLE)); + a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/mine"); + a.ui.answering_control = true; + let r = confirm(&mut a); + a.ui.answering_control = false; + assert!(r.is_err(), "{r:?}"); + assert!(saved.lock().unwrap().is_empty()); + assert_eq!(a.prefs.as_ref().and_then(|w| w.draft.get::("integrations.readRoot")).as_deref(), Some("/mine")); + confirm(&mut a).unwrap(); + assert_eq!(saved.lock().unwrap().last().map(|s| s.read_root.clone()), Some("/mine".to_string())); +} + /// OK sends only the agent settings changed in the window: one changed through `prefs.agents` while Preferences is /// open keeps its new value. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index d7545f2df7..9a343ade45 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -44,7 +44,8 @@ pub struct Done { /// The document rendered, and the options it was rendered with. pub doc: Arc, pub opts: RenderOptions, - pub img: Rendered, + /// The frame's pixels, a pixel a word ([`Renderer::render_words`]). + pub img: Rendered>, pub ms: f64, /// [`vectorcraft_render::FrameStats::moved`] of the frame. pub moved: usize, diff --git a/crates/ui-egui/src/screen_color.rs b/crates/ui-egui/src/screen_color.rs index c644b9b7a2..d7495adb83 100644 --- a/crates/ui-egui/src/screen_color.rs +++ b/crates/ui-egui/src/screen_color.rs @@ -41,6 +41,33 @@ fn remember_doc(app: &VectorcraftApp, ctx: &egui::Context) { ctx.data_mut(|d| d.insert_temp(doc_key(), uid)); } +/// Where the owner of the running pick is kept, as a hash of its key. +fn owner_key() -> egui::Id { + egui::Id::unique("screen-color-owner") +} + +fn owner_hash(owner: impl Hash) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + owner.hash(&mut hasher); + hasher.finish() +} + +fn remember_owner(ctx: &egui::Context, owner: impl Hash) { + let key = owner_hash(owner); + ctx.data_mut(|d| d.insert_temp(owner_key(), key)); +} + +/// Ends the running pick when `owner` started it, and drops a color `owner` has not taken yet; a +/// pick another owner started keeps running. The next pass finishes a capture the cancel ends. +pub(crate) fn cancel_for(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash) { + let started_by = ctx.data(|d| d.get_temp::(owner_key())); + if app.screen_pick.busy() && started_by == Some(owner_hash(&owner)) { + app.screen_pick.cancel(); + ctx.request_repaint(); + } + let _ = app.screen_pick.take(owner); +} + /// The platform can capture the screen: the shell's capabilities say so and no capture has said it /// cannot. Without a window there is nothing to capture. pub fn available(app: &VectorcraftApp) -> bool { @@ -65,6 +92,10 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result { } if let Some(ctx) = app.ui_ctx.clone() { remember_doc(app, &ctx); + match picker { + Some(id) => remember_owner(&ctx, crate::dialogs::color_picker::owner(id)), + None => remember_owner(&ctx, if stroke { STROKE } else { FILL }), + } } match picker { Some(id) => app.screen_pick.start(crate::dialogs::color_picker::owner(id)), @@ -78,6 +109,7 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result { pub(crate) fn hold(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option { if !app.screen_pick.busy() { remember_doc(app, ctx); + remember_owner(ctx, &owner); } app.screen_pick.hold(ctx, owner, gesture) } diff --git a/crates/ui-egui/src/screen_color/tests.rs b/crates/ui-egui/src/screen_color/tests.rs index f36e669422..414a1a41c0 100644 --- a/crates/ui-egui/src/screen_color/tests.rs +++ b/crates/ui-egui/src/screen_color/tests.rs @@ -89,6 +89,35 @@ fn the_color_pickers_eyedropper_samples_into_it() { assert_eq!(paints(&app).0, "#123456"); } +/// Closing the Color Picker ends the sample its eyedropper started. +#[test] +fn closing_the_color_picker_ends_its_sample() { + let (mut app, ctx) = app(); + app.run("ui.colorPicker", json!({})).unwrap(); + let id = app.color_dialogs.pickers.last().unwrap().id; + assert_eq!(hold(&mut app, &ctx, crate::dialogs::color_picker::owner(id), ScreenPickGesture::Clicked), None); + assert!(app.screen_pick.busy()); + assert!(app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id))); + let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.color_dialogs.pickers.is_empty()); + assert!(!app.screen_pick.busy(), "the sample ends with the picker"); +} + +/// Ending a picker's pick drops the color it sampled and has not taken yet; another owner's color +/// stays. +#[test] +fn ending_a_pick_drops_the_color_its_owner_has_not_taken() { + let (mut app, ctx) = app(); + for own in [true, false] { + assert_eq!(hold(&mut app, &ctx, "picker", ScreenPickGesture::Clicked), None); + finish(&mut app, &ctx, Ok(srgba("#123456"))); + assert!(!app.screen_pick.busy(), "the capture finished"); + cancel_for(&mut app, &ctx, if own { "picker" } else { "other" }); + assert_eq!(take(&mut app, &ctx, "picker").is_some(), !own, "own {own}"); + } +} + /// A canceled capture changes nothing; a failed one reaches the status line. #[test] fn cancel_and_errors_leave_the_art_alone() { diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index eed7529753..33862e7af2 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -55,12 +55,21 @@ pub(crate) struct PaletteWindow { /// field shows it until no change of that field waits, even while the palette's field holds the /// same text, since a run before the change may set the field to another one. pending: BTreeMap, + queued_texts: Vec, open: bool, } impl PaletteWindow { fn new(palette: ScriptPalette) -> Self { - PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), pending: BTreeMap::new(), open: true } + PaletteWindow { + palette, + drafts: BTreeMap::new(), + draft_scopes: BTreeMap::new(), + given: Vec::new(), + pending: BTreeMap::new(), + queued_texts: Vec::new(), + open: true, + } } /// The palette as the session has it now. A typed text whose field the palette no longer has is @@ -68,6 +77,7 @@ impl PaletteWindow { /// [`vectorcraft_engine::Session::script_palette_changes_waiting`]). fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) { self.palette = palette; + self.queued_texts = waiting.iter().filter(|(id, _)| *id == self.palette.id).map(|(_, field)| *field).collect(); script_window::keep_fields(&self.palette.dialog, &mut self.drafts); let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty()); self.pending.retain(|id, _| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id)); @@ -76,7 +86,7 @@ impl PaletteWindow { /// Draws the palette's controls in `ui` and takes what the person did, as its body does. #[cfg(test)] pub(crate) fn paint(&mut self, ui: &mut Ui) { - let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true); + let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true, &self.queued_texts); self.take_pass(pass.drafts.into_iter().collect(), pass.events); } @@ -105,8 +115,12 @@ impl PaletteWindow { /// the focus. #[cfg(test)] pub(crate) fn commit_text(&mut self, i: usize, text: &str) { - if let Some(n) = self.palette.dialog.nodes.get(i) { - self.take_pass(vec![(n.id, None)], vec![UiEvent::Change(i, UiValue::Text(text.to_string()))]); + let committed = shown_dialog(&self.palette.dialog, &self.pending) + .nodes + .get(i) + .map(|n| (n.id, script_window::text_change(i, n, text.to_string(), self.queued_texts.contains(&n.id)))); + if let Some((id, event)) = committed { + self.take_pass(vec![(id, None)], event.into_iter().collect()); } } @@ -219,7 +233,7 @@ impl StackDialog for PaletteWindow { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let heading = script_window::heading(&self.palette.dialog); - let PaletteWindow { palette, drafts, pending, open, .. } = self; + let PaletteWindow { palette, drafts, pending, queued_texts, open, .. } = self; let dialog = shown_dialog(&palette.dialog, pending); let drafts_now = &*drafts; // The body can run twice in a pass (measure, then paint), so the last run's report is @@ -228,7 +242,7 @@ impl StackDialog for PaletteWindow { .modeless() .initial_focus(Initial::Keep) .opened(Bind::bound(open)) - .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true)); + .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true, queued_texts)); let pass = shown.inner.unwrap_or_default(); let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes @@ -316,7 +330,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => true, }); let before = at_pass.clone(); - let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); + let (batch, refused) = drafted(app, p, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); // A refused text keeps every later click and close out of line too. change_refused |= refused; // A text the click or close took leaves its field unless a later one was typed there. @@ -358,13 +372,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { /// events with their scopes, and whether a text was refused. fn drafted( app: &mut VectorcraftApp, - w: &ScriptUiDialog, + p: &ScriptPalette, drafts: &mut BTreeMap, events: &mut Vec, scope: &ScopeHandle, pass_scope: &ScopeHandle, draft_scopes: &BTreeMap, ) -> (Vec<(ScopeHandle, UiEvent)>, bool) { + let w = &p.dialog; let mut refused = false; if let Some(e) = script_window::keep_refused(w, drafts, events) { app.status(e); @@ -375,7 +390,10 @@ fn drafted( if events.iter().any(closing) { changes.extend(events.iter().filter(|e| !closing(e)).cloned()); let existing = changes.len(); - match script_window::commit_texts(w, drafts, &mut changes) { + // A draft that matches its field's text still goes in line when a change of that field + // waits, so the click reads the draft and not the waiting change. + let queued: Vec = app.session.script_palette_changes_waiting().into_iter().filter(|(id, _)| *id == p.id).map(|(_, e)| e).collect(); + match script_window::commit_texts_over(w, drafts, &mut changes, &queued) { Ok(()) => { drop(changes.drain(..existing)); } @@ -465,10 +483,38 @@ pub(crate) fn with_palette(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut } /// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]): -/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no -/// frame meanwhile. +/// it also waits while the last run's print jobs wait to be approved or canceled, and after a start +/// that failed until the person's next input or a change of the edit state ([`clear_failed_start`]), +/// and asks for no frame meanwhile. pub(crate) fn can_start(app: &VectorcraftApp) -> bool { - app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app) + app.ui.palette_start_failed.is_none_or(|at| at != edit_state(app)) + && app.session.script_palette_can_start() + && !crate::script_runs::waiting_for_print(app) +} + +/// What a failed start may depend on: the documents, whether each has changes, an open drag or +/// undo group, the active one, and the palette events in line. +fn edit_state(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + for d in app.session.documents() { + (d.uid, d.is_dirty(), d.interaction.is_some(), d.undo_group.is_some()).hash(&mut h); + } + app.session.active().map(|d| d.uid).hash(&mut h); + app.session.script_copy_first.hash(&mut h); + app.session.prefs.recovery_off_for_complex.hash(&mut h); + app.session.prefs.recovery_folder.hash(&mut h); + app.session.script_palette_events_waiting().hash(&mut h); + app.session.script_palette_last_ticket().hash(&mut h); + h.finish() +} + +/// Lets a waiting palette event whose start failed try again once the frame carries input, which +/// may have changed the edit that kept it from starting. +pub(crate) fn clear_failed_start(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.ui.palette_start_failed.is_some() && ctx.input(|i| !i.events.is_empty()) { + app.ui.palette_start_failed = None; + } } /// Starts the run of the oldest waiting palette event when no run is going. → whether one started. @@ -485,6 +531,7 @@ pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { None => false, Some(Ok(_)) => true, Some(Err(e)) => { + app.ui.palette_start_failed = Some(edit_state(app)); app.status(e.to_string()); false } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 099a0c556c..9f75b2cc80 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,15 +1,17 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, -//! waits for the person's answer. A run that prepared jobs for a printer ends with the question -//! before they are sent. With no run going, the oldest event a ScriptUI palette waits with starts -//! its run ([`crate::script_palettes`]). +//! `alert`, `confirm`, `prompt`, `app.showColorPicker`, a ScriptUI dialog's `show()` or a `File` or +//! `Folder` file dialog, waits for the person's answer. A run that prepared jobs for a printer ends +//! with the question before they are sent. With no run going, the oldest event a ScriptUI palette +//! waits with starts its run ([`crate::script_palettes`]). use serde_json::{Value, json}; use vectorcraft_engine::WindowView; +use vectorcraft_engine::script::DialogKind; use crate::VectorcraftApp; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; use crate::dialogs::script_window; @@ -239,13 +241,22 @@ fn ask(app: &mut VectorcraftApp) -> bool { } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if script_run::can_ask(app) { + if dialog.kind == DialogKind::ColorPicker { + // A picker that closed this frame answers the run in its own pump. + if color_picker::script_picker(app).is_none() + && !script_run::busy(app) + && let Some(color) = dialog.color + { + color_picker::open_for_script(app, color, dialog.cmyk_document); + } + } else if script_run::can_ask(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + script_run::forget_color_picker(app); // A run past its growth allowance asks about it first, also when its ScriptUI dialog waits // again. if app.session.script_waiting() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2ad9bce8d8..fda6c31677 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -724,6 +724,12 @@ pub struct UiState { #[serde(skip)] pub touch_drawing_tool: Option, pub status: String, + /// The edit state in which the last start of a waiting palette event's run failed + /// ([`crate::script_palettes::start_next`]). The event then waits for the person's next input, + /// or for that state to change, before it starts again, and asks for no frame meanwhile. Not + /// saved. + #[serde(skip)] + pub palette_start_failed: Option, /// How many times [`crate::VectorcraftApp::status`] has set `status`, so that work finishing /// later can tell whether the line it started with is still the latest one. Not saved. #[serde(skip)] @@ -1553,6 +1559,7 @@ impl Default for UiState { group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), touch_drawing_tool: None, status: String::new(), + palette_start_failed: None, status_sets: 0, script_print_failures: 0, script_print_failure_notes: Vec::new(), diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 28d573d09b..2045e85976 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -75,6 +75,83 @@ fn samples_show_the_text_in_the_family_or_a_generic_sample() { assert_eq!(texts.iter().filter(|t| t.text == "Sample").count(), 2, "both runs are the generic sample: {texts:?}"); } +/// A face with no hinting instructions draws a sample in a context the app has adopted, as the font list and the +/// font picker draw each family's sample in its own face (a document face of the context): a Hebrew letter that is a +/// bar 20 by 700 thousandths of an em, whose blue zones the automatic hinter of skrifa 0.44 never finishes measuring. +/// The face is served to the fixture's context only, so the font database other tests read does not change. The +/// sample is one rasterized glyph from that face. It is drawn on a thread of its own, and the test fails when it has +/// not ended after 300 s. +#[test] +fn a_face_without_hinting_instructions_draws_its_sample() { + use std::sync::{Arc, Mutex}; + + use craft::ui::fonts::{FaceBytes, FaceState}; + use craft::ui::primitives::{ContentPainterCx, DocRun, DocText, FacesCx as _}; + use craft::ui::runtime::env::Env; + use craft::ui::style::{DataColor, SurfaceKind}; + use craft::ui::testing::Fixture; + use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font}; + + let mut glyph = FileGlyph { ch: '\u{5d1}', outline: Default::default(), advance: 300.0 }; + glyph.outline.move_to((0.0, 0.0)); + glyph.outline.line_to((0.0, 700.0)); + glyph.outline.line_to((20.0, 700.0)); + glyph.outline.line_to((20.0, 0.0)); + glyph.outline.close_path(); + let info = FileFontInfo { family: "Unhinted Bar".into(), style: "Regular".into(), ..Default::default() }; + let bytes: Arc<[u8]> = Arc::from(build_file_font(&info, &[glyph]).unwrap()); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let sample = Arc::new(Mutex::new((false, false))); + let drawn_sample = Arc::clone(&sample); + let mut fixture = Fixture::new(move |ui| { + *drawn_sample.lock().unwrap() = (false, false); + let env = Env::of(ui); + let cx = ContentPainterCx::new(ui.painter().clone(), &env, SurfaceKind::Panel.ink()); + let state = cx.document_face("font-sample/Unhinted Bar/Regular", || { + let bytes = Arc::clone(&bytes); + move || Some(FaceBytes::new(bytes, 0)) + }); + let FaceState::Ready(font) = state else { return }; + let color = DataColor::new(egui::Color32::BLACK); + let runs = [DocRun::new("\u{5d1}", font, 16.0, color)]; + let layout = cx.layout(&DocText::new(&runs)); + let fixture_has_glyph = layout + .galley + .job + .sections + .first() + .is_some_and(|section| ui.ctx().fonts_mut(|fonts| fonts.has_glyph(§ion.format.font_id, '\u{5d1}'))); + let mut glyphs = layout.galley.rows.iter().flat_map(|row| row.glyphs.iter()); + let nonempty_glyph = + glyphs.next().is_some_and(|glyph| glyph.chr == '\u{5d1}' && glyph.uv_rect.size.x > 0.0 && glyph.uv_rect.size.y > 0.0) + && glyphs.next().is_none(); + *drawn_sample.lock().unwrap() = (fixture_has_glyph, nonempty_glyph); + cx.painter.galley(ui.max_rect().min, layout.galley.clone(), color.0); + }); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.adopt_context(fixture.ctx()); + fixture.settle(); + let texts = fixture.texts().iter().map(|t| t.text.clone()).collect::>(); + let (fixture_has_glyph, nonempty_glyph) = *sample.lock().unwrap(); + let ctx = fixture.ctx(); + let hinting = [ + ctx.global_style().visuals.text_options.font_hinting, + ctx.style_of(egui::Theme::Light).visuals.text_options.font_hinting, + ctx.style_of(egui::Theme::Dark).visuals.text_options.font_hinting, + ]; + tx.send((texts, hinting, fixture_has_glyph, nonempty_glyph)).ok() + }); + let (texts, [hinting, light_hinting, dark_hinting], fixture_has_glyph, nonempty_glyph) = + rx.recv_timeout(std::time::Duration::from_secs(300)).unwrap_or_else(|e| panic!("drawing the sample: {e}")); + assert!(texts.iter().any(|t| t == "\u{5d1}"), "the sample is the letter, in the face: {texts:?}"); + assert!(!hinting, "a context the app adopts draws text without hinting"); + assert!(!light_hinting, "the light theme draws text without hinting"); + assert!(!dark_hinting, "the dark theme draws text without hinting"); + assert!(fixture_has_glyph, "the sample's face maps U+05D1"); + assert!(nonempty_glyph, "the sample is one rasterized glyph for U+05D1"); +} + #[test] fn preview_changes_the_text_live_and_only_a_choice_is_a_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 29b439050d..9d2c95bffd 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -1,12 +1,14 @@ //! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, //! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers -//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other -//! script tests. +//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers +//! over the dialog host are shared with the other script tests. +use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice}; use crate::{VectorcraftApp, menus, script_runs}; @@ -318,6 +320,196 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["log"], json!([true, "p", "done"])); } +/// Is the Color Picker of the script's `app.showColorPicker` open? +fn picker_open(app: &VectorcraftApp) -> bool { + let id = color_picker::script_picker(app); + id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::(id).is_some()).unwrap()) +} + +/// Polls the run until it ends, or until its Color Picker is open (true). +fn until_picker(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if picker_open(app) { + return true; + } + } + panic!("the script neither ended nor opened the Color Picker"); +} + +/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump. +fn answer_picker(app: &mut VectorcraftApp, ok: bool) { + let id = color_picker::script_picker(app).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap(); + assert!(done); + color_picker::pump(app, &ctx); +} + +#[test] +fn the_color_picker_waits_and_answers_the_run() { + let mut app = app(); + // A selected object, which a picker that previews would paint. + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap(); + let gray = "var g = new GrayColor(); g.gray = 40;"; + start( + &mut app, + &format!( + "{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \ + {gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());" + ), + ); + assert!(until_picker(&mut app)); + assert!(!is_open::(&app), "the picker opens in place of a notice"); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + app.ui.status.clear(); + color_picker::pump(&mut app, &ctx); + // A preview would begin an edit, which the running script refuses with a status message. + assert_eq!(app.ui.status, "", "the picker starts no preview"); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app), "the next call opens the picker again"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app)); + answer_picker(&mut app, false); + assert!(!until_picker(&mut app)); + assert_eq!( + log(&app), + json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]), + "OK gives the color picked, untouched its own color, Cancel the color given" + ); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing"); + let dialogs = app.session.script_report().unwrap()["dialogs"].clone(); + assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null"); +} + +#[test] +fn the_same_color_set_in_another_model_is_a_new_pick() { + let mut app = app(); + start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);"); + assert!(until_picker(&mut app)); + // The gray's own sRGB, set as a plain color, as a screen sample sets one. + let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap(); + script_run::with_host(&app, |host, _| host.get_mut_by_id::(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave"); +} + +#[test] +fn stopping_or_quitting_the_run_closes_its_color_picker() { + let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');"); + let mut app = app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert!(!picker_open(&app), "no picker is left for the stopped run"); + assert!(color_picker::script_picker(&app).is_none()); + assert_eq!(objects(&app), 0, "the run's edit goes back"); + assert_eq!(log(&app), json!([])); + let mut app = self::app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + script_run::ask_to_close(&mut app); + assert!(is_open::(&app), "quitting asks over the picker"); + cancel(&mut app, CLOSE_KIND); + assert!(picker_open(&app), "Cancel shows the picker again"); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert!(!picker_open(&app), "no picker is left for the abandoned run"); + assert_eq!(objects(&app), 0); +} + +#[test] +fn stopping_the_run_ends_only_the_screen_pick_its_color_picker_started() { + use craft::color_ui::ui::ScreenPickGesture; + let source = "var c = new RGBColor(); app.showColorPicker(c);"; + for own in [true, false] { + let mut app = app(); + start(&mut app, source); + assert!(until_picker(&mut app)); + let ctx = app.ui_ctx.clone().unwrap(); + let id = color_picker::script_picker(&app).unwrap(); + let started = if own { + crate::screen_color::hold(&mut app, &ctx, color_picker::owner(id), ScreenPickGesture::Clicked) + } else { + crate::screen_color::hold(&mut app, &ctx, "fill", ScreenPickGesture::Clicked) + }; + assert_eq!(started, None); + assert!(app.screen_pick.busy()); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert_eq!(app.screen_pick.busy(), !own, "own pick {own}: only the picker's own pick ends with it"); + } +} + +#[test] +fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() { + let mut app = app(); + let ctx = app.ui_ctx.clone().unwrap(); + // A frame of the window's dialogs starts the open pickers with the app's host, whose settings + // keep what a picker remembers. + let frame = |app: &mut VectorcraftApp| { + let _ = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + }); + }; + // A fill picker closed with Only Web Colors on, which later fill pickers recall. + color_picker::open(&mut app, &json!({})).unwrap(); + frame(&mut app); + set(&app, "fill", "webColors", json!(true)).unwrap(); + let id = open_id(&app, "fill"); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + color_picker::pump(&mut app, &ctx); + color_picker::open(&mut app, &json!({})).unwrap(); + frame(&mut app); + assert_eq!(fields(&app, "fill")["webColors"], json!(true), "the next fill picker recalls Only Web Colors"); + let id = open_id(&app, "fill"); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + color_picker::pump(&mut app, &ctx); + // A frame without the picker drops its overlay. + frame(&mut app); + assert!(!script_run::busy(&app), "no picker is left open"); + start( + &mut app, + "var c = new RGBColor(); c.red = 18; c.green = 52; c.blue = 86; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());", + ); + assert!(until_picker(&mut app)); + frame(&mut app); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor,18,52,86"]), "untouched OK gives the script's color, not its nearest web color"); +} + +#[test] +fn a_pick_takes_the_model_of_the_document_the_script_made() { + for (doc, made, want) in [("{}", "CMYK", "CMYKColor"), ("{\"colorMode\": \"cmyk\"}", "RGB", "RGBColor")] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default())); + app.run("file.new", serde_json::from_str(doc).unwrap()).unwrap(); + app.session.prefs.show_external_script_warning = false; + start( + &mut app, + &format!( + "app.documents.add(DocumentColorSpace.{made}, 50, 60, 1); var c = new RGBColor(); c.red = 255; \ + var p = app.showColorPicker(c); vc.log(p.typename);" + ), + ); + assert!(until_picker(&mut app)); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!([want]), "an RGB pick in the {made} document the script made"); + } +} + /// Only the person at the keyboard turns off the external script warning: Yes from automation, set /// as the answer or given in a pass automation drives, is refused, the warning stays on and the /// question opens again; No is taken from automation. diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index ef816ce39e..e2ffd4626b 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -260,6 +260,81 @@ fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() { } } +#[test] +fn a_click_reads_a_typed_text_that_matches_the_field_while_another_change_of_it_waits() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap(); + // The person types the field's text back and clicks before the change to `b` is delivered. + with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + let mut logs = Vec::new(); + for _ in 0..10 { + script_runs::poll(&mut app); + if !app.session.script_running() && app.session.script_palette_events_waiting() == 0 { + break; + } + run_to_end(&mut app); + logs.extend(app.session.script_report().unwrap()["log"].as_array().cloned().unwrap_or_default()); + } + run_to_end(&mut app); + if let Some(report) = app.session.script_report() { + logs.extend(report["log"].as_array().cloned().unwrap_or_default()); + } + assert!(logs.contains(&json!("clicked a")), "the click reads the text the person typed: {logs:?}"); + assert!(!logs.contains(&json!("clicked b")), "{logs:?}"); +} + +#[test] +fn focus_loss_commits_a_restored_text_while_another_change_of_the_field_waits() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap(); + follow(&mut app); + with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let paint = |app: &mut VectorcraftApp, events: Vec| { + let raw = egui::RawInput { events, ..Default::default() }; + crate::testing::part_frame(app, &ctx, raw, |app, ui| { + with_palette(app, id, |w| w.paint(ui)); + }); + }; + paint(&mut app, Vec::new()); + // Tab gives the edit field, the palette's first control, the keyboard focus. + let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + paint(&mut app, vec![tab(true), tab(false)]); + paint(&mut app, Vec::new()); + let focused = ctx.memory(|m| m.focused()).expect("the edit field has the keyboard focus"); + assert!(ctx.text_edit_focused()); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some("a")); + // Tab moves the keyboard focus on to the Go button, and the pass after it gives the field's text to the script. + paint(&mut app, vec![tab(true), tab(false)]); + paint(&mut app, Vec::new()); + paint(&mut app, Vec::new()); + assert_ne!(ctx.memory(|m| m.focused()), Some(focused), "the edit field lost the keyboard focus"); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten(), None, "focus loss gives the typed text"); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "focus loss merges the restored text into the waiting change"); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 2, "the click follows the restored text"); + for _ in 0..2 { + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + } + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked a"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_text_typed_in_two_scopes_goes_to_the_script_in_what_both_allow() { use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; @@ -791,6 +866,68 @@ fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() { assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status); } +#[test] +fn a_click_whose_run_cannot_begin_asks_for_no_frame_until_the_next_input() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine two\nvar p = new Window('palette'); p.add('button', undefined, 'A').onClick = function () { vc.log('a'); }; \ + p.add('button', undefined, 'B').onClick = function () { vc.log('b'); }; p.show();", + ); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + give(&app, id, UiEvent::Click(1)); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the second click still waits"); + assert!(!script_palettes::can_start(&app), "the failed start does not retry, nor ask for a frame, on every pass"); + // An event given without the window, as automation gives one, changes what the start depends on. + app.session.script_palette_event(id, UiEvent::Click(1)).unwrap(); + assert!(script_palettes::can_start(&app), "a change of the edit state lets the start try again"); + assert!(!script_palettes::start_next(&mut app)); + assert!(!script_palettes::can_start(&app)); + let ctx = app.ui_ctx.clone().unwrap(); + let input = egui::RawInput { events: vec![egui::Event::PointerGone], ..Default::default() }; + crate::testing::part_frame(&mut app, &ctx, input, |app, ui| script_palettes::clear_failed_start(app, ui.ctx())); + assert!(script_palettes::can_start(&app), "the person's next input lets the click try again"); + app.session.script_copy_first = false; + assert!(script_palettes::start_next(&mut app)); +} + +#[test] +fn a_failed_palette_start_retries_after_recovery_settings_change_without_input() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine retries\nvar p = new Window('palette'); \ + for (var i = 0; i < 3; i++) { p.add('button', undefined, 'Go ' + i).onClick = function () { vc.log('clicked'); }; } p.show();", + ); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + for i in 1..=3 { + give(&app, id, UiEvent::Click(i)); + } + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 2); + assert!(!script_palettes::can_start(&app)); + assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "the failed start asks for no frames"); + app.session.execute("prefs.set", &json!({"key": "recoveryOffForComplex", "value": true})).unwrap(); + assert!(script_palettes::can_start(&app), "automation can change the recovery condition without window input"); + assert!(!script_palettes::start_next(&mut app), "the missing recovery store still prevents a start"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + assert!(!script_palettes::can_start(&app)); + assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "a repeated failure still asks for no frames"); + app.session.script_copy_first = false; + assert!(script_palettes::can_start(&app), "disabling the recovery prerequisite permits another attempt"); + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index f78dd21961..7c3c3d69f7 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -277,6 +277,15 @@ fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() { cancel(&mut app, PRINT_KIND); script_runs::poll(&mut app); assert_eq!(app.session.script_palette_events_waiting(), 0, "the click's run starts once the jobs are answered"); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the click's run ends"); + let report = app.session.script_report().expect("the click's run reports"); + assert_eq!(report["log"], serde_json::json!(["clicked"]), "the click's handler ran: {report}"); } /// Cancel, from anyone, drops the jobs and keeps the run's changes. diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 24260dc24c..e75c8e21b1 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -24,6 +24,17 @@ pub fn ui_fonts() -> UiFonts<'static> { } } +/// Turns font hinting off for all text `ctx` draws, in both themes. With hinting on, egui hints a TrueType face that +/// has no hinting instructions (no `fpgm`, no `prep` and no glyph instructions) with skrifa 0.44's automatic hinter, +/// whose blue-zone search never ends for some glyphs, such as a tall narrow Hebrew letter, so the font list stops +/// responding when a row draws such a face. The font list and the samples get their faces through craft-libs, which +/// sets no hinting option per face, so the switch covers every face of the context. Hinting stays off until the +/// skrifa blue-zone exit (storytold/craft-libs#5222) is in the build; the craft-libs pin that brings it removes this +/// function and its call. +pub(crate) fn hinting_off(ctx: &egui::Context) { + ctx.all_styles_mut(|style| style.visuals.text_options.font_hinting = false); +} + #[derive(Clone)] struct FontSelection { language: Lang, diff --git a/docs/mcp.md b/docs/mcp.md index ee2d767223..76d0797f83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -47,7 +47,11 @@ only the folders given on its command line, as before. Preferences › AI Integrations shows the switch's state, the port agents connect on, Control Port (0: any free port), the two folders and the closed-app choice. Without the `AI-MCP` flag it only says that agents use VectorCraft without a window. The same settings are the UI command `prefs.agents {controlPort?, readRoot?, -writeRoot?, whenAppClosed?}`, which agents' own requests can read but not change. Started with `--control`, +writeRoot?, whenAppClosed?}`, which agents' own requests can read but not change. Once input injected through +the control channel has reached the open Preferences window, OK and Apply in that window put the agent +settings back as they were read and save none of them; the person changes them in a Preferences window +they open again. An OK or Apply sent by a control request is refused when it would change an agent setting, +and leaves the window's draft as it is. Started with `--control`, the window serves that channel for the whole run instead, and the page says so. ### Command catalogue (headless vs remote) @@ -3086,7 +3090,8 @@ through `$`: describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`, `app.redraw()`, `app.undo()`, `app.redo()`, - `app.getIsFileOpen(path)`, `app.selectTool(name)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing + `app.getIsFileOpen(path)`, `app.selectTool(name)`, `app.showColorPicker(color)` (described with the dialogs + below) and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing anything. `app.undo()` and `app.redo()` run `edit.undo` and `edit.redo` in the active document and reach only the steps the run made; with no such step they change nothing, and with no document open they throw `No active document` (VectorCraft's own rules). After a run that succeeds, each document that was open @@ -3198,7 +3203,8 @@ through `$`: its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with - nothing changed, when they would leave an image at the bottom of such a group. An object of + nothing changed, when they would leave an image at the bottom of such a group, and so do `groupItems.removeAll()` + and `compoundPathItems.removeAll()`. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or @@ -3764,7 +3770,9 @@ through `$`: `NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept. `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as - https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it; a gray within about 1e-14 % of white reads as + 100; assigning it to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it + to any other paint gives white), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -4430,8 +4438,10 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`). `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a - `show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list - stopped at its limit. + `show()` that ended with an error. `app.showColorPicker` is listed as `{kind: "colorPicker", color, answer}`, with + the color it opened on and the color picked, `null` for Cancel, `"stop"` or `"missing"`, each color as + `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at + its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -4478,6 +4488,22 @@ left, when the next answer is for another kind of dialog, or when the script end and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an empty object are the same. +`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at +https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, +`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in the app, +when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so +the color's `typename` can differ from the picker's model and from the color given. An answer taken from `answers` +keeps the color model it was given. The picker opens on the color as +given, whatever Only Web Colors was left at in another picker. OK with both the color and its model unchanged, and Cancel, return a new object of the color the +script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting +end the run as they do at the other dialogs, and close the picker. They also end a screen color sample +(`ui.sampleScreenColor` with `picker`, or the picker's eyedropper) that the picker started, and drop a sampled color +it has not taken; a sample started for the fill, the stroke or another picker keeps running. A run with nobody to ask takes `{kind: +"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its +range (a color key such as `"rgb 300 0 0"` is refused, not clamped), or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. + ```sh vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` @@ -4686,7 +4712,9 @@ visible, controls: [{index, kind, name, text, enabled, visible, value?, items?, waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a `change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in -`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events in order and returns the report of +`ui.inspect`'s `scriptReport`. When a waiting event's run cannot begin in the app, the status bar shows the error, +and the events still in line wait until the next input in the window, another `script.palette.event`, or a change +to a document's unsaved state, drag or undo group, to the active document, or to the `recoveryFolder` or `recoveryOffForComplex` preference. With nobody to ask, it runs the waiting events in order and returns the report of the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's result when this one has run, and the events after it keep waiting. When an open edit cannot be finished before @@ -7351,7 +7379,8 @@ takes fewer, and an image past that limit at one sample a pixel draws the shaded drawn for a scene past the renderer's limits on triangles, vertices, lights or work, for a mesh point at or behind the eye, for Revolve on a group or on a fill or stroke, for solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, and for a later geometry effect that reshapes paths but -leaves images unchanged. The status bar and +leaves images unchanged. Extrude & Bevel and Inflate check the top fill and the strokes they build solids from; Rotate +checks every fill and stroke, since it draws a plane for each. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. A `render` that is not an object, another key, another value, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document changes. In wireframe mode the graphics' art is not checked against the graphics @@ -11001,6 +11030,11 @@ Printing / Exporting, `accurate` by default) does the same for RGB raster export Print as Bitmap: `rich` draws pure CMYK black as RGB black in the pixels; CMYK ink exports and the document's colours stay as they are. `antiAliasedBitmaps` (off by default; desktop app): in View › Pixel Preview, on softens placed and embedded bitmaps; off, their pixels stay hard-edged. +`smoothBitmaps` (Display Bitmaps as Anti-aliased Images, on by default): the same choice for the canvas unless +Pixel Preview draws its own pixel raster, which requires a document pixel larger than a screen pixel and a region +within the display's texture limit; off, placed and embedded bitmaps drawn larger than their pixels show each pixel +as a hard-edged square. Both preferences also cover images inside pattern tiles and placed documents. An image marked +pixelated is never softened. `pdfTextAs` (Preferences › File Handling › PDF Text, `text` by default; `text` or `outlines`): what the text of a PDF opened or placed embedded from the app becomes when the open or place gives no `textAs` (see `document.open`). `disableAutoAddDelete` (off by default): on, the Pen no longer adds or deletes an anchor when a click lands on a @@ -11754,6 +11788,8 @@ art's bounds); with `link: false` it is placed as one clipped group. An EPS file too, showing the art `link: false` places (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); with `link: false` or from `dataBase64` it is one group. `at` centres it, `rect` fits it, `replace` swaps the selected object (keeping its place and transform), `template` puts it on a new template layer. +When placed editable art names a font family it does not define as a composite font, and the document defines a +composite font of that name, the placed type gets a free name such as "Name 2" so it keeps the font it was laid out in. A DCS file (Desktop Color Separation, version 1.0 or 2.0: an EPS file whose header names one EPS program per printing plate, ) is placed only from its `path` with link, as one linked image ([Import DCS files](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-dcs-files.html)). @@ -18782,7 +18818,7 @@ records the value used, and a replay of that entry scales corners the same way w | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference); `corners` (the Scale Corners preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `corners` (the Scale Corners preference); `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes`; `corners` (the Scale Corners preference) | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `corners` (the Scale Corners preference); `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame after it is turned, with no smallest scale; the side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, a `size` that takes a width or a height the source or a target does not have, a `size` that a stroke or an effect that does not scale keeps a target from reaching, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `corners` (the Scale Corners preference); `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame after it is turned, with no smallest scale; the side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, a `size` that takes a width or a height the source or a target does not have, a `size` that a stroke or an effect that does not scale keeps a target from reaching, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group or a target's own layer or group is locked, when it would take a target out of the blend input it is in (a blend's input objects and the art inside each one stay in that input; to restack the blend itself, select the whole blend), when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. With Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 16d8de90b9..b1bba3d826 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -979,7 +979,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › Plug-ins & Scratch Disks describes its settings:** the line under the Preferences fields shows a sentence for Additional Plug-ins Folder, Primary and Secondary on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop the folder's `.wasm` plug-ins load at startup and when OK sets a new folder, except in Safe Mode, and the web version does not load them; Primary and Secondary take Startup, None or a folder path and are stored, but no scratch disk is used yet (G12 stays open). Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › User Interface describes its settings:** the line under the Preferences fields shows a sentence for each of the 13 User Interface settings, from Brightness to Language, System Title Bar and VectorCraft Title Bar on Every Desktop included where the platform shows them, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Accent Color is dimmed while the color scheme has its own accent; Outline view shows the canvas white whatever Canvas Color says; with Auto-Collapse Iconic Panels on, a panel opened from its icon closes on Esc or a click outside it; Open Documents As Tabs applies to documents opened or created afterwards; both title bar settings apply from the next start; UI Scaling leaves the size of art at a given zoom alone; Scale Cursor Proportional to UI sizes only the pointers VectorCraft draws; the dialog shows a chosen language before OK. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Performance describes its settings:** the line under the Preferences fields shows a sentence for each of the 8 Performance settings, from GPU Performance to Use Monitor Profile for Canvas, Linux Display Server included on Linux, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: GPU Performance only allows Animated Zoom; Animated Zoom makes wheel zooms glide and the Zoom tool zoom as it is dragged or held; Graphics Processor applies to the desktop version from the next start, and Automatic prefers the processor that drives the display; History States caps each document's undo steps, and the memory budget can drop older steps sooner; with Real-time Drawing and Editing off, outlines follow a drag and the art changes on release, while a ruler guide still moves; Render Threads sets the canvas rasterizer's workers, and the web version uses none; Linux Display Server's X11 choice always uses XWayland on a Wayland desktop and the others only with a pen attached; Use Monitor Profile for Canvas converts the canvas to the display's profile unless the system does so, and off draws it in sRGB. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. -- **Preferences › File Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 File Handling settings, from Enable Background Save to Use Compression, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop, Background Save writes saves to a file on the worker, and Background Export does the same for exports to files and packages but not 3D exports; timed recovery copies are made at the Every (minutes) interval, only of documents changed since their last copy, and skip documents with more than 20,000 objects when Turn off Data Recovery for complex documents is on; a blank recovery Folder uses VectorCraft's own folder, and the web version keeps copies in the browser; Number of Recent Files to Display limits Open Recent Files and the Home screen while up to 30 files stay remembered; Use Low Resolution Proxy for Linked EPS keeps a linked EPS image's saved preview on open; anti-aliased bitmaps apply only in Pixel Preview; Update Links rereads, asks or notes a changed link; a blank Templates Folder uses VectorCraft Templates in the documents folder; Edit Original opens raster images in PhotoCraft when its system-defaults option is off; files from older versions open marked [Converted] and Save asks where to save them; Use Compression compresses native files and templates unless a save says otherwise. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › File Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 File Handling settings, from Enable Background Save to Use Compression, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop, Background Save writes saves to a file on the worker, and Background Export does the same for exports to files and packages but not 3D exports; timed recovery copies are made at the Every (minutes) interval, only of documents changed since their last copy, and skip documents with more than 20,000 objects when Turn off Data Recovery for complex documents is on; a blank recovery Folder uses VectorCraft's own folder, and the web version keeps copies in the browser; Number of Recent Files to Display limits Open Recent Files and the Home screen while up to 30 files stay remembered; Use Low Resolution Proxy for Linked EPS keeps a linked EPS image's saved preview on open; Display Bitmaps as Anti-aliased Images smooths images, and its Pixel Preview setting takes its place while Pixel Preview draws its own pixel raster (zoom above one screen pixel per document pixel, region within the texture limit); Update Links rereads, asks or notes a changed link; a blank Templates Folder uses VectorCraft Templates in the documents folder; Edit Original opens raster images in PhotoCraft when its system-defaults option is off; files from older versions open marked [Converted] and Save asks where to save them; Use Compression compresses native files and templates unless a save says otherwise. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Clipboard Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 5 Clipboard Handling settings, from Include SVG Code to When pasting text, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Include SVG Code gives other apps SVG code of copied art, and on the desktop the code is not copied as text when the art embeds more than 1 MiB of images; the PDF checkbox puts a PDF on the system clipboard on Windows and macOS; both legacy vector clipboard settings are stored but not used yet; When pasting text applies to text copied from VectorCraft type and pasted into type, where Keep Formatting keeps its styles and Keep Plain Text gives it the style where it lands. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Appearance of Black describes its settings:** the line under the Preferences fields shows a sentence for On Screen and for Printing / Exporting on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas, and Display All Blacks Accurately converts it through the CMYK working space; Output All Blacks as Rich Black does the same in RGB and grayscale raster exports and Print as Bitmap, and does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Devices describes its settings:** the line under the Preferences fields shows a sentence for Enable Touch Workspace and for Enable Touch Gestures on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: with Enable Touch Workspace on, a touch screen switches VectorCraft to the Touch workspace, and turning the setting off or losing the touch screen goes back to the workspace it switched from; with Enable Touch Gestures on, a two-finger tap on the canvas undoes, or in the Touch workspace switches between selection and drawing tools, and a three-finger tap redoes, except in Presentation Mode. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices have sentences, and Type leaves the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. @@ -1123,7 +1123,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops are not there yet. `crates/engine/src/tests/script_text.rs`. @@ -1137,6 +1137,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. @@ -1189,7 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. When a waiting event's run cannot begin in the app, the status bar shows the error, and the events in line wait until the next input in the window, another palette event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the `recoveryFolder` or `recoveryOffForComplex` preference. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). @@ -1446,7 +1447,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. - **Pen rubber band over an anchor a click ends on:** over the path's first anchor, the preview segment ends on that anchor, as the closing segment does; over an end of another open path, it ends on that end and arrives along the end's own handle, as the joining segment does. The preview picks these anchors at the pointer before snapping, as a press does. Before, the preview ended at the pointer and arrived without a handle, so the segment moved by up to the pick tolerance at the click, and changed shape when the other end was smooth (#8296, in part; the `pen_rubber_band` tests in `engine/tests/it`); scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none or a size no display has; VectorCraft's own rules: a document in a floating window counts from that window's display, where the help page names only the primary monitor, and the preference also applies in Pixel Preview, which the help page leaves out; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: while Pixel Preview draws its own pixel raster, at a zoom above one screen pixel per document pixel and a region within the texture limit, images get each pixel from their nearest image pixel), and File Handling › Display Bitmaps as Anti-aliased Images, the same choice in every other case (on by default; off, images zoomed in show hard-edged pixels; `prefs.set` key `smoothBitmaps`, #10712). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none or a size no display has; VectorCraft's own rules: a document in a floating window counts from that window's display, where the help page names only the primary monitor, and the preference also applies in Pixel Preview, which the help page leaves out; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences › User Interface › UI Scaling scales the interface ([help](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/modify-workspaces.html)). VectorCraft's own rule is that it leaves the art's size alone: at a given zoom a document point covers the same device pixels at every UI Scaling, so View › Actual Size shows the art at the same size whatever the UI Scaling. A click, a pinch or wheel zoom about the pointer, a pan, the Zoom tool's marquee, Fit, tiled panes, Pixel Preview and the Navigator's view box use the same mapping. Evidence: `canvas::tests_ui_scaling`, `tiled_documents_fit_their_panes_at_every_ui_scaling`, `the_view_box_outlines_the_canvas_at_every_ui_scaling`. Scores unchanged. @@ -3181,7 +3182,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into or out of a locked layer or group, out of the blend input it is in, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place; with Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. Strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index ece5ccfe45..939bf2e2be 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -73,21 +73,35 @@ const LEVELS: [(&str, Level); 5] = /// The `unsafe_code` level that the `#![doc(test(attr(...)))]` attributes leave in force, read in /// order. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and nothing lowers a -/// `forbid`. The check does not evaluate `cfg_attr` conditions: a `deny` or `forbid` inside -/// `cfg_attr(...)` does not count, and an `allow`, `warn` or `expect` inside one lowers the level. +/// `forbid`. The check does not evaluate `cfg_attr` conditions. A `doc(...)` inside +/// `cfg_attr(...)` at any depth can only lower the level: `allow`, `warn` and `expect` of +/// `unsafe_code`, directly or inside a nested `cfg_attr(...)`, set it to `Allow`, and `deny` +/// and `forbid` do not count. The same rule applies to lint attributes inside `cfg_attr(...)` +/// within an unconditional `doc(...)`. fn doc_test_level(attrs: &[String]) -> Option { - let mut level = None; - for doc in attrs.iter().filter_map(|a| args(a, "doc")) { - for test in items(doc).into_iter().filter_map(|i| args(i, "test")) { - for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) { - for lint in items(attr) { - let direct = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l)); - let next = direct.or_else(|| sets_level(lint, &["allow", "warn", "expect"]).then_some(Level::Allow)); - if let Some(next) = next - && level != Some(Level::Forbid) - { - level = Some(next); - } + attrs.iter().fold(None, |level, a| after_doc_attr(a, level, false)) +} + +/// The level in force after `attr`, given the `level` before it: `attr` is a `doc(...)`, or a +/// `cfg_attr(...)` that may hold some. When `conditional` is true, only lint attributes that +/// lower the level count. Nothing lowers `forbid`. +fn after_doc_attr(attr: &str, level: Option, conditional: bool) -> Option { + if let Some(inner) = args(attr, "cfg_attr") { + return items(inner).into_iter().skip(1).fold(level, |l, a| after_doc_attr(a, l, true)); + } + let mut level = level; + for test in args(attr, "doc").into_iter().flat_map(items).filter_map(|i| args(i, "test")) { + for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) { + for lint in items(attr) { + let direct = LEVELS + .into_iter() + .filter(|(_, l)| !conditional || *l == Level::Allow) + .find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l)); + let next = direct.or_else(|| sets_level(lint, &["allow", "warn", "expect"]).then_some(Level::Allow)); + if let Some(next) = next + && level != Some(Level::Forbid) + { + level = Some(next); } } } @@ -357,6 +371,35 @@ mod tests { assert_eq!(problem("#![cfg_attr(forbid, deny(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); } + #[test] + fn a_doc_attribute_inside_cfg_attr_can_only_lower_the_doc_tests() { + let deny = "#![doc(test(attr(deny(unsafe_code))))]\n"; + assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(allow(unsafe_code)))))]\n")), NEEDS_DENY); + assert_eq!(problem(&format!("{deny}#![cfg_attr(test, cfg_attr(all(), doc(test(attr(warn(unsafe_code))))))]\n")), NEEDS_DENY); + assert_eq!(problem("#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))))]\n"), NEEDS_DENY); + assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))))]\n")), None); + assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(allow(unsafe_code), deny(unsafe_code)))))]\n")), NEEDS_DENY); + assert_eq!( + problem(&format!( + "{deny}#![cfg_attr(all(), doc(test(attr(allow(unsafe_code)))))]\n#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))))]\n" + )), + NEEDS_DENY + ); + assert_eq!( + problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(cfg_attr(test, expect(unsafe_code)), deny(unsafe_code)))))]\n")), + NEEDS_DENY + ); + let both = "doc(test(attr(allow(unsafe_code)))), doc(test(attr(deny(unsafe_code))))"; + assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), {both})]\n")), NEEDS_DENY); + assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))), cfg_attr(test, {both}))]\n")), NEEDS_DENY); + let allow = "doc(test(attr(allow(unsafe_code))))"; + assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))), cfg_attr(test, {allow}))]\n")), NEEDS_DENY); + let forbid = "#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"; + assert_eq!(problem(&format!("{forbid}#![cfg_attr(all(), doc(test(attr(forbid(unsafe_code)))))]\n")), NEEDS_FORBID); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![cfg_attr(all(), doc(test(attr(forbid(unsafe_code)))))]\n"), NEEDS_FORBID); + assert_eq!(problem(&format!("#![doc(test(attr(forbid(unsafe_code))))]\n#![cfg_attr(all(), {both})]\n")), None); + } + #[test] fn a_later_allow_lowers_deny_but_not_forbid() { assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]\n"), NEEDS_DENY); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 542a3e8c41..95c0b2f649 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6"; +const REV: &str = "37d0532f42eb3421769c8a454e3e25a20fbcff97"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),