diff --git a/Cargo.lock b/Cargo.lock index 74aba289b4..65c0466fa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,30 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "acadrust" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8923c99ea1f151cb7fc17ce2fc14f8b1e330fa22611e535602d985c0cc3c89a2" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "byteorder", + "encoding_rs", + "flate2", + "foldhash 0.2.0", + "indexmap", + "itoa", + "memmap2", + "nom 7.1.3", + "oem_cp", + "once_cell", + "rayon", + "ryu", + "thiserror 2.0.21", + "web-time", +] + [[package]] name = "accesskit" version = "0.25.2" @@ -1231,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", @@ -1273,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", @@ -1294,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", @@ -1306,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", ] @@ -1314,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", @@ -1339,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", @@ -1357,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", @@ -1375,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", @@ -1384,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", ] @@ -1392,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", @@ -1401,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", @@ -1426,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", @@ -1442,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", @@ -1452,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", ] @@ -1460,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", @@ -1486,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", @@ -1502,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", ] @@ -1510,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", @@ -1526,10 +1550,19 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-dwg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" +dependencies = [ + "acadrust", + "log", +] + [[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", @@ -1541,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", @@ -1551,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", @@ -1566,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", @@ -1581,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", @@ -1600,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", @@ -1609,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", @@ -1632,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", ] @@ -1645,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", ] @@ -1653,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", @@ -1666,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", @@ -1696,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", @@ -1723,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", @@ -1741,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", ] @@ -1749,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", @@ -1760,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", @@ -1775,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", @@ -1789,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", @@ -1807,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", @@ -1819,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", @@ -1830,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", @@ -1840,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", @@ -1849,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", @@ -1865,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", @@ -1874,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", @@ -1885,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", @@ -1897,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", @@ -1930,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", @@ -1939,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", @@ -1963,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", @@ -1974,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", @@ -1988,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", @@ -1999,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", @@ -2009,10 +2042,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-raster3d" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[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", @@ -2031,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", @@ -2048,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", @@ -2059,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", @@ -2080,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", @@ -2092,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", @@ -2117,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", ] @@ -2125,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", @@ -2140,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", @@ -2155,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", @@ -2165,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", @@ -2174,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", @@ -2189,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", @@ -2208,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", @@ -2225,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", @@ -2263,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", @@ -2274,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", @@ -2292,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", @@ -2313,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", @@ -2334,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", @@ -2353,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", @@ -2385,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", @@ -2396,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", @@ -2406,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", @@ -2417,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", ] @@ -2425,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", @@ -2457,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", @@ -3817,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", @@ -3826,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", @@ -3844,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", @@ -3862,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", @@ -4850,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", @@ -5007,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", @@ -5891,6 +5933,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oem_cp" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7959d3349f484aec36462f98226983578bf7d33f9b034c32967489c7000e1f" +dependencies = [ + "phf 0.11.3", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -6063,6 +6114,15 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.13.1" @@ -6130,6 +6190,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -7546,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", @@ -8645,6 +8713,7 @@ dependencies = [ name = "vectorcraft-cad" version = "0.25.1" dependencies = [ + "craft-dwg", "craft-dxf", "craft-image-codecs", "craft-plotter", @@ -8658,6 +8727,7 @@ dependencies = [ "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", "vectorcraft-text", + "web-time", ] [[package]] @@ -8665,6 +8735,7 @@ name = "vectorcraft-cli" version = "0.25.1" dependencies = [ "craft", + "craft-dwg", "log", "objc2-core-foundation", "objc2-core-text", @@ -8727,6 +8798,7 @@ name = "vectorcraft-effects" version = "0.25.1" dependencies = [ "craft-image-codecs", + "craft-raster3d", "craft-svg", "image", "kurbo 0.13.1", @@ -8754,6 +8826,7 @@ dependencies = [ "craft-codepage", "craft-doc", "craft-docpath", + "craft-dwg", "craft-font-catalog", "craft-font-store", "craft-image-codecs", @@ -9032,6 +9105,7 @@ dependencies = [ name = "vectorcraft-render" version = "0.25.1" dependencies = [ + "bytemuck", "craft-gif", "craft-image-codecs", "craft-psd", @@ -9200,6 +9274,7 @@ dependencies = [ "bytemuck", "chrono", "craft", + "craft-dwg", "craft-image-codecs", "egui", "egui_extras", diff --git a/Cargo.toml b/Cargo.toml index 7dab0c8895..03de727454 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,53 +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 = "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 = "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" } @@ -196,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/NOTICE b/NOTICE index 4d7c813796..4790c330bc 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,12 @@ based in part on the work of the Independent JPEG Group. WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is under the Apache License 2.0 with the LLVM exception. +DWG drawings are read by the acadrust crate 0.6.6 (https://crates.io/crates/acadrust/0.6.6), through +craft-dwg from https://github.com/storytold/craft-libs. acadrust is used unmodified under the Mozilla +Public License 2.0; its source is available at that address. Its license text and its third-party +notices (code adapted from ACadSharp, Copyright (c) 2021 Albert Domenech, MIT License) are in +licenses/acadrust-0.6.6/. + The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part diff --git a/README.md b/README.md index 3280824dc8..df83d9e9dd 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,8 @@ RISC-V (riscv64) packages are `vectorcraft--linux-riscv64.deb`, ### FreeBSD +Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds. + | Build | File | |---|---| | x86_64 | `vectorcraft--freebsd-x86_64.tar.gz` | diff --git a/ROADMAP.md b/ROADMAP.md index f81353a895..616e6eea9d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,7 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log -- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged. - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 9c87a0045e..fc781c31c0 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -49,6 +49,8 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" [dev-dependencies] tempfile = "3" vectorcraft-testkit = { workspace = true } +# DWG files for the `info` test, written from DXF by craft-dwg. +craft-dwg = { workspace = true } serde_json = { workspace = true } # The files of other crates that this crate compiles or its tests read, for CI's test selection. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b049ac18ca..8855d3f9e3 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -224,6 +224,12 @@ fn help() -> Result<(), String> { } fn main() -> ExitCode { + // A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits. + if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() { + std::process::exit(code); + } + // DWG drawings open through that copy, so a damaged file can't end this process. + vectorcraft_engine::dwg::use_own_worker(); // Before the first render: the cores the process may run on. #[cfg(windows)] windows_cores::install(); @@ -668,6 +674,8 @@ fn thumbnail(args: &[String]) -> Result<(), String> { } } let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?; + // A DWG worker ends by then too, so the exit below leaves no conversion running. + vectorcraft_engine::dwg::use_own_worker_for(THUMBNAIL_TIME); // The process ends when the time is up, wherever the work is: OUT is written whole or not at all. std::thread::spawn(|| { std::thread::sleep(THUMBNAIL_TIME); diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 9593d2630e..fee790b65b 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -378,3 +378,70 @@ fn convert_and_run_write_ait_templates() { assert!(!one.status.success()); assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr)); } + +/// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from +/// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on +/// aarch64. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() { + let dxf = tmp("plan.dxf"); + make(&dxf, 120, 80); + craft_dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap(); + let good = tmp("plan.dwg"); + std::fs::write(&good, &dwg).unwrap(); + // The DWG comes in as the DXF it was written from. + let (v, from) = (info(&good), info(&dxf)); + assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}"); + assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}"); + + let n = dwg.len(); + let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()]; + let mut overwritten = dwg.clone(); + overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF); + damaged.push(overwritten); + let mut flipped = dwg.clone(); + flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5); + damaged.push(flipped); + for (i, bytes) in damaged.iter().enumerate() { + let path = tmp(&format!("damaged-{i}.dwg")); + std::fs::write(&path, bytes).unwrap(); + let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap(); + // A process ended by a signal has no exit code. + assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status); + // The file cut to a third and the one cut to its header can't be read; the reader may + // recover the others. + if i == 0 || i == 2 { + assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout)); + } + if !out.status.success() { + assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr)); + } + } +} + +/// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the +/// deadline passes, even while it still waits for its drawing, and at once when it has already +/// passed, so `thumbnail`'s exit leaves no conversion running. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() { + let now = std::time::SystemTime::now(); + for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] { + let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string(); + let mut worker = Command::new(crate::bin()) + .args(["--dwg-worker", "--dwg-worker-until", &millis]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + // Its input stays open, so the worker never gets the whole request. + let input = worker.stdin.take(); + let out = worker.wait_with_output().unwrap(); + drop(input); + assert_eq!(out.status.code(), Some(1), "{:?}", out.status); + // It stops without answering, so no partial drawing reaches the caller. + assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len()); + } +} 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/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 7ffdb4b291..d772397ce3 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -598,10 +598,17 @@ fn finish_pending_update(nightly: bool) { } fn main() -> std::process::ExitCode { + // A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits, + // before the launch profile, the logger or any window. + if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() { + std::process::exit(code); + } // The launch profile first: a nightly build self-isolates or uses the Launcher's profile here, // before the update helper, the logger, fonts or any saved state, and `--version` is answered // here too. let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; + // DWG drawings open through that copy, so a damaged file can't end this process. + vectorcraft_engine::dwg::use_own_worker(); let nightly = launch_profile::current().is_nightly(); #[cfg(windows)] finish_pending_update(nightly); diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 651be6f6a3..ba5b6a3a18 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -180,7 +180,8 @@ mod system { let sockets = local_sockets(); // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, // so its sizes come from the server. - if scheduler_is_local(named.as_deref(), &sockets, real_path) { + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + if named_scheduler_is_local(named.as_deref(), port, |s| std::path::Path::new(s).exists(), &sockets, real_path) { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); @@ -199,7 +200,6 @@ mod system { return papers; } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. - let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; @@ -286,10 +286,19 @@ mod system { } } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or - /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` + /// `/etc/cups/client.conf`; `None` when none is named, where CUPS uses its domain socket when one exists and + /// `localhost` on `IPP_PORT` otherwise ([`named_scheduler_is_local`] resolves that case). macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. + /// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second + /// scheduler rather than the local one. #[cfg(not(windows))] fn cups_server() -> Option { + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + named_cups_server().map(|server| vectorcraft_ui_egui::print::server_with_ipp_port(&server, port)) + } + /// The scheduler `cups_server` names, as written. + #[cfg(not(windows))] + fn named_cups_server() -> Option { if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { return Some(server.trim().to_string()); } @@ -304,8 +313,26 @@ mod system { client_conf_server_name(&text) }) } + /// Whether the scheduler CUPS uses runs on this machine, given the server `cups_server` names, the `IPP_PORT` + /// port, whether a path exists, the local scheduler's domain `sockets` and a socket path's real path. With no + /// server named, CUPS uses its domain socket when one exists, which is local, and otherwise `localhost` on the + /// `IPP_PORT` port, which is local only on port 631. + #[cfg(not(windows))] + pub(super) fn named_scheduler_is_local( + named: Option<&str>, + port: Option, + exists: impl Fn(&str) -> bool, + sockets: &[String], + resolve: impl Fn(&str) -> Option, + ) -> bool { + match named { + Some(server) => scheduler_is_local(Some(server), sockets, resolve), + None if CUPS_SOCKETS.iter().any(|s| exists(s)) => true, + None => scheduler_is_local(Some(&vectorcraft_ui_egui::print::server_with_ipp_port("localhost", port)), sockets, resolve), + } + } /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain - /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// `sockets`, or `localhost`, `127.0.0.1` or `[::1]` with no port or port 631, each with an optional `/version=` suffix. /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. #[cfg(not(windows))] @@ -320,6 +347,10 @@ mod system { rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) } else if server.matches(':').count() == 1 { server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) + } else if let Some((host, port)) = server.rsplit_once(':').filter(|(_, port)| port.starts_with(|c: char| c.is_ascii_digit())) { + // CUPS (`cupsSetServer`) reads the digits after the last `:` of an unbracketed name as its port, so `::1` is + // host `:` on port 1. + (host, Some(port)) } else { (server, None) }; @@ -646,7 +677,21 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local}; + use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, named_scheduler_is_local, scheduler_is_local}; + + #[test] + fn with_no_server_named_the_implicit_scheduler_decides_locality() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + let real = |_: &str| None; + let own = cupsd_listen_sockets(""); + assert!(!named_scheduler_is_local(None, Some(8631), none, &own, real), "localhost:8631 is a second scheduler"); + assert!(named_scheduler_is_local(None, Some(631), none, &own, real)); + assert!(named_scheduler_is_local(None, None, none, &own, real)); + assert!(named_scheduler_is_local(None, Some(8631), socket, &own, real), "CUPS's socket is the local scheduler"); + assert!(!named_scheduler_is_local(Some("print.example.com"), None, socket, &own, real)); + assert!(named_scheduler_is_local(Some("localhost:631"), Some(8631), none, &own, real)); + } #[test] fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { @@ -700,7 +745,6 @@ mod client_conf_tests { Some("LocalHost:631"), Some("localhost:631"), Some("127.0.0.1:631"), - Some("::1"), Some("[::1]:631"), Some("[::1]"), Some("localhost/version=1.1"), @@ -714,6 +758,7 @@ mod client_conf_tests { "192.0.2.7", "[2001:db8::1]:631", "2001:db8::1", + "::1", "localhost.example.com", "print.example.com:631/version=1.1", "localhost:8631", @@ -727,6 +772,23 @@ mod client_conf_tests { } } + #[test] + fn a_loopback_server_on_another_ipp_port_is_not_local() { + use vectorcraft_ui_egui::print::server_with_ipp_port; + let own = cupsd_listen_sockets(""); + let real = |_: &str| None; + for named in ["localhost", "127.0.0.1", "[::1]", "localhost/version=1.1"] { + assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631))), &own, real), "{named}"); + assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631))), &own, real), "{named}"); + } + // CUPS reads an unbracketed `::1` as host `:` on port 1, so it is not the local scheduler on any `IPP_PORT`. + for port in [None, Some(631), Some(8631)] { + assert!(!scheduler_is_local(Some(&server_with_ipp_port("::1", port)), &own, real), "::1 with {port:?}"); + } + assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631))), &own, real), "a port in the server name wins"); + assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))), &own, real)); + } + #[test] fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com")); diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 1cbf8dc431..c09eb31879 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,13 +3,14 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer" +description = "VectorCraft CAD interchange: DXF export through craft-dxf, DXF and DWG import, and an HP-GL/2 plot file reader and writer" [lints] workspace = true [dependencies] craft-dxf = { workspace = true } +craft-dwg = { workspace = true } craft-plotter = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } @@ -21,6 +22,7 @@ vectorcraft-text = { workspace = true } kurbo = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } +web-time = "1" [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs new file mode 100644 index 0000000000..b6e4b545c4 --- /dev/null +++ b/crates/cad/src/dwg.rs @@ -0,0 +1,278 @@ +//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result. +//! +//! The conversion runs in a child process once the program has called [`use_own_worker`] (and +//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort +//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless +//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there. + +use std::hash::BuildHasher; +use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; +use std::time::Duration; + +use web_time::Instant; + +pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; + +/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch +/// ([`use_own_worker_for`]). +const WORKER_UNTIL_ARG: &str = "--dwg-worker-until"; + +/// Serve one conversion and return the exit code if this process was started as a worker. A +/// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the +/// conversion is. +pub fn serve_if_asked() -> Option { + let mut args = std::env::args_os().skip(1); + if args.next()? != WORKER_ARG { + return None; + } + if args.next().is_some_and(|a| a == WORKER_UNTIL_ARG) + && let Some(millis) = args.next().and_then(|s| s.to_str()?.parse::().ok()) + && let Some(until) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis)) + { + if until <= std::time::SystemTime::now() { + return Some(1); + } + std::thread::spawn(move || { + std::thread::sleep(until.duration_since(std::time::SystemTime::now()).unwrap_or_default()); + std::process::exit(1); + }); + } + craft_dwg::serve_if_asked() +} + +/// [`use_own_worker`], each worker exiting once `limit` from this call is up (a deadline passed to it +/// in milliseconds since the UNIX epoch), however late it starts, so a program that ends after +/// `limit` leaves no conversion running. If this program's path can't be found, or the deadline +/// can't be written, the worker setting does not change. Web builds have no worker. +pub fn use_own_worker_for(limit: std::time::Duration) { + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + if let Ok(program) = std::env::current_exe() + && let Some(until) = std::time::SystemTime::now().checked_add(limit).and_then(|until| until.duration_since(std::time::UNIX_EPOCH).ok()) + && let Ok(millis) = u64::try_from(until.as_millis()) + { + craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_UNTIL_ARG.into(), millis.to_string().into()]); + } + #[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))] + let _ = limit; +} + +/// The largest DXF rendition kept for the next read of the same drawing (128 MiB). +const MAX_KEPT: usize = 128 << 20; + +/// Is `bytes` a DWG drawing (an `AC10nn` version code first)? +pub fn is_dwg(bytes: &[u8]) -> bool { + craft_dwg::is_dwg(bytes) +} + +/// A DWG drawing as DXF bytes, and what the conversion left out. +#[derive(Debug, PartialEq)] +pub(crate) struct Converted { + pub dxf: Vec, + pub notes: Vec, +} + +type Outcome = Result, String>; + +/// The outcome of the last drawing converted, by a hash of its bytes and its length, and the +/// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its +/// dialog and then opens it, and each of those reads the same file; a file the conversion refused +/// (or whose worker stopped) is refused again without another conversion for [`FAILURE_KEPT`], +/// after which the next read converts it again. +#[derive(Default)] +struct Kept { + hasher: std::collections::hash_map::RandomState, + /// The last outcome, by key, and when it was kept. + last: Option<((u64, usize), Outcome, Instant)>, + /// The conversions handed out by [`hold`], while a [`Held`] for each exists. + held: Vec<((u64, usize), Weak)>, +} + +impl Kept { + fn key(&self, bytes: &[u8]) -> (u64, usize) { + (self.hasher.hash_one(bytes), bytes.len()) + } + + fn get(&self, key: (u64, usize), now: Instant) -> Option { + let fresh = |outcome: &Outcome, at: &Instant| outcome.is_ok() || now.saturating_duration_since(*at) < FAILURE_KEPT; + if let Some((_, outcome, _)) = self.last.as_ref().filter(|(k, outcome, at)| *k == key && fresh(outcome, at)) { + return Some(outcome.clone()); + } + self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok) + } + + fn hold(&mut self, key: (u64, usize), converted: &Arc) { + self.held.retain(|(_, c)| c.strong_count() > 0); + self.held.push((key, Arc::downgrade(converted))); + } + + fn keep(&mut self, key: (u64, usize), outcome: &Outcome, now: Instant) { + if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) { + self.last = None; + } else { + self.last = Some((key, outcome.clone(), now)); + } + } +} + +/// How long a failed conversion is returned again for the same bytes. A worker can fail for a +/// passing cause (memory, its deadline, a failed start), so a later read converts the drawing again. +const FAILURE_KEPT: Duration = Duration::from_secs(10); + +/// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The +/// lock is not held while `convert` runs, so another drawing can be converted at the same time. +fn through(kept: &Mutex, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result) -> Outcome { + through_at(kept, bytes, &Instant::now, convert) +} + +/// [`through`] with the time read from `now`; an outcome is kept from when `convert` returned. +fn through_at(kept: &Mutex, bytes: &[u8], now: &dyn Fn() -> Instant, convert: impl FnOnce(&[u8]) -> Result) -> Outcome { + let key = { + let kept = kept.lock().unwrap_or_else(PoisonError::into_inner); + let key = kept.key(bytes); + if let Some(outcome) = kept.get(key, now()) { + return outcome; + } + key + }; + let outcome = convert(bytes).map(Arc::new); + kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome, now()); + outcome +} + +/// [`through`], and the conversion stays where `kept` finds it while the [`Held`] lasts. +fn hold_in(kept: &Mutex, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result) -> Result { + let converted = through(kept, bytes, convert)?; + let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner); + let key = kept.key(bytes); + kept.hold(key, &converted); + Ok(Held { _converted: converted }) +} + +static KEPT: LazyLock> = LazyLock::new(Mutex::default); + +/// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF). +pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome { + through(&KEPT, bytes, convert) +} + +/// A DWG drawing's conversion, kept for every read of the same bytes ([`crate::info`], +/// [`crate::import`]) while this value exists, whatever other drawings are converted meanwhile and +/// however large its DXF is. +#[derive(Debug, Clone)] +pub struct Held { + _converted: Arc, +} + +/// Convert `bytes` (a DWG drawing), or take the conversion already kept, and keep it while the +/// returned [`Held`] exists → the conversion's error when it fails. +pub fn hold(bytes: &[u8]) -> Result { + hold_in(&KEPT, bytes, convert) +} + +fn convert(bytes: &[u8]) -> Result { + let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?; + Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) +} + +/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one. +fn worded(message: &str) -> String { + message + .replace("accepted by this bridge", "VectorCraft opens") + .replace("types this bridge can't preserve", "types VectorCraft can't read") + .replace("; saving over the original file would lose them", "") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn counting<'a>(calls: &'a std::cell::Cell, dxf: &'a [u8]) -> impl FnOnce(&[u8]) -> Result + 'a { + move |_| { + calls.set(calls.get() + 1); + Ok(Converted { dxf: dxf.to_vec(), notes: vec![] }) + } + } + + #[test] + fn the_same_drawing_is_converted_once_and_another_drawing_again() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let a = through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + let again = through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap(); + assert_eq!(calls.get(), 1); + assert_eq!(again.dxf, a.dxf); + through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 2); + // The first drawing is no longer held. + through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 3); + } + + #[test] + fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let start = Instant::now(); + let at_start = move || start; + assert_eq!(through_at(&kept, b"AC1015 bad", &at_start, |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no"); + let again = through_at(&kept, b"AC1015 bad", &at_start, counting(&calls, b"0\nEOF\n")); + assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0)); + let big = vec![b' '; MAX_KEPT + 1]; + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again"); + } + + #[test] + fn a_failed_conversion_is_tried_again_once_its_time_is_up() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let clock = std::cell::Cell::new(Instant::now()); + let now = || clock.get(); + // The worker fails after running for longer than FAILURE_KEPT: the failure is kept from then. + let slow_failure = |_: &[u8]| { + clock.set(clock.get() + FAILURE_KEPT * 2); + Err("DWG: stopped".to_string()) + }; + assert!(through_at(&kept, b"AC1015 bad", &now, slow_failure).is_err()); + clock.set(clock.get() + FAILURE_KEPT / 2); + let within = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n")); + assert_eq!((within.unwrap_err().as_str(), calls.get()), ("DWG: stopped", 0)); + clock.set(clock.get() + FAILURE_KEPT / 2); + let later = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n")); + assert_eq!((later.unwrap().dxf.as_slice(), calls.get()), (b"0\nEOF\n".as_slice(), 1)); + // A conversion that worked is kept whatever the time. + clock.set(clock.get() + FAILURE_KEPT * 100); + through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"other")).unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let big = vec![b' '; MAX_KEPT + 1]; + let one = hold_in(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + let large = hold_in(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 3); + // Another drawing converted since, and a rendition over MAX_KEPT, are still found. + through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap(); + assert_eq!(through(&kept, b"AC1015 big", counting(&calls, b"other")).unwrap().dxf.len(), big.len()); + assert_eq!(calls.get(), 3); + drop((one, large)); + through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + assert_eq!(calls.get(), 5, "a dropped hold no longer keeps its conversion"); + let refused = hold_in(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string())); + assert_eq!(refused.unwrap_err(), "DWG: no"); + } + + #[test] + fn messages_name_what_vectorcraft_does() { + let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge"); + assert_eq!(m, "DWG: the file is 9.9 MB, larger than the 1.0 MB VectorCraft opens"); + let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them"); + assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)"); + } +} diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 9216c57c29..5a5582efe1 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -1,4 +1,5 @@ -//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. +//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. A DWG drawing comes +//! in the same way, converted to DXF first ([`crate::dwg`]). //! //! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N //! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred @@ -102,11 +103,24 @@ pub fn is_dxf(bytes: &[u8]) -> bool { false } -/// The tags of a DXF file and where it is damaged (DWG files are refused). -fn tags(bytes: &[u8]) -> Result<(Vec, Option), String> { - if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") { - return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into()); +/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read +/// left out: where the file is damaged, and what the DWG conversion couldn't read. +fn tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { + if crate::dwg::is_dwg(bytes) { + let converted = crate::dwg::to_dxf(bytes)?; + let (tags, mut notes) = dxf_tags(&converted.dxf)?; + notes.extend(converted.notes.iter().cloned()); + return Ok((tags, notes)); } + // R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number. + if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) { + return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into()); + } + dxf_tags(bytes) +} + +/// The tags of a DXF file and where it is damaged. +fn dxf_tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e { craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(), _ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(), @@ -115,7 +129,7 @@ fn tags(bytes: &[u8]) -> Result<(Vec, Option), String> { if tags.is_empty() { return Err("not a DXF drawing".into()); } - Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")))) + Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")).into_iter().collect())) } /// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it. @@ -182,7 +196,7 @@ pub fn info(bytes: &[u8]) -> Result { }) } -/// Import a DXF drawing with `o`. +/// Import a DXF or DWG drawing with `o`. pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { let (w, h) = o.fit_to; if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) { @@ -193,7 +207,7 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { { return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end())); } - let (tags, damaged) = tags(bytes)?; + let (tags, notes) = tags(bytes)?; let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags)); if d.sections == 0 { return Err("not a DXF drawing".into()); @@ -214,10 +228,12 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { }; let (mut document, mut warnings) = build::Build::new(&d, o).run(layout, natural, ratio)?; document.units = if o.fit { unit } else { o.unit.unwrap_or(unit) }; - warnings.extend(damaged); + warnings.extend(notes); document.limit_depth_noting(&mut warnings); Ok(Imported { document, warnings }) } #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_dwg; diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 309a4ea228..9d147b08cf 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -178,7 +178,7 @@ pub(crate) struct Converter { const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour"; -const MESHES: &str = "3D polygon meshes and polyface meshes are left out"; +const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out"; const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; @@ -233,14 +233,20 @@ impl Converter { path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?) } model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs), - model::EntityKind::Polyline(p) => self.polyline(p, ocs), + model::EntityKind::Polyline(p) => self.polyline(p, &g, ocs), model::EntityKind::Spline(s) => path(spline(s)?), model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => { let [a, b, c, d] = corners.map(point); // The corners zigzag: the outline runs 1, 2, 4, 3. Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 }) } - model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))), + model::EntityKind::Face3d { corners, hidden_edges } => { + // Bit n of group 70 hides the edge from corner n. + let corners: Vec<(Point, bool)> = corners.iter().enumerate().map(|(i, c)| (point(*c), hidden_edges & (1 << i) == 0)).collect(); + let mut bp = BezPath::new(); + face(&mut bp, &corners); + (!bp.elements().is_empty()).then_some(bp).and_then(path) + } model::EntityKind::Hatch(h) => self.hatch(h, ocs), model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text), model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text), @@ -253,10 +259,11 @@ impl Converter { } } - fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option { - if p.is_mesh() || p.is_polyface() { - self.warn(MESHES); - return None; + fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option { + // Meshes are in world coordinates, seen from above. + if p.is_polyface() || p.is_mesh() { + let bp = if p.is_polyface() { self.polyface(p) } else { self.mesh(p, g) }?; + return Some(Geom::Path { bp, fill: false, width: 0.0 }); } // Spline frame control points and polyface faces aren't on the line. let verts: Vec = @@ -267,6 +274,60 @@ impl Converter { Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) }) } + /// A polyface mesh's faces: each one's visible edges, closed when all of them are. + fn polyface(&mut self, p: &model::Polyline) -> Option { + let points: Vec = p.vertices.iter().filter(|v| !v.is_face()).map(|v| point(v.location)).collect(); + let mut bp = BezPath::new(); + for f in p.vertices.iter().filter(|v| v.is_face()) { + // Vertex numbers count from 1, negative when the edge from that vertex is hidden; + // 0 ends a triangle's list. + let corners: Option> = f + .face + .iter() + .take_while(|n| **n != 0) + .map(|n| { + let i = usize::try_from(n.unsigned_abs()).ok()?.checked_sub(1)?; + Some((*points.get(i)?, *n > 0)) + }) + .collect(); + match corners { + Some(corners) => face(&mut bp, &corners), + None => self.warn(MESH_VERTICES), + } + } + (!bp.elements().is_empty()).then_some(bp) + } + + /// A polygon mesh as its M lines and N lines. Its vertices go row by row (N to a row); a + /// smoothed mesh holds its surface's vertices (groups 73 and 74 count them) after the frame. + fn mesh(&mut self, p: &model::Polyline, g: &Groups<'_>) -> Option { + let points: Vec = p.vertices.iter().filter(|v| !v.is_spline_frame()).map(|v| point(v.location)).collect(); + let size = |m: i64, n: i64| { + let (m, n) = (usize::try_from(m).ok()?, usize::try_from(n).ok()?); + (m > 0 && n > 0 && m.checked_mul(n) == Some(points.len())).then_some((m, n)) + }; + let (frame, surface) = ((p.m, p.n), (g.i_or(73, 0), g.i_or(74, 0))); + // Without the frame's vertices only the surface's counts describe the grid. + let dims = if p.vertices.iter().any(model::Vertex::is_spline_frame) { + size(surface.0, surface.1) + } else { + size(frame.0, frame.1).or_else(|| size(surface.0, surface.1)) + }; + let Some((m, n)) = dims else { + self.warn(MESH_VERTICES); + return None; + }; + let mut bp = BezPath::new(); + for row in points.chunks(n) { + line(&mut bp, row, p.flags & 32 != 0); + } + for col in 0..n { + let pts: Vec = (0..m).map(|r| points[r * n + col]).collect(); + line(&mut bp, &pts, p.closed()); + } + (!bp.elements().is_empty()).then_some(bp) + } + fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option { let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase(); let [sx, sy, _] = ins.scale; @@ -398,6 +459,46 @@ fn polygon(pts: &[Point]) -> BezPath { bp } +/// Adds the line through `pts` to `bp`, closed if `closed` (nothing for fewer than two points). +fn line(bp: &mut BezPath, pts: &[Point], closed: bool) { + if pts.len() < 2 { + return; + } + for (i, p) in pts.iter().enumerate() { + if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } + } + if closed { + bp.close_path(); + } +} + +/// Adds a face's outline to `bp`: its corners with whether the edge from each to the next is +/// visible. All visible, the outline is closed; otherwise each run of visible edges is an open +/// line. +fn face(bp: &mut BezPath, corners: &[(Point, bool)]) { + let pts: Vec = corners.iter().map(|c| c.0).collect(); + let Some(hidden) = corners.iter().position(|c| !c.1) else { + line(bp, &pts, true); + return; + }; + // Start after a hidden edge, so that no run is split where the list wraps. + let n = corners.len(); + let mut run: Vec = Vec::new(); + for k in 1..=n { + let i = (hidden + k) % n; + if corners[i].1 { + if run.is_empty() { + run.push(pts[i]); + } + run.push(pts[(i + 1) % n]); + } else { + line(bp, &run, false); + run.clear(); + } + } + line(bp, &run, false); +} + fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 5faad39835..d53694343a 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -248,6 +248,125 @@ fn polyline_bulges_are_exact_arcs() { assert!((b.y1 - height(&doc)).abs() < 1e-4, "the arc's chord is at y 0: {b:?}"); } +/// The straight segments of the paths of the one object a drawing brings in, in drawing +/// coordinates (y up), each with its ends in order, sorted. +fn drawn_edges(r: &Imported) -> Vec<[(i64, i64); 2]> { + let doc = &r.document; + assert_eq!(doc.layers[0].children().map_or(0, Vec::len), 1, "one object: {:?}", r.warnings); + let h = height(doc); + let at = |p: Point| (p.x.round() as i64, (h - p.y).round() as i64); + let mut edges = vec![]; + for n in leaves(doc) { + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {:?}", n.kind) }; + for s in path.to_bezpath().segments() { + let kurbo::PathSeg::Line(l) = s else { panic!("not a line: {s:?}") }; + edges.push([at(l.p0), at(l.p1)]); + } + } + sorted(edges) +} + +/// Edges with their ends in order, sorted. +fn sorted(mut e: Vec<[(i64, i64); 2]>) -> Vec<[(i64, i64); 2]> { + for x in &mut e { + x.sort_unstable(); + } + e.sort_unstable(); + e +} + +fn vertex(flags: &'static str, x: &'static str, y: &'static str, z: &'static str) -> [(i32, &'static str); 5] { + [(0, "VERTEX"), (70, flags), (10, x), (20, y), (30, z)] +} + +#[test] +fn polyface_meshes_draw_their_faces_visible_edges_from_above() { + // A square at two heights as two triangles sharing a hidden diagonal, and a face naming a + // vertex the mesh doesn't have. + let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "64"), (71, "4"), (72, "3")]; + for (x, y, z) in [("0", "0", "5"), ("10", "0", "5"), ("10", "10", "0"), ("0", "10", "0")] { + e.extend(vertex("192", x, y, z)); + } + for f in [["1", "2", "-3"], ["3", "4", "-1"], ["1", "2", "9"]] { + e.extend(vertex("128", "0", "0", "0")); + e.extend([(71, f[0]), (72, f[1]), (73, f[2])]); + } + e.push((0, "SEQEND")); + let r = open(&entities(&e), &points()); + let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]); + assert_eq!(drawn_edges(&r), square, "the outline without the diagonal"); + assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings); + // With every edge visible, each face is a closed outline. + let e: Vec<(i32, &str)> = e.iter().map(|&(c, v)| (c, v.trim_start_matches('-'))).collect(); + let r = open(&entities(&e), &points()); + let diagonal = drawn_edges(&r).iter().filter(|e| **e == [(0, 0), (10, 10)]).count(); + assert_eq!(diagonal, 2, "the diagonal, once per face"); + let faces = leaves(&r.document); + assert_eq!(faces.len(), 2); + assert!(faces.iter().all(|f| f.path_data().is_some_and(|p| p.subpaths.iter().all(|s| s.closed)))); +} + +#[test] +fn polygon_meshes_draw_their_m_and_n_lines_from_above() { + // Rows of 3 vertices: N runs along x, M along y. + let grid = |flags: &'static str, m: &'static str, n: &'static str, rows: &[&'static str]| { + let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, flags), (71, m), (72, n)]; + for y in rows { + for x in ["0", "10", "20"] { + e.extend(vertex("64", x, y, "7")); + } + } + e.push((0, "SEQEND")); + e + }; + let edges = |e: &[(i32, &str)]| drawn_edges(&open(&entities(e), &points())); + let rows = vec![[(0, 0), (10, 0)], [(10, 0), (20, 0)], [(0, 10), (10, 10)], [(10, 10), (20, 10)]]; + let cols = vec![[(0, 0), (0, 10)], [(10, 0), (10, 10)], [(20, 0), (20, 10)]]; + let open_grid = sorted([rows.clone(), cols.clone()].concat()); + assert_eq!(edges(&grid("16", "2", "3", &["0", "10"])), open_grid); + // Closed in N (32): each row joins its last vertex to its first. + let wrap = vec![[(20, 0), (0, 0)], [(20, 10), (0, 10)]]; + assert_eq!(edges(&grid("48", "2", "3", &["0", "10"])), sorted([rows, cols, wrap].concat())); + // Closed in M (1): each column joins its last vertex to its first. + let tall = edges(&grid("17", "3", "3", &["0", "10", "20"])); + for e in [[(0, 0), (0, 20)], [(10, 0), (10, 20)], [(20, 0), (20, 20)]] { + assert_eq!(tall.iter().filter(|x| **x == e).count(), 1, "{e:?} in {tall:?}"); + } + // A smoothed mesh draws its surface (73 by 74 vertices), not the frame before it, even when + // the frame (3 by 2) has as many vertices. + let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "20"), (71, "3"), (72, "2"), (73, "2"), (74, "3"), (75, "6")]; + for (x, y) in [("-50", "-50"), ("50", "-50"), ("-50", "0"), ("50", "0"), ("-50", "50"), ("50", "50")] { + e.extend(vertex("80", x, y, "0")); + } + e.extend_from_slice(&grid("16", "2", "3", &["0", "10"])[5..]); + assert_eq!(edges(&e), open_grid); + // When the surface counts (2 by 4) don't fit, the frame's (3 by 2) don't describe the surface + // vertices either: the mesh is left out with a warning. + let i = e.iter().position(|t| *t == (74, "3")).unwrap_or_else(|| panic!("no group 74 in {e:?}")); + e[i] = (74, "4"); + let r = open(&entities(&e), &points()); + assert!(leaves(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings); + // Vertices that don't fill the grid: the mesh is left out with a warning. + let r = open(&entities(&grid("16", "2", "4", &["0", "10"])), &points()); + assert!(leaves(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings); +} + +#[test] +fn three_d_faces_leave_out_their_hidden_edges() { + let edges = |hidden: &'static str| { + let mut e: Vec<(i32, &str)> = vec![(0, "3DFACE"), (70, hidden)]; + e.extend([(10, "0"), (20, "0"), (11, "10"), (21, "0"), (12, "10"), (22, "10"), (13, "0"), (23, "10")]); + drawn_edges(&open(&entities(&e), &points())) + }; + let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]); + assert_eq!(edges("0"), square); + // Bit 0 hides the edge from the first corner, bit 2 the one from the third. + assert_eq!(edges("1"), sorted(vec![[(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]])); + assert_eq!(edges("5"), sorted(vec![[(10, 0), (10, 10)], [(0, 10), (0, 0)]])); +} + #[test] fn nurbs_splines_stay_within_a_hundredth() { // A rational quadratic circle of radius 100: nine weighted control points. diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs new file mode 100644 index 0000000000..00ff6aa7da --- /dev/null +++ b/crates/cad/src/import/tests_dwg.rs @@ -0,0 +1,85 @@ +//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF +//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD +//! on aarch64. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, Unit}; +use vectorcraft_geom::{Rect, shapes}; + +use super::*; +use crate::{DxfOptions, DxfVersion}; + +/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse. +fn dxf() -> Vec { + let mut d = Document::new(200.0, 100.0); + let layer = d.add_layer(Some("Walls")); + let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0); + let rect = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), stroke(Color::rgb(1.0, 0.0, 0.0))); + let oval = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), stroke(Color::rgb(0.0, 0.0, 1.0))); + for n in [rect, oval] { + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; + crate::export(&d, &o).unwrap().bytes +} + +fn dwg() -> Vec { + crate::dwg::allow_in_process(); + craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap() +} + +/// A layer's name, and each of its objects' bounds (to 0.01 pt) and stroke color. +type LayerArt = (Option, Vec<([i64; 4], Option<[u8; 4]>)>); + +/// Each layer holding art. +fn art(doc: &Document) -> Vec { + let r = |v: f64| (v * 100.0).round() as i64; + doc.layers + .iter() + .filter_map(|layer| { + let objects: Vec<_> = layer + .children()? + .iter() + .map(|n| { + let b = n.geometric_bounds().unwrap(); + let stroke = match n.appearance.stroke().map(|s| &s.paint) { + Some(Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ => None, + }; + ([r(b.x0), r(b.y0), r(b.x1), r(b.y1)], stroke) + }) + .collect(); + (!objects.is_empty()).then(|| (layer.name.clone(), objects)) + }) + .collect() +} + +#[test] +fn a_dwg_drawing_comes_in_as_its_dxf_does() { + let (dxf, dwg) = (dxf(), dwg()); + assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf)); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let want = art(&import(&dxf, &o).unwrap().document); + assert_eq!(want.len(), 1, "{want:?}"); + assert_eq!(want[0].0.as_deref(), Some("Walls")); + assert_eq!(want[0].1.len(), 2, "{want:?}"); + assert_eq!(art(&import(&dwg, &o).unwrap().document), want); + let i = info(&dwg).unwrap(); + assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model"))); + assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}"); +} + +#[test] +fn a_damaged_dwg_is_an_error_that_names_dwg() { + let mut cut = dwg(); + cut.truncate(cut.len() / 3); + let e = import(&cut, &ImportOptions::default()).unwrap_err(); + assert!(e.contains("DWG"), "{e}"); + assert!(info(&cut).is_err()); + // An R1.x or R2.x drawing is refused without reading it. + for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] { + let e = import(old, &ImportOptions::default()).unwrap_err(); + assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}"); + } +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 5f2d41d538..73e30bd2a9 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -14,16 +14,19 @@ //! clipping) is approximated or left out, and each such loss comes back as a warning. //! //! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`]. +//! It reads a DWG drawing too, converted to DXF by [`dwg`]. //! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. //! - The ASCII file around those entities is written by `craft_dxf::drawing`. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. +//! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. #![doc(test(attr(deny(unsafe_code))))] mod aci; +pub mod dwg; #[cfg(test)] mod expansion_test; pub mod hpgl; @@ -34,6 +37,7 @@ use vectorcraft_doc::{Document, Unit}; use vectorcraft_geom::Rect; pub use aci::{aci_rgb, nearest_aci}; +pub use dwg::is_dwg; pub use import::{DxfInfo, ImportOptions, Imported, import, info, is_dxf}; /// How deep symbols, blocks and brush art may nest in one another (deeper art is left out). diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index e7f50fa8ee..ba12eafabb 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -36,14 +36,14 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { let was_relative = live.radii_relative(); let base = match live { LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)), - LiveShape::Polygon { .. } => live.polygon_outline(), + LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(), LiveShape::Path { base, .. } => base.clone(), LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; let corners = path_corners(&base); let radii: &mut [f64] = match live { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii, LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; @@ -62,6 +62,7 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { match live { LiveShape::Rectangle { radii_relative: rel, .. } | LiveShape::Polygon { radii_relative: rel, .. } + | LiveShape::Star { radii_relative: rel, .. } | LiveShape::Path { radii_relative: rel, .. } => { *rel = relative; } @@ -99,7 +100,7 @@ impl<'a> LiveCorners<'a> { let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None }; (Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative) } - Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => { + Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => { (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative) } Some(LiveShape::Path { base, radii, kinds, radii_relative }) => { @@ -258,6 +259,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne edit(&outline, relative, radii, kinds, corners, radius, kind); trim_vec_radii(radii, kinds); } + LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => { + let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf); + let n = 2 * *points as usize; + radii.resize(n, 0.0); + kinds.resize(n, CornerKind::Round); + edit(&outline, relative, radii, kinds, corners, radius, kind); + trim_vec_radii(radii, kinds); + } LiveShape::Path { base, radii, kinds, .. } => { let n = base.anchor_count(); radii.resize(n, 0.0); 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/document_ext.rs b/crates/doc/src/document_ext.rs index c29e8464ea..fe2ffc0fd1 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -239,6 +239,52 @@ impl Document { round_json_paths(brushes, &round); } } + + /// Make every live star a plain path of the outline it draws, for a save that versions before + /// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the + /// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and + /// in the brush definitions. + pub fn live_stars_to_paths(&mut self) { + let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. })); + let mut plain = |n: &mut Node| { + if let NodeKind::Path { live, .. } = &mut n.kind + && matches!(live.as_deref(), Some(LiveShape::Star { .. })) + { + *live = None; + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + edit_branches_where(root, &is_star, &mut plain); + } + if let Some(brushes) = self.unknown.get_mut("brushes") { + json_stars_to_paths(brushes); + } + } +} + +/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a +/// star. +fn json_stars_to_paths(v: &mut serde_json::Value) { + use serde_json::Value; + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_str) == Some("path") + && o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") + { + o.remove("live"); + } + o.values_mut().for_each(json_stars_to_paths); + } + Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths), + _ => {} + } } /// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds, 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/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 0a17301331..33b3f10868 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -46,11 +46,32 @@ pub enum LiveShape { #[serde(default, skip_serializing_if = "is_false")] radii_relative: bool, }, + /// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable. + Star { + /// Outer radius: centre to each tip. + r1: f64, + /// Inner radius: centre to each point between two tips. + r2: f64, + /// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read. + #[serde(deserialize_with = "de_points")] + points: u32, + /// Maps the star (centred on the origin, first tip straight up) into the document. + xf: Affine, + /// Corner radii in document units, by vertex from the first tip clockwise, tips and inner + /// points alternating (none: sharp). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + radii: Vec, + /// Corner kinds, in the same order (none: round). + #[serde(default, skip_serializing_if = "all_round")] + kinds: Vec, + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + }, Line { a: Point, b: Point, }, - /// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut + /// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut /// outline so the corners stay editable. Without a cut corner it is a plain path again. Path { /// The path with its corners uncut, in the document. @@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool { impl LiveShape { pub fn radii_relative(&self) -> bool { match self { - LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => { - *radii_relative - } + LiveShape::Rectangle { radii_relative, .. } + | LiveShape::Polygon { radii_relative, .. } + | LiveShape::Star { radii_relative, .. } + | LiveShape::Path { radii_relative, .. } => *radii_relative, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false, } } @@ -86,6 +108,7 @@ impl LiveShape { LiveShape::Rectangle { .. } => "Rectangle", LiveShape::Ellipse { .. } => "Ellipse", LiveShape::Polygon { .. } => "Polygon", + LiveShape::Star { .. } => "Star", LiveShape::Line { .. } => "Line", LiveShape::Path { .. } => "Path", } @@ -100,7 +123,7 @@ impl LiveShape { shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf) } LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf), - LiveShape::Polygon { radii, kinds, radii_relative, .. } => { + LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => { let outline = self.polygon_outline(); let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative); cut_corners(&outline, &radii, kinds).0 @@ -112,10 +135,12 @@ impl LiveShape { } } } - /// A polygon's outline with its corners uncut, in the document (empty for other shapes). + /// A polygon's or star's outline with its corners uncut, in the document (empty for other + /// shapes). pub fn polygon_outline(&self) -> PathData { match self { LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf), + LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf), _ => PathData::default(), } } @@ -123,16 +148,38 @@ impl LiveShape { /// the corners past the old last one are sharp. pub fn set_sides(&mut self, n: u64) { let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; + let old = *sides as usize; *sides = n.clamp(3, 1000) as u32; - fn spread(v: &mut Vec, n: usize) { - match v.first().copied() { - Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], - Some(_) => v.resize(n, T::default()), - None => {} - } + spread(radii, old, *sides as usize); + spread(kinds, old, *sides as usize); + } + /// A star's point count. None for other shapes. + pub fn star_points(&self) -> Option { + let LiveShape::Star { points, .. } = self else { return None }; + Some(*points) + } + /// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the + /// corners past the old last one are sharp. + pub fn set_points(&mut self, n: u64) { + let LiveShape::Star { points, radii, kinds, .. } = self else { return }; + let old = 2 * *points as usize; + *points = n.clamp(2, 1000) as u32; + spread(radii, old, 2 * *points as usize); + spread(kinds, old, 2 * *points as usize); + } + /// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None + /// for other shapes. + pub fn star_ratio(&self) -> Option { + let LiveShape::Star { r1, r2, .. } = self else { return None }; + Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 }) + } + /// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer + /// radius. Nothing changes for other shapes or a ratio outside 0 to 1. + pub fn set_star_ratio(&mut self, ratio: f64) { + let LiveShape::Star { r1, r2, .. } = self else { return }; + if ratio.is_finite() && (0.0..=1.0).contains(&ratio) { + *r2 = *r1 * ratio; } - spread(radii, *sides as usize); - spread(kinds, *sides as usize); } /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of /// `xf` (exact while its sides are equal). None for other shapes. @@ -151,7 +198,9 @@ impl LiveShape { /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for /// other shapes. pub fn shape_angle(&self) -> Option { - let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None }; + let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else { + return None; + }; // No −0° or 360° from rounding: a shape drawn level reads 0°. let a = (-self.angle_deg()).rem_euclid(360.0); Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) @@ -168,7 +217,7 @@ impl LiveShape { let angle = angle.rem_euclid(360.0); let (xf, local) = match self { LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), - LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), + LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO), LiveShape::Line { .. } | LiveShape::Path { .. } => return, }; let center = *xf * local; @@ -274,7 +323,7 @@ impl LiveShape { *xf = a * *xf; false } - LiveShape::Polygon { xf, radii, radii_relative, .. } => { + LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => { *xf = a * *xf; scale_radii(radii, a, *radii_relative) } @@ -326,7 +375,7 @@ impl LiveShape { let relative = self.radii_relative(); let radii: &mut [f64] = match self { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false, }; if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 { @@ -338,7 +387,7 @@ impl LiveShape { /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). pub fn angle_deg(&self) -> f64 { match self { - LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { + LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => { let c = xf.as_coeffs(); c[1].atan2(c[0]).to_degrees() } @@ -358,6 +407,28 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { u32::deserialize(d).map(|n| n.clamp(3, 1000)) } +/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]). +fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + +/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it; +/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list +/// shorter than `old` holds the default for its missing corners, so it is shared only when that +/// default is; entries of a longer list past `old` name no corner and go first. An empty list +/// stays empty. +fn spread(v: &mut Vec, old: usize, n: usize) { + v.truncate(old); + if !v.is_empty() && v.len() < old { + v.resize(old, T::default()); + } + match v.first().copied() { + Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], + Some(_) => v.resize(n, T::default()), + None => {} + } +} + /// Whether `a` only moves (no rotation, scale, shear or reflection). pub(super) fn moves_only(a: Affine) -> bool { let [a0, a1, a2, a3, _, _] = a.as_coeffs(); diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 480e201e2d..2ecdda06bd 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -158,6 +158,77 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() { assert_eq!(huge.polygon_outline().anchor_count(), 1000); } +/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points. +#[test] +fn a_star_round_trips_and_its_file_count_is_clamped() { + let star = LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 7, + xf: Affine::translate((10.0, 20.0)), + radii: vec![2.0; 14], + kinds: vec![], + radii_relative: false, + }; + let text = serde_json::to_string(&star).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), star); + assert_eq!(star.label(), "Star"); + let read = |points: u64| { + let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]}); + serde_json::from_value::(json).unwrap().star_points().unwrap() + }; + assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]); + // Points and ratio change; the outer radius stays. + let mut s = star.clone(); + s.set_points(9); + s.set_star_ratio(0.25); + assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18])); + assert_eq!(s.polygon_outline().anchor_count(), 18); +} + +/// A corner list shorter than the corners holds sharp corners past its end, so a new point or +/// side count does not give those corners the first corner's radius. +#[test] +fn a_short_corner_list_keeps_its_missing_corners_sharp() { + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + star.set_points(6); + let mut want = vec![0.0; 12]; + want[0] = 2.0; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}"); + let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + polygon.set_sides(6); + let mut want = vec![0.0; 6]; + want[0] = 2.0; + assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}"); +} + +/// A corner list longer than the corners drops its entries past the old last corner, so the +/// corners a new point count adds are sharp and keep the default kind. +#[test] +fn a_long_corner_list_drops_its_entries_past_the_corners() { + let mut radii = vec![0.0; 12]; + radii[0] = 2.0; + radii[10] = 7.0; + radii[11] = 7.0; + let mut kinds = vec![CornerKind::Round; 12]; + kinds[0] = CornerKind::Chamfer; + kinds[10] = CornerKind::Chamfer; + kinds[11] = CornerKind::Chamfer; + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false }; + star.set_points(6); + let mut want_radii = vec![0.0; 12]; + want_radii[0] = 2.0; + let mut want_kinds = vec![CornerKind::Round; 12]; + want_kinds[0] = CornerKind::Chamfer; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}"); + assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}"); + // A complete list that all corners share still fills the new corners. + let mut star = + LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false }; + star.set_points(6); + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}"); +} + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 02c4391921..ead201ffab 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -78,7 +78,7 @@ pub struct Selection { } /// See [`Selection::symbol_part`]. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct SymbolPart { /// The symbol instance. pub instance: NodeId, 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/Cargo.toml b/crates/effects/Cargo.toml index e737bc5ad8..679284ff97 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -24,6 +24,11 @@ craft-svg = { workspace = true, features = ["tree-render"] } # The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" serde_json = { workspace = true } +# Render Settings › Rendered: the 3D effects' solids drawn as an image with depth and shadow maps. +craft-raster3d = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-raster3d = { workspace = true, features = ["parallel"] } [dev-dependencies] vectorcraft-color = { workspace = true } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 8138474736..a89005aa21 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { if let Some(m) = crate::addons::halftone::halftone_art(d, n) { return Some(bake_pieces(d, m)); } - if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { + if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, & /// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and /// effects are dropped. `None` for other kinds of objects. pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option { - if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { + if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option { /// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`]. fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option { - if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { + if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) { return Some(m); } if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index c07f3b0413..7a6663b603 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, 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; 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), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, 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), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), 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; 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), 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 caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), 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 caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"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( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), 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; 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), 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 puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), 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 puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).", json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"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( 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; 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), 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, 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/lib.rs b/crates/effects/src/lib.rs index c2be1804db..1b6bd49c85 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -96,16 +96,19 @@ pub use reshape::{ has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ - CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, + CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve, + validate_revolve_in, }; +pub use solids::rendered::{rendered_warning, three_d_bounds_art_in}; pub use solids::{ BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic, - MeshGraphics, RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, - classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, - is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, - rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, - three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, - validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, + MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings, + SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, + graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, + names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art, + solid_art_drawn_in, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, + three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, + validate_three_d_params, view_options, with_graphic, }; pub use solids::{ GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 9ce14bbf47..ffbecebb17 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -172,8 +172,9 @@ fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec Option { + use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape}; + let bez = path.to_bezpath(); + let elements = bez.elements(); + if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) { + return None; + } + let segments: Vec = bez.segments().collect(); + for (i, a) in segments.iter().enumerate() { + let b = &segments[(i + 1) % segments.len()]; + if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) { + continue; + } + let controls = |s: &PathSeg| match s { + PathSeg::Line(s) => vec![s.p0, s.p1], + PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2], + PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3], + }; + let seam = a.end(); + let directions: Vec<_> = controls(a) + .into_iter() + .map(|p| p - seam) + .chain(controls(b).into_iter().map(|p| seam - p)) + .filter(|v| v.hypot() > 0.0) + .map(|v| v / v.hypot()) + .collect(); + let separated = directions.iter().any(|a| { + directions.iter().any(|b| { + let axis = *a + *b; + directions.iter().all(|v| axis.dot(*v) > 1e-12) + }) + }); + if !separated { + return None; + } + } + let mut flat = vectorcraft_geom::BezPath::new(); + let mut overflow = false; + let mut last = kurbo::Point::ZERO; + for el in elements { + if overflow { + break; + } + let from = last; + let controls = match el { + PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]), + PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]), + _ => None, + }; + if let Some(controls) = controls { + let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum(); + if !length.is_finite() + || length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2) + || controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH)) + { + return None; + } + } + last = match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p, + PathEl::ClosePath => last, + }; + let curve = match el { + PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))), + PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))), + _ => None, + }; + // Each curve piece is monotonic in both coordinates before flattening. + let pieces = curve.map_or_else( + || vec![(from, *el)], + |curve| { + curve + .extrema_ranges() + .into_iter() + .map(|range| { + let piece = curve.subsegment(range); + (piece.start(), piece.as_path_el()) + }) + .collect() + }, + ); + for (from, el) in pieces { + if overflow { + break; + } + let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_))); + let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_))); + vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| { + if skip > 0 { + skip -= 1; + } else if flat.elements().len() > SEAMED_FILL_EDGES + 2 { + overflow = true; + } else { + flat.push(e); + } + }); + } + } + if overflow { + return None; + } + // Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve. + seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?; + let fill = footprint(&bez, seam); + (fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill)) +} + /// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight` /// screened over it: a group of the face and the highlight's path on the face and its seam /// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the @@ -255,7 +372,13 @@ const SEAMED_FILL_EDGES: usize = 256; /// a seam that is not a positive finite width, or a footprint with no finite bounds or less area /// than the facet. pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option { - use kurbo::{PathEl, Point, Shape}; + seamed_fill_with_clearance(path, seam, 0.0) +} + +/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of +/// each other. +fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option { + use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape}; if !(seam.is_finite() && seam > 0.0) { return None; } @@ -294,6 +417,19 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio if touch(a, b, c, d) { return None; } + if clearance > 0.0 { + let ab = Line::new(a, b); + let cd = Line::new(c, d); + let distance_sq = ab + .nearest(c, 1e-6) + .distance_sq + .min(ab.nearest(d, 1e-6).distance_sq) + .min(cd.nearest(a, 1e-6).distance_sq) + .min(cd.nearest(b, 1e-6).distance_sq); + if distance_sq <= clearance * clearance { + return None; + } + } } } let fill = footprint(&bez, seam); @@ -690,6 +826,98 @@ mod tests { } } + /// A material's highlight over a curved face reaches its seam too, as the face's clip does, + /// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps + /// its outline alone. + #[test] + fn a_highlight_over_a_curved_face_covers_its_seam() { + use kurbo::Shape; + let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] { + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + let Some(shape) = over.path_data() else { panic!("a path") }; + let bez = shape.to_bezpath(); + assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge"); + assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face"); + assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam"); + assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2); + } + // A curved face that folds over itself keeps its outline alone, as its own nonzero fill. + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.quad_to((5.0, -1.0), (10.0, 10.0)); + folded.line_to((10.0, 0.0)); + folded.quad_to((5.0, 1.0), (0.0, 10.0)); + folded.close_path(); + let folded = vectorcraft_geom::PathData::from_bezpath(&folded); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&folded)); + } + + /// A curved face whose fold is smaller than the flattening tolerance, so that its flattened + /// outline does not cross itself, still keeps its outline alone, wound either way. + #[test] + fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.line_to((10.0, 0.0)); + folded.line_to((10.0, 10.0)); + folded.line_to((0.0, 10.0)); + folded.line_to((0.0, 0.01)); + folded.quad_to((5.0, -0.03), (9.0, 0.01)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold"); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&path)); + } + } + + /// A face with a collinear cubic that reverses direction keeps its highlight outline. + #[test] + fn a_highlight_over_a_retraced_cubic_keeps_its_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0)); + folded.line_to((12.0, 10.0)); + folded.line_to((0.0, 10.0)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal"); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&path)); + } + } + + #[test] + fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.line_to((1000.0, 1000.0)); + folded.quad_to((500.0, 499.999), (0.0, 0.2)); + folded.line_to((-1000.0, 1000.0)); + folded.line_to((-1000.0, -1000.0)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some()); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap(); + assert_eq!(over.path_data(), Some(&path)); + } + } + /// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the /// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound /// either way and in a concave notch. A facet whose footprint would gain or lose area under a diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 5d49c52de2..601706a0ca 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ - Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, + Build, Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, }; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; @@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option { /// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be /// resolved. pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art(doc, n, false) + art_reporting(doc, n, false, Build::Vector, &mut None) } /// [`expand_revolve_art_in`] without a document. @@ -854,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option { expand_revolve_art_in(None, n) } -/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared -/// command and UI remain unchanged. +/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in +/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI +/// remain unchanged. pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art(doc, n, true) + art_reporting(doc, n, true, Build::Draw, &mut None) } /// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on @@ -918,8 +919,9 @@ fn surface_meshes( graphics: bool, ) -> Result, String> { let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params)); + let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options)); surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics) - .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect()) + .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..m }).collect()) } /// [`surface_meshes`] in the default material. @@ -1083,13 +1085,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, n: &Node, expand: bool) -> Option { +/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, +/// the image of the lit surface where it can be made, in place of the shaded faces that +/// [`revolve_art_in`] keeps for bounds, hit testing and snapping. +pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { + art_reporting(doc, n, false, Build::Draw, &mut None) +} + +/// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with +/// the reason a rendered image can't be made kept in `warning`. +pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option) -> Option { + let check_only = build == Build::Check; if !has_revolve(n) { return None; } let n = &*resolve_for(doc, n, "Revolve", false).ok()?; if is_container(n) { - return group_art(doc, n, expand); + return group_art(doc, n, expand, check_only, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -1103,7 +1115,43 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - if crate::solids::renders_wireframe(fx) { + let p = merged_params(&fx.id, &fx.params); + // Rendered, the surface's image, with the shadows of every light on the surface and on the + // shadow plane; the shaded faces when it can't be made, and for vector measurements. + let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| { + let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) { + Err(crate::solids::rendered::PATHS_ONLY.into()) + } else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { + let b = path.bounds()?; + let (paint, opacity, _) = paint_of(item); + let options = rule_options(fx, rule); + surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| { + let lighting = crate::solids::rendered::lighting(&fx.id, &p); + let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) { + Some(shadow) => { + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let faces = cast_surface(&mut caster, &path, b, options, None)?; + crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces]) + } + None => lighting, + }; + if build == Build::Bounds { + crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) + } else { + crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only) + } + }) + } else { + Err(crate::solids::rendered::OPAQUE_ONLY.into()) + }; + crate::solids::rendered::reported(result, warning) + }); + if check_only { + return None; + } + if let Some(image) = image { + children.push(image); + } else if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?); } else { @@ -1132,6 +1180,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { for (original, item) in originals.into_iter().zip(&items) { if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; + if crate::renders_image(fx) { + warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + } + if check_only { + continue; + } let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { @@ -1284,9 +1338,15 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. -fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { +fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option) -> Option { let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; + if crate::renders_image(fx) { + warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + } + if check_only { + return None; + } let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); let b = union_bounds(&shapes)?; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 786d3954e4..6a9ddfbbff 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -41,7 +41,12 @@ pub use vectorcraft_three_d::SurfaceKind; pub(crate) mod shadow; pub(crate) mod wireframe; -pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in}; +pub use wireframe::{ + RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe, + three_d_wireframe_in, +}; + +pub mod rendered; pub(crate) mod material; pub use material::MATERIAL; @@ -1003,6 +1008,17 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, /// fill rule, its shape's scopes and the index of its shape. type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize); +fn solid_items(shape: &Profile) -> impl Iterator { + let top_fill = shape.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); + 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): @@ -1012,8 +1028,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { .iter() .enumerate() .flat_map(|(member, s)| { - let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); - s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| { + solid_items(s).map(move |i| { let (area, rule) = region(&s.path, s.rule, i); (i, s.opacity, area, rule, s.scopes.as_slice(), member) }) @@ -2053,12 +2068,57 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it /// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every /// surface of the object, and the surfaces. -fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { +fn art_for( + doc: Option<&Document>, + n: &Node, + effects: &[Effect], + shapes: &[Profile], + build: Build, + warning: &mut Option, +) -> Option { + let (fx, later) = effects.split_first()?; + if build == Build::Check && !crate::renders_image(fx) { + return Some((vec![], vec![])); + } // In wireframe mode the effect draws the edges of the faces it builds, with no shadow. if wireframe::renders_wireframe(fx) { return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?)); } let p = crate::merged_params(&fx.id, &fx.params); + // Rendered, the solids' image, with the shadows of every light on the solids and on the shadow + // plane; the shaded faces when it can't be made, and for vector measurements. + if build != Build::Vector + && let Some(settings) = wireframe::render_settings(&fx.id, &p) + { + let image = if rendered::reshapes_paths_only(later) { + Err(rendered::PATHS_ONLY.into()) + } 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))? { + Some((caster, shadow, cast)) => { + let faces: Vec> = cast.iter().map(|c| c.2.clone()).collect(); + rendered::with_receiver(lighting, &caster, shadow, &faces) + } + None => lighting, + }; + if build == Build::Bounds { + rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) + } else { + rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check) + } + }) + } else { + Err(rendered::OPAQUE_ONLY.into()) + }; + let image = rendered::reported(image, warning); + if build == Build::Check { + return Some((vec![], vec![])); + } + if let Some(image) = image { + return Some((vec![], vec![image])); + } + } let cast = casts_shadow(&fx.id, &p); let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?; // A shadow past the limits draws the source path, as a solid past them does; commands report @@ -2091,10 +2151,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result< /// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to /// the part of the shadow they cast too ([`shadow::scoped_art`]). fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result>, String> { + cast_shadow_with(id, p, shapes, shadow::options(p)) +} + +/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`. +fn cast_shadow_with<'a>( + id: &str, + p: &Value, + shapes: &'a [Profile], + settings: Option, +) -> Result>, String> { if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { return Ok(None); } - let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) }; let view = view_options(p); let mut caster = vectorcraft_three_d::ShadowCaster::new(); // The faces each solid of visible art added, with its member's scopes and its ink (opacity @@ -2823,21 +2893,48 @@ pub fn solid_art(n: &Node) -> Option { /// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be /// resolved. pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { + solid_art_reporting(doc, n, Build::Vector, &mut None) +} + +/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the +/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that +/// [`solid_art_in`] keeps for bounds, hit testing and snapping. +pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { + solid_art_reporting(doc, n, Build::Draw, &mut None) +} + +/// What a 3D effect's art is built for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Build { + /// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No + /// rendered image is made. + Vector, + /// Painted measurement art, with rendered images represented by their rectangles and no pixels. + Bounds, + /// Only whether the rendered image can be made, with the reason in the warning when it can't: + /// no art and no pixels. + Check, + /// The art drawn and exported: the rendered image where it can be made. + Draw, +} + +pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { if !has_solid(n) { return None; } let n = &*resolve(doc, n, "").ok()?; if is_container(n) { - return group_solid_art(doc, n); + return group_solid_art(doc, n, build, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); let (sources, paints) = solid_paint_sources(n); let mut children = vec![]; let remaining: Vec; - if let Some((index, fx)) = solid(&n.appearance.effects) { + if let Some((index, _)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = + art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); @@ -2851,9 +2948,16 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { // Every item's shadow goes behind every item's art. let mut shadows = vec![]; for (source, item) in sources.into_iter().zip(&paints) { - if let Some((index, fx)) = solid(item.effects()) { + if let Some((index, _)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item))); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = art_for( + doc, + n, + &item.effects()[index..], + &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], + build, + warning, + )?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); let with_later = |mut art: Arc| { Arc::make_mut(&mut art).appearance.effects = later.clone(); @@ -2882,11 +2986,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { /// geometry effects before it reshape the members, those after it bend the result as a whole; the /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the /// group's own fills or strokes, or when its members can't become solids. -fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option { - let (index, fx) = solid(&n.appearance.effects)?; +fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { + let (index, _) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?; + let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); @@ -3195,12 +3299,15 @@ pub struct SolidMesh { /// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`] /// for the 3D (Classic) effects. pub material: vectorcraft_three_d::Material, + /// The projection that takes the mesh's points to where the effect draws them on the page; + /// `None` when it is not known. + pub projection: Option, } impl SolidMesh { - /// A mesh painted `color`, with no graphics, in the default material. + /// A mesh painted `color`, with no graphics, in the default material, with no projection. pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { - Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT } + Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None } } } @@ -3305,17 +3412,17 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let material = material::of(&fx.id, &p); let mut out = vec![]; // A solid's parts with and without graphics count together against the limit. - let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { + let mut keep = |out: &mut Vec, (mesh, projection): (Mesh, _), (paint, opacity): (&Paint, f32), bounds: Rect| { split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) .into_iter() - .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit)) + .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, ..part }, limit)) }; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?; + keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?; } } return Ok(out); @@ -3352,7 +3459,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) match solid.mesh() { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *member); - keep(&mut out, mesh, (&paint, opacity), bounds)?; + keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs new file mode 100644 index 0000000000..59b425da48 --- /dev/null +++ b/crates/effects/src/solids/rendered.rs @@ -0,0 +1,779 @@ +//! Render Settings › Rendered: the solids of a 3D effect drawn as one image, with a depth buffer, +//! the metallic-roughness shading of every light and the shadows each light casts on the solids, +//! instead of the shaded vector faces. The image lies on the page where the vector faces lie: each +//! mesh point goes through the projection the effect draws its faces with +//! ([`vectorcraft_three_d::MeshProjection`]). +use std::io::Cursor; +use std::sync::Arc; + +use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps}; +use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_three_d::{Light, MeshProjection}; + +use super::SolidMesh; +use super::wireframe::RenderSettings; + +/// The message a rendered image that can't be made is reported with; the effect then draws its +/// shaded faces. +pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead"; + +/// The message for a solid painted with something other than an opaque solid color in Normal +/// blending, or with graphics; the effect then draws its shaded faces. +pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead"; + +/// The message for a later geometry effect that reshapes paths but leaves images unchanged. +pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead"; + +/// Do any visible effects reshape paths without also reshaping images in `reshape_leaves`? +pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool { + effects.iter().any(|e| { + e.visible + && (crate::is_geometry(&e.id) || crate::is_pathfinder(&e.id)) + && e.id != "distort.transform" + && e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none() + }) +} + +/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces. +pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead"; + +/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image. +/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back. +pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option { + let rendered = |fx: &vectorcraft_doc::Effect| fx.visible && crate::renders_image(fx); + if !n.appearance.effects.iter().any(rendered) && !n.appearance.items.iter().any(|i| i.effects().iter().any(rendered)) { + return None; + } + let mut warning = None; + if crate::has_revolve(n) { + let _ = crate::revolve::art_reporting(Some(doc), n, false, super::Build::Check, &mut warning); + } else { + let _ = super::solid_art_reporting(Some(doc), n, super::Build::Check, &mut warning); + } + warning +} + +/// The art of `n`'s 3D effect for painted bounds, with rendered images represented by their page +/// rectangles without pixels. Shaded fallback art and later effects keep their normal bounds. +/// This art is for measurement only; selection and snapping use the vector art instead. +pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) -> Option { + crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None) + .or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None)) +} + +/// The image rectangle for painted measurements, with the same eligibility and scene limits as +/// the rendered image, without rasterizing or adding an image to the cache. +pub(crate) fn bounds_art( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, +) -> Result>, String> { + art(doc, id, lighting, meshes, settings, true)?; + let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?; + let object = ImageObject { + key: String::new(), + width: m.cols, + height: m.rows, + xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]), + link: None, + placement: Default::default(), + pixels: None, + }; + Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) +} + +/// The rendered image of `result`, or `None` after a successful check. An error keeps its message +/// in `warning` when no earlier reason is there; the caller then draws its shaded faces. +pub(crate) fn reported(result: Result>, String>, warning: &mut Option) -> Option> { + match result { + Ok(image) => image, + Err(message) => { + warning.get_or_insert(message); + None + } + } +} + +/// The lights a rendered image is shaded with, as the effect's shaded faces are. +#[derive(Clone, Debug, PartialEq)] +pub struct Lighting { + /// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]). + pub lights: Vec, + /// Each light's shadow diffusion in points, in the same order as `lights`. + pub diffusion: Vec, + /// The ambient light, 0 to 2. + pub ambient: f64, + /// Shading on: off, the solids show their paint unlit, as the shaded faces do. + pub shade: bool, + /// Shadows on: each light that lights the art casts shadows on the solids and on + /// [`Lighting::receiver`]. Off, no light casts one. + pub shadows: bool, + /// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in + /// order round it ([`receiver`]); `None` without one. + pub receiver: Option<[[f64; 3]; 4]>, +} + +impl Lighting { + /// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art? + fn casts(&self, l: &Light) -> bool { + self.shade && self.shadows && l.intensity > 0.0 + } +} + +/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector +/// shadow paints it. +const PLANE_SHADOW: f32 = 0.5; + +/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size, +/// so a soft edge is not cut. VectorCraft's own value. +const PLANE_MARGIN: f64 = 0.05; + +/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster` +/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]). +pub(crate) fn with_receiver( + mut lighting: Lighting, + caster: &vectorcraft_three_d::ShadowCaster, + shadow: vectorcraft_three_d::Shadow, + faces: &[std::ops::Range], +) -> Lighting { + let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect(); + lighting.diffusion = lighting + .lights + .iter() + .map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0)) + .collect(); + let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max); + let shadow = vectorcraft_three_d::Shadow { softness, ..shadow }; + lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z])); + lighting +} + +/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page, +/// made with `samples` × `samples` samples a pixel. +#[derive(Clone, Debug, PartialEq)] +pub struct Rendered { + pub rect: Rect, + pub cols: u32, + pub rows: u32, + pub samples: u32, + pub pixels: Vec, +} + +/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the +/// ends of the depth buffer. +const DEPTH_MARGIN: f64 = 0.01; + +/// The largest share of the eye's distance a point may lie in front of the projection origin: at it +/// the vector faces stop growing ([`vectorcraft_three_d::MeshProjection::project`]). +const NEAREST: f64 = 0.999; + +/// The image of `meshes` lit by `lighting`, with `settings`, at the document's raster effects +/// resolution `doc_ppi` when the settings take it, within `limits`. An error ([`TOO_LARGE`]) when a +/// mesh has no projection or a different one, when a point lies at or behind the eye, when the +/// image has more pixels than `limits` allow even at one sample a pixel, or when the rasterizer +/// refuses the scene. `draft` takes one sample a pixel and draft shadow maps, as Low quality does. +pub fn render( + meshes: &[SolidMesh], + lighting: &Lighting, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, +) -> Result { + let too_large = || TOO_LARGE.to_string(); + let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?; + let scale = f64::from(cols * k) / rect.width(); + let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?; + scene.ssaa = k; + #[cfg(test)] + RASTERIZATIONS.with(|n| n.set(n.get() + 1)); + if scene.lights.iter().any(|l| l.shadow >= 0) { + try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?; + } + let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?; + try_encode(&mut image).map_err(|_| too_large())?; + let pixels = image + .data + .iter() + .flat_map(|p| { + let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p }; + let a = p[3].clamp(0.0, 1.0); + let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 }; + [straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8) + }) + .collect(); + Ok(Rendered { rect, cols, rows, samples: k, pixels }) +} + +#[cfg(test)] +thread_local! { + /// How many rendered images enter the rasterizing path on this thread. + static RASTERIZATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The projection, clip matrix and raster dimensions within the image's sample budget. +struct Measured { + projection: MeshProjection, + rect: Rect, + z: [f64; 2], + clip: [[f32; 4]; 4], + cols: u32, + rows: u32, + samples: u32, + low: bool, +} + +/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples, +/// without building a scene or producing pixels. +fn measure( + meshes: &[SolidMesh], + lighting: &Lighting, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, +) -> Result { + let too_large = || TOO_LARGE.to_string(); + let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?; + if meshes.iter().any(|m| m.projection != Some(projection)) { + return Err(too_large()); + } + let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?; + let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0); + let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0)); + let pixels = cols * rows; + if pixels.is_nan() || pixels > limits.max_pixels as f64 { + return Err(too_large()); + } + let (cols, rows) = (cols as u32, rows as u32); + let rect = Rect::new(bounds.x0, bounds.y0, bounds.x0 + f64::from(cols) * cell, bounds.y0 + f64::from(rows) * cell); + let low = draft || settings.quality == 0; + let mut k = if low { 1 } else { settings.samples() }; + while k > 1 && pixels * f64::from(k * k) > limits.max_pixels as f64 { + k -= 1; + } + let clip = clip(projection, rect, z).ok_or_else(too_large)?; + Ok(Measured { projection, rect, z, clip, cols, rows, samples: k, low }) +} + +/// Check scene limits without allocating raster or shadow depth buffers. The counts follow +/// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223, +/// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and +/// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657. +/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible +/// materials, the plane's two triangles hold no texture and the lights are directional, so each +/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer. +fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> { + let m = measure(meshes, lighting, settings, ppi, false, limits)?; + let size = (m.cols * m.samples, m.rows * m.samples); + let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?; + limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?; + if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights { + return Err(TOO_LARGE.into()); + } + let transform = + |matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3]; + let mut work = 0u64; + for tri in s.indices.as_chunks::<3>().0 { + let mut points = [[0.0; 2]; 3]; + for (point, &i) in points.iter_mut().zip(tri) { + let p = s.vertices[i as usize].pos; + let c = [0, 1, 2, 3].map(|r| transform(&s.clip, p, r)); + // Refuse transforms whose rounding escapes the measured clip volume. + if !c.iter().all(|v| v.is_finite()) || c[3] <= 0.0 || c[2] < 0.0 || c[2] > c[3] { + return Err(TOO_LARGE.into()); + } + let iw = 1.0 / c[3]; + *point = [(f64::from(c[0] * iw) + 1.0) * 0.5 * f64::from(s.width), (1.0 - f64::from(c[1] * iw)) * 0.5 * f64::from(s.height)]; + } + let area = (0..3).map(|i| points[i][0] * points[(i + 1) % 3][1] - points[(i + 1) % 3][0] * points[i][1]).sum::(); + if !area.is_finite() { + return Err(TOO_LARGE.into()); + } + if area != 0.0 { + let pixels = bounding_work(points, [s.width, s.height]); + if pixels > 0 { + work = work.saturating_add(pixels + 1); + } + } + if work > limits.max_work { + return Err(TOO_LARGE.into()); + } + } + // Shadow maps are made only for the lights that cast shadows, from the triangles that cast them. + let casters: Vec<&[u32; 3]> = s + .indices + .as_chunks::<3>() + .0 + .iter() + .filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows)) + .collect(); + if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) { + return Ok(()); + } + let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + for v in &s.vertices { + for k in 0..3 { + lo[k] = lo[k].min(f64::from(v.pos[k])); + hi[k] = hi[k].max(f64::from(v.pos[k])); + } + } + let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5); + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0; + let kinds: Vec = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect(); + let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds); + let maps = sizes.iter().flatten().count() as u64; + if maps.saturating_mul(casters.len() as u64) > limits.max_work { + return Err(TOO_LARGE.into()); + } + let mut work = 0u64; + for (light, size) in s.lights.iter().zip(sizes) { + let (Some(size), true) = (size, light.shadow >= 0) else { continue }; + let dir = light.dir.map(f64::from); + let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0); + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let unit = |v: [f64; 3]| v.map(|x| x / dot(v, v).sqrt()); + let forward = unit(dir); + let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }; + let down = unit([0, 1, 2].map(|k| hint[k] - forward[k] * dot(hint, forward))); + let right = unit([ + down[1] * forward[2] - down[2] * forward[1], + down[2] * forward[0] - down[0] * forward[2], + down[0] * forward[1] - down[1] * forward[0], + ]); + let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]); + let focal = (f64::from(size) * 0.5 / radius) as f32; + for tri in &casters { + let points = [0, 1, 2].map(|k| { + let p = s.vertices[tri[k] as usize].pos; + [0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5)) + }); + let [a, b, c] = points; + let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + if !area.is_finite() { + return Err(TOO_LARGE.into()); + } + let texels = if area.abs() < 1e-12 { 0 } else { bounding_work(points, [size; 2]) }; + work = work.saturating_add(texels + 1); + if work > limits.max_work { + return Err(TOO_LARGE.into()); + } + } + } + Ok(()) +} + +/// The pixels inside a triangle's bounding box, clamped to the raster. +fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 { + [0, 1] + .map(|k| { + let lo = points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min).floor().clamp(0.0, f64::from(size[k])) as u64; + let hi = points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max).ceil().clamp(0.0, f64::from(size[k])) as u64; + hi.saturating_sub(lo) + }) + .into_iter() + .product() +} + +/// The corners of the shadow plane of `lighting`, in mesh space; none without one. +fn receiver(lighting: &Lighting) -> &[[f64; 3]] { + lighting.receiver.as_ref().map_or(&[], |q| q.as_slice()) +} + +/// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and +/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or +/// behind the eye. +fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> { + let mut bounds: Option = None; + let mut z = [f64::INFINITY, f64::NEG_INFINITY]; + meshes.iter().flat_map(|m| &m.mesh.positions).next()?; + for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) { + if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) { + return None; + } + let at = projection.project(*p); + let r = Rect::from_points(at, at); + bounds = Some(bounds.map_or(r, |b| b.union(r))); + z = [z[0].min(p[2]), z[1].max(p[2])]; + } + bounds.filter(|b| b.width().is_finite() && b.height().is_finite()).map(|b| (b, z)) +} + +/// The row-major clip matrix that takes a point of the solids' world space (mesh space with y down, +/// about the projection origin) to the image `rect` as [`MeshProjection::project`] places it, with +/// depths `z` kept inside the depth buffer and nearer points deeper in it. `None` when no depth +/// mapping keeps them in order. +fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]; 4]> { + let (rw, rh) = (rect.width(), rect.height()); + let a = 2.0 * (projection.origin.x - rect.x0) / rw - 1.0; + let b = 1.0 - 2.0 * (projection.origin.y - rect.y0) / rh; + // w = 1 − z / eye without perspective's eye: 1. + let inv_eye = projection.eye.map_or(0.0, |e| 1.0 / e); + let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) }; + let w = |z: f64| 1.0 - z * inv_eye; + // ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN. + // With w positive over [z0, z1] the ndc depth is a linear-fractional function of z, so it rises + // monotonically between those two ends even when dz itself is negative (a near eye). + let (w0, w1) = (w(z0), w(z1)); + if !(w0 > 0.0 && w1 > 0.0) { + return None; + } + let (lo, hi) = (DEPTH_MARGIN * w0, (1.0 - DEPTH_MARGIN) * w1); + let dz = (hi - lo) / (z1 - z0); + let d0 = lo - dz * z0; + if !(dz.is_finite() && d0.is_finite() && hi / w1 > lo / w0) { + return None; + } + let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]]; + let m = m.map(|row| row.map(|v| v as f32)); + m.iter().flatten().all(|v| v.is_finite()).then_some(m) +} + +/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world +/// space (mesh space with y down, as the page is), opaque ones first, then +/// those of see-through solids from back to front; one material for each mesh; one parallel light, +/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including +/// the samples per image pixel. +fn scene( + meshes: &[SolidMesh], + lighting: &Lighting, + projection: MeshProjection, + z: [f64; 2], + clip: [[f32; 4]; 4], + size: (u32, u32), + scale: f64, +) -> Option { + let eye = projection.eye.unwrap_or(z[1] + 1.0); + let mut vertices = vec![]; + let mut opaque: Vec<[u32; 3]> = vec![]; + let mut clear: Vec<([u32; 3], f64)> = vec![]; + let mut materials = vec![]; + for (index, m) in meshes.iter().enumerate() { + let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }); + materials.push(craft_raster3d::Material { + base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0], + metallic: m.material.metallic() as f32, + roughness: m.material.roughness() as f32, + opacity: alpha, + double_sided: true, + unlit: !lighting.shade, + casts_shadows: true, + ..Default::default() + }); + let base = vertices.len() as u32; + let mesh = &m.mesh; + for (i, p) in mesh.positions.iter().enumerate() { + let n = mesh.normals.get(i).copied().unwrap_or([0.0, 0.0, 1.0]); + vertices.push(Vertex { + pos: [p[0] as f32, -p[1] as f32, p[2] as f32], + normal: [n[0] as f32, -n[1] as f32, n[2] as f32], + uv: mesh.uvs.get(i).map_or([0.0; 2], |uv| [uv[0] as f32, uv[1] as f32]), + tangent: [1.0, 0.0, 0.0, 1.0], + material: index as u32, + }); + } + for t in &mesh.triangles { + if t.iter().any(|&i| i as usize >= mesh.positions.len()) { + return None; + } + let tri = t.map(|i| base + i); + if alpha >= 1.0 { + opaque.push(tri); + } else { + let depth = t.iter().map(|&i| mesh.positions[i as usize][2]).sum::() / 3.0; + clear.push((tri, depth)); + } + } + } + clear.sort_by(|a, b| a.1.total_cmp(&b.1)); + // The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's + // opacity, behind every surface, so first in the see-through range. + let mut plane = vec![]; + if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) { + let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3])); + let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len.is_finite() && len > 0.0 { + let material = materials.len() as u32; + materials.push(craft_raster3d::Material { + base: [0.0, 0.0, 0.0, 1.0], + opacity: PLANE_SHADOW, + double_sided: true, + shadows_only: true, + receives_shadows: true, + casts_shadows: false, + ..Default::default() + }); + let base = vertices.len() as u32; + for p in q { + vertices.push(Vertex { + pos: [p[0] as f32, -p[1] as f32, p[2] as f32], + normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32], + uv: [0.0; 2], + tangent: [1.0, 0.0, 0.0, 1.0], + material, + }); + } + plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]]; + } + } + // Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles + // first so the strict depth test keeps that paint when surfaces share a depth. + let opaque_count = (opaque.len() * 3) as u32; + let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect(); + let lights = lighting + .lights + .iter() + .enumerate() + .filter(|_| lighting.shade) + .map(|(i, l)| { + // The direction the light travels: away from it. + let [x, y, z] = l.direction().map(|v| -v); + let len = (x * x + y * y + z * z).sqrt(); + craft_raster3d::Light { + kind: 0, + pos: [0.0; 3], + dir: [(x / len) as f32, (y / len) as f32, (z / len) as f32], + color: l.color.map(|c| srgb_to_linear((c * l.intensity).clamp(0.0, 1.0) as f32)), + cos_inner: 1.0, + cos_outer: 1.0, + falloff: 0, + radius: 0.0, + falloff_distance: 0.0, + // With Shadows off no light casts one, on the solids or on a plane. + shadow: if lighting.casts(l) { 0 } else { -1 }, + shadow_darkness: 1.0, + shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32, + } + }) + .collect(); + // Ambient light up to 100% goes through the sRGB curve; above it, the linear value scales with + // the intensity, as the shaded faces' ambient term does. + let ambient = lighting.ambient.clamp(0.0, 2.0) as f32; + let ambient = srgb_to_linear(ambient.min(1.0)) * ambient.max(1.0); + Some(Scene { + width: size.0, + height: size.1, + ssaa: 1, + clip, + // Camera depth: the distance in front of the eye, on the z axis. + view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, eye as f32], [0.0, 0.0, 0.0, 1.0]], + eye: [0.0, 0.0, eye as f32], + cam_fwd: [0.0, 0.0, -1.0], + ortho: projection.eye.is_none(), + vertices, + indices, + opaque_count, + // Read only by the renderers with auxiliary outputs, which this one does not use. + part_ids: vec![], + materials, + textures: vec![], + texels: vec![], + lights, + shadows: vec![], + shadow_texels: vec![], + env: None, + ambient: [ambient; 3], + linear_io: false, + }) +} + +/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be +/// encoded. +pub fn image_node(id: NodeId, image: &Rendered) -> Option> { + Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?))))) +} + +/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded. +fn image_object(image: &Rendered) -> Option { + let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?; + let mut png = vec![]; + raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let blob = ImageBlob::png(png); + let cell = image.rect.width() / f64::from(image.cols); + Some(ImageObject { + key: blob.content_key(), + width: image.cols, + height: image.rows, + xf: Affine::new([cell, 0.0, 0.0, image.rect.height() / f64::from(image.rows), image.rect.x0, image.rect.y0]), + link: None, + placement: Default::default(), + pixels: Some(Arc::new(blob)), + }) +} + +/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with +/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the +/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits +/// without producing pixels, returning `Ok(None)` when it fits. +pub(crate) fn art( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, + check_only: bool, +) -> Result>, String> { + // Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and + // apply a solid's opacity once to the whole surface. + if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) { + return Err(OPAQUE_ONLY.into()); + } + let ppi = doc.map_or(72.0, |d| d.raster_ppi()); + if check_only { + check(meshes, lighting, settings, ppi, &Limits::default())?; + return Ok(None); + } + let key = image_key(meshes, lighting, settings, ppi); + let made = match cached(key) { + Some(made) => made, + None => { + let made = render(meshes, lighting, settings, ppi, false, &Limits::default()) + .and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string())); + keep(key, &made); + made + } + }; + made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) +} + +/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's +/// own values. +const KEPT_IMAGES: usize = 32; +const KEPT_BYTES: usize = 64 << 20; + +/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]). +type Kept = Vec<(u128, Result)>; + +#[cfg(not(test))] +static KEPT: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +thread_local! { + /// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on + /// what other tests drew. + static KEPT: std::cell::RefCell = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Run `f` on the kept images; `None` when they can't be reached. +fn with_kept(f: impl FnOnce(&mut Kept) -> T) -> Option { + #[cfg(not(test))] + { + KEPT.lock().ok().map(|mut kept| f(&mut kept)) + } + #[cfg(test)] + { + KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept))) + } +} + +/// The image kept under `key`, moved to the newest place. +fn cached(key: u128) -> Option> { + with_kept(|kept| { + let at = kept.iter().position(|(k, _)| *k == key)?; + let entry = kept.remove(at); + let made = entry.1.clone(); + kept.push(entry); + Some(made) + }) + .flatten() +} + +/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`]. +fn keep(key: u128, made: &Result) { + let bytes = |m: &Result| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len()); + if bytes(made) > KEPT_BYTES { + return; + } + with_kept(|kept| { + kept.retain(|(k, _)| *k != key); + kept.push((key, made.clone())); + while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::() > KEPT_BYTES { + drop(kept.remove(0)); + } + }); +} + +/// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals, +/// texture coordinates, triangles, color, material and projection, the lights, ambient light, +/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or +/// reshaping the object, or changing any setting, changes it; panning and redrawing do not. +fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 { + use std::hash::{Hash, Hasher}; + let half = |seed: u8| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + seed.hash(&mut h); + let mut f = |v: f64| v.to_bits().hash(&mut h); + for m in meshes { + let mesh = &m.mesh; + mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v)); + mesh.uvs.iter().flatten().for_each(|v| f(*v)); + m.color.iter().for_each(|c| f(f64::from(*c))); + f(m.material.roughness()); + f(m.material.metallic()); + if let Some(p) = m.projection { + [p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f); + } + f(mesh.positions.len() as f64); + f(mesh.triangles.len() as f64); + } + for l in &lighting.lights { + [l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f); + } + lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v)); + lighting.diffusion.iter().for_each(|v| f(*v)); + f(lighting.diffusion.len() as f64); + [lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64] + .into_iter() + .for_each(&mut f); + [settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f); + for m in meshes { + m.mesh.triangles.hash(&mut h); + } + h.finish() + }; + (u128::from(half(1)) << 64) | u128::from(half(2)) +} + +/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or +/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them +/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped +/// graphics, masks and blending. +pub(crate) fn takes<'a>(items: impl IntoIterator, masked: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + use vectorcraft_doc::color::Paint; + !masked + && items.into_iter().all(|i| match i { + AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(), + AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(), + }) +} + +/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`]) +/// for Revolve, the other effects' ([`super::view_options`]) otherwise. +pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting { + let (lights, ambient, shade) = if id == crate::REVOLVE { + let o = crate::revolve_options(p); + (o.active_lights(), o.ambient, o.shade) + } else { + let v = super::view_options(p); + (v.active_lights(), v.ambient, v.shade) + }; + let lit = lights.iter().any(|l| l.intensity > 0.0); + let shadows = super::shadow::rendered_options(p, lit).is_some(); + Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None } +} + +/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting` +/// draws its shadow plane with; `None` with Shadows off or no light lighting the art. +pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option { + super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0)) +} + +#[cfg(test)] +#[path = "rendered/tests.rs"] +mod tests; diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs new file mode 100644 index 0000000000..403991b6ca --- /dev/null +++ b/crates/effects/src/solids/rendered/tests.rs @@ -0,0 +1,1114 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::*; + +fn square(x: f64, y: f64, size: f64) -> PathData { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + size, y)); + b.line_to((x + size, y + size)); + b.line_to((x, y + size)); + b.close_path(); + PathData::from_bezpath(&b) +} + +/// A 100 pt square filled `color`, with effect `id` and `params`. +fn solid_square(id: &str, color: Color, params: Value) -> Node { + let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(color), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'. +fn drawn(n: &Node) -> Node { + crate::revolve_art_drawn_in(None, n).or_else(|| super::super::solid_art_drawn_in(None, n)).unwrap_or_else(|| panic!("no art for {n:?}")) +} + +/// The image objects in `art`. +fn images(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |c| { + if let NodeKind::Image(i) = &c.kind { + out.push((**i).clone()); + } + }); + out +} + +/// The bounds of every filled path in `art`. +fn faces_bounds(art: &Node) -> Option { + let mut out: Option = None; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + out = Some(out.map_or(b, |o| o.union(b))); + } + }); + out +} + +/// The straight-alpha RGBA8 pixel at column `x`, row `y` of `image`. +fn pixel(image: &Rendered, x: u32, y: u32) -> [u8; 4] { + let i = 4 * (y * image.cols + x) as usize; + [image.pixels[i], image.pixels[i + 1], image.pixels[i + 2], image.pixels[i + 3]] +} + +/// The meshes and lights of `n`'s 3D effect, as the rendered image takes them. +fn scene_of(n: &Node) -> (Vec, Lighting) { + let fx = &n.appearance.effects[0]; + let p = crate::merged_params(&fx.id, &fx.params); + (crate::three_d_meshes(n).unwrap(), lighting(&fx.id, &p)) +} + +const MEDIUM: RenderSettings = RenderSettings { quality: 1, resolution: None, white: false }; + +const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, super::super::ROTATE]; + +#[test] +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] { + 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( + Gradient::new(GradientKind::Linear, stops), + ))))); + n.appearance.items.insert(0, lower); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + n.appearance.items.swap(0, 1); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "{id}"); + assert!(images(&drawn(&n)).is_empty(), "{id}"); + } +} + +/// 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); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + n.appearance.effects.push(crate::new_effect("pathfinder.add", &json!({})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(PATHS_ONLY), "{id}"); + assert!(images(&drawn(&n)).is_empty(), "{id}"); + assert!(faces_bounds(&drawn(&n)).is_some(), "{id}"); + n.appearance.effects[1].visible = false; + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + } +} + +/// The projection each mesh carries takes its points onto the page where the vector faces of the +/// same solid lie: every corner of every facet is a projected mesh point, with and without +/// perspective. +#[test] +fn projected_mesh_points_land_on_the_facets() { + for perspective in [0.0, 60.0] { + let path = square(100.0, 100.0, 100.0); + let b = path.bounds().unwrap(); + let view = vectorcraft_three_d::View { perspective, ..Default::default() }; + let solid = vectorcraft_three_d::extrude_meshed(&path, FillRule::NonZero, b, Default::default(), view).unwrap(); + let projection = solid.projection().unwrap(); + let points: Vec = solid.mesh().unwrap().positions.iter().map(|p| projection.project(*p)).collect(); + let corners: Vec = solid.facets.iter().flat_map(|f| f.contours.iter().flatten().copied()).collect(); + assert!(!corners.is_empty()); + for c in corners { + let near = points.iter().map(|p| p.distance(c)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "perspective {perspective}: facet corner {c:?} is {near} pt from every projected mesh point"); + } + } +} + +/// Rendered, each of the panel's four effects draws one image in place of its shaded faces, over +/// the area the shaded faces cover: at most one pixel larger on each side. +#[test] +fn rendered_mode_draws_one_image_over_the_shaded_faces() { + for id in FOUR { + let shaded = faces_bounds(&drawn(&solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({})))).unwrap(); + let art = drawn(&solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}}))); + let list = images(&art); + assert_eq!(list.len(), 1, "{id}"); + assert!(faces_bounds(&art).is_none(), "{id}: the shaded faces are drawn too"); + let i = &list[0]; + let rect = Rect::new(i.xf.as_coeffs()[4], i.xf.as_coeffs()[5], 0.0, 0.0); + let (x0, y0) = (rect.x0, rect.y0); + let (x1, y1) = (x0 + f64::from(i.width) * i.xf.as_coeffs()[0], y0 + f64::from(i.height) * i.xf.as_coeffs()[3]); + // At 72 ppi one pixel is one point. + for (got, want, grows) in [(x0, shaded.x0, false), (y0, shaded.y0, false), (x1, shaded.x1, true), (y1, shaded.y1, true)] { + let off = if grows { got - want } else { want - got }; + assert!((-1e-6..=1.0 + 1e-6).contains(&off), "{id}: image edge {got} against the faces' {want}"); + } + } +} + +/// Later path deformations keep shaded faces for drawing and bounds and report the fallback. +/// Hidden deformations, Gaussian Blur, Transform and Warp keep the rendered image. +#[test] +fn later_geometry_keeps_shaded_faces_only_when_images_cannot_take_it() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + n.appearance.effects.push(crate::new_effect("distort.puckerBloat", &json!({"amount": 20.0})).unwrap()); + let art = drawn(&n); + assert!(images(&art).is_empty(), "{id}"); + assert!(faces_bounds(&art).is_some(), "{id}"); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(PATHS_ONLY), "{id}"); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + assert!(images(&measured).is_empty(), "{id}: bounds use shaded faces"); + assert!(faces_bounds(&measured).is_some(), "{id}"); + + n.appearance.effects[1].visible = false; + assert_eq!(images(&drawn(&n)).len(), 1, "{id}: hidden deformation"); + assert!(crate::rendered_warning(&doc, &n).is_none(), "{id}"); + for (later, params) in + [("blur.gaussian", json!({"radius": 5.0})), ("distort.transform", json!({"moveH": 10.0})), ("warp.arc", json!({"bend": 20.0}))] + { + n.appearance.effects[1] = crate::new_effect(later, ¶ms).unwrap(); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}: {later}"); + assert!(crate::rendered_warning(&doc, &n).is_none(), "{id}: {later}"); + } + } +} + +/// With ambient light alone at 100 %, the rendered surface shows its paint unchanged, as the shaded +/// faces do (brightness 1 times the paint); with no light at all it is black, as they are. +#[test] +fn ambient_light_alone_shows_the_paint_as_the_shaded_faces_do() { + let paint = Color::rgb(0.2, 0.5, 0.8); + for (ambient, want) in [(100.0, [51u8, 128, 204]), (0.0, [0, 0, 0])] { + let n = solid_square( + super::super::ROTATE, + paint, + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightIntensity": 0, "ambient": ambient}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + for c in 0..3 { + assert!(center[c].abs_diff(want[c]) <= 1, "ambient {ambient}: {center:?} against {want:?}"); + } + assert_eq!(center[3], 255); + } +} + +#[test] +fn coplanar_opaque_paints_keep_the_shaded_faces_order() { + use vectorcraft_doc::{AppearanceItem, FillLayer}; + + let lower = Color::rgb(0.8, 0.2, 0.1); + let upper = Color::rgb(0.1, 0.3, 0.9); + let params = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false, "render": {"mode": "rendered"}}); + let mut fills = solid_square(super::super::ROTATE, lower, params.clone()); + fills.appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(upper)))); + let mut group = Node::group( + NodeId(3), + vec![ + Arc::new(Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(lower), Paint::None, 0.0))), + Arc::new(Node::path(NodeId(2), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(upper), Paint::None, 0.0))), + ], + ); + group.appearance.effects.push(crate::new_effect(super::super::ROTATE, ¶ms).unwrap()); + for n in [fills, group] { + let mut shaded = n.clone(); + shaded.appearance.effects[0].params["render"]["mode"] = json!("shaded"); + let mut top = None; + drawn(&shaded).walk(&mut |face| { + if face.path_data().is_some() { + for item in &face.appearance.items { + if let AppearanceItem::Fill(f) = item { + top = f.paint.color(); + } + } + } + }); + assert_eq!(top, Some(upper)); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + let want = top.unwrap().to_rgb().map(|c| (c * 255.0).round() as u8); + assert!(center[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 1), "{center:?} against {want:?}"); + assert_eq!(center[3], 255); + } +} + +#[test] +fn side_mapped_graphics_draw_the_shaded_faces_and_report_the_fallback() { + let mut doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mark = Node::path(NodeId(0), square(0.0, 0.0, 10.0), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); + let n = solid_square( + super::super::EXTRUDE, + Color::rgb(0.5, 0.5, 0.5), + json!({ + "rotationX": -90, "rotationY": 0, "rotationZ": 0, "shade": false, + "graphics": [{"symbol": "Mark", "face": "side"}], "render": {"mode": "rendered"} + }), + ); + let art = super::super::solid_art_drawn_in(Some(&doc), &n).unwrap(); + assert!(images(&art).is_empty()); + assert!(faces_bounds(&art).is_some()); + let mut graphic_drawn = false; + art.walk(&mut |face| { + graphic_drawn |= face + .appearance + .items + .iter() + .any(|item| matches!(item, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint.color() == Some(Color::rgb(1.0, 0.0, 0.0)))); + }); + assert!(graphic_drawn); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY)); +} + +/// Ambient intensity retains the upper half of its range even where no directional light falls. +#[test] +fn ambient_200_percent_is_brighter_than_100_percent() { + let level = |ambient| { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.2, 0.3, 0.4), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightIntensity": 0, "ambient": ambient}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + pixel(&image, image.cols / 2, image.rows / 2) + }; + let (normal, bright) = (level(100.0), level(200.0)); + assert_eq!(normal[3], 255); + assert_eq!(bright[3], 255); + for c in 0..3 { + assert!(bright[c] > normal[c] + 10, "channel {c}: 100% {normal:?}, 200% {bright:?}"); + } +} + +/// An extruded U under a light from the right, with Shadows `shadow`. +fn concave_u(shadow: bool) -> Node { + let mut path = BezPath::new(); + path.move_to((100.0, 100.0)); + for p in [(125.0, 100.0), (125.0, 175.0), (175.0, 175.0), (175.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)] { + path.line_to(p); + } + path.close_path(); + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&path), Appearance::basic(Paint::solid(Color::rgb(0.7, 0.7, 0.7)), Paint::None, 0.0)); + n.appearance.effects.push( + crate::new_effect( + super::super::EXTRUDE, + &json!({ + "depth": 80, "rotationX": -30, "rotationY": -30, "rotationZ": 0, + "lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10, "shadow": shadow + }), + ) + .unwrap(), + ); + n +} + +/// The most the solids' own shadows darken a pixel's linear red in the image of `n`, against the +/// same scene with no material casting shadows. +fn self_shadow_darkening(n: &Node) -> f32 { + let (meshes, lighting) = scene_of(n); + assert_eq!(meshes.len(), 1, "the caster and receiver belong to the same solid"); + let projection = meshes[0].projection.unwrap(); + let (rect, z) = extent(&meshes, &[], projection).unwrap(); + let mut shadowed = scene(&meshes, &lighting, projection, z, clip(projection, rect, z).unwrap(), (160, 160), 160.0 / rect.width()).unwrap(); + let mut unshadowed = shadowed.clone(); + for material in &mut unshadowed.materials { + material.casts_shadows = false; + } + let limits = Limits::default(); + let draw = |scene: &mut Scene| { + if scene.lights.iter().any(|l| l.shadow >= 0) { + try_shadow_maps(scene, false, &limits).unwrap(); + } + try_render_cpu(scene, &limits).unwrap().0 + }; + let (shadowed, unshadowed) = (draw(&mut shadowed), draw(&mut unshadowed)); + shadowed.data.iter().zip(&unshadowed.data).filter(|(a, b)| a[3] == 1.0 && b[3] == 1.0).map(|(a, b)| b[0] - a[0]).fold(0.0, f32::max) +} + +/// With Shadows on, the arms of an extruded U cast shadows across its recess under a light from +/// the right; with Shadows off the solid casts none on itself. +#[test] +fn a_concave_solid_casts_a_shadow_on_itself() { + let on = self_shadow_darkening(&concave_u(true)); + assert!(on > 0.05, "Shadows on: the solid's own shadow darkens linear red by {on}"); + let off = self_shadow_darkening(&concave_u(false)); + assert_eq!(off, 0.0, "Shadows off: the solid shadows itself by {off}"); +} + +/// Shading off, the surface shows its paint unlit, as the shaded faces do. +#[test] +fn unshaded_surfaces_show_their_paint() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"shade": false})); + let (meshes, lighting) = scene_of(&n); + assert!(!lighting.shade); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + let worst = center[..3].iter().zip([51u8, 128, 204]).map(|(a, b)| a.abs_diff(b)).max(); + assert!(matches!(worst, Some(0..=1)), "{center:?}"); +} + +/// A face turned toward the light is lit more than one turned away from it, and a light straight +/// in front of a face lights it more than one that grazes it. +#[test] +fn a_face_toward_the_light_is_brighter() { + let level = |height: f64| { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.5, 0.5, 0.5), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": height, "lightIntensity": 100, "ambient": 0}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + pixel(&image, image.cols / 2, image.rows / 2)[0] + }; + let (front, grazing) = (level(90.0), level(10.0)); + assert!(front > grazing + 40, "front {front}, grazing {grazing}"); + assert!(grazing > 0); +} + +/// Low, Medium and High take 1, 2 × 2 and 3 × 3 samples a pixel; a quality whose samples would +/// pass the pixel limit takes fewer, and an image past the limit at one sample a pixel is refused, +/// when the effect draws its shaded faces instead. +#[test] +fn quality_sets_the_samples_within_the_pixel_limit() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + for (quality, k) in [(0, 1), (1, 2), (2, 3)] { + let image = render(&meshes, &lighting, RenderSettings { quality, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + assert_eq!(image.samples, k, "quality {quality}"); + } + let one = render(&meshes, &lighting, RenderSettings { quality: 2, ..MEDIUM }, 72.0, true, &Limits::default()).unwrap(); + assert_eq!(one.samples, 1, "a draft takes one sample"); + let pixels = u64::from(one.cols) * u64::from(one.rows); + let mut limits = Limits::default(); + limits.max_pixels = pixels * 4; + let image = render(&meshes, &lighting, RenderSettings { quality: 2, ..MEDIUM }, 72.0, false, &limits).unwrap(); + assert_eq!(image.samples, 2); + limits.max_pixels = pixels - 1; + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &limits), Err(TOO_LARGE.to_string())); +} + +/// The resolution sets the image's pixels: 144 ppi gives twice the columns and rows of 72 ppi over +/// the same area, and without one the document's raster effects resolution applies. +#[test] +fn resolution_sets_the_image_grid() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let at = |resolution: Option, doc: f64| { + render(&meshes, &lighting, RenderSettings { resolution, ..MEDIUM }, doc, false, &Limits::default()).unwrap() + }; + let (base, fine, doc) = (at(Some(72.0), 300.0), at(Some(144.0), 300.0), at(None, 144.0)); + assert!( + fine.cols.abs_diff(2 * base.cols) <= 1 && fine.rows.abs_diff(2 * base.rows) <= 1, + "{}x{} against {}x{}", + fine.cols, + fine.rows, + base.cols, + base.rows + ); + assert_eq!((doc.cols, doc.rows), (fine.cols, fine.rows)); +} + +/// A white background makes every pixel opaque, white where no surface is; transparent, those +/// pixels are clear. +#[test] +fn the_background_is_white_or_clear() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let clear = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let white = render(&meshes, &lighting, RenderSettings { white: true, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + let corners = |i: &Rendered| [(0, 0), (i.cols - 1, 0), (0, i.rows - 1), (i.cols - 1, i.rows - 1)].map(|(x, y)| pixel(i, x, y)); + assert!(corners(&clear).iter().any(|p| p[3] == 0), "{:?}", corners(&clear)); + assert!(white.pixels.chunks(4).all(|p| p[3] == 255)); + assert!(corners(&white).contains(&[255; 4]), "{:?}", corners(&white)); +} + +/// A mesh without a projection, or meshes with different ones, can't be placed: the image is refused. +#[test] +fn meshes_without_one_projection_are_refused() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (mut meshes, lighting) = scene_of(&n); + let mut other = meshes[0].clone(); + other.projection = other.projection.map(|p| MeshProjection { origin: Point::new(p.origin.x + 1.0, p.origin.y), ..p }); + meshes.push(other); + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); + meshes[0].projection = None; + assert_eq!(render(&meshes[..1], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); + assert_eq!(render(&[], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); +} + +/// Depths reaching close to a near eye still map in order: with the eye at 100 and depths 0 to 99.5 +/// the farthest point lands at the depth margin and the nearest at one minus it. +#[test] +fn depths_close_to_a_near_eye_keep_a_clip_matrix() { + let projection = MeshProjection { origin: Point::new(50.0, 50.0), eye: Some(100.0) }; + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let Some(m) = clip(projection, rect, [0.0, 99.5]) else { panic!("a perspective range in front of the eye maps") }; + let ndc = |z: f64| { + let row = |r: [f32; 4]| f64::from(r[2]) * z + f64::from(r[3]); + row(m[2]) / row(m[3]) + }; + assert!((ndc(0.0) - DEPTH_MARGIN).abs() < 1e-3, "{}", ndc(0.0)); + assert!((ndc(99.5) - (1.0 - DEPTH_MARGIN)).abs() < 1e-3, "{}", ndc(99.5)); + assert!(ndc(50.0) > ndc(0.0) && ndc(99.5) > ndc(50.0)); + assert!(clip(projection, rect, [0.0, 100.0]).is_none()); +} + +/// A solid painted with a gradient, in a blending mode other than Normal or with an opacity below +/// 100% draws its shaded faces, which keep that paint: the image shows opaque solid colors only. +#[test] +fn gradients_and_blending_draw_the_shaded_faces() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + for id in FOUR { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + n.appearance.items[0] = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new( + GradientPaint::new(Gradient::new(GradientKind::Linear, stops)), + )))); + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: gradient"); + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.blend = vectorcraft_doc::color::BlendMode::Multiply; + } + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blending"); + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = 0.5; + } + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: opacity"); + } +} + +/// A loaded file whose `render` breaks the rules draws the shaded faces. +#[test] +fn an_invalid_loaded_render_draws_shaded() { + let mut n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + n.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "ultra"}); + let art = drawn(&n); + assert!(images(&art).is_empty()); + assert!(faces_bounds(&art).is_some()); +} + +#[test] +fn rendered_warning_reports_the_fallback() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: plain solid"); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + n.appearance.items[0] = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new( + GradientPaint::new(Gradient::new(GradientKind::Linear, stops)), + )))); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "{id}: gradient"); + } + let mut large = Node::path(NodeId(2), square(0.0, 0.0, 100_000.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + large.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &large).as_deref(), Some(TOO_LARGE)); +} + +#[test] +fn rendered_warning_does_not_rasterize() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + let before = RASTERIZATIONS.with(|count| count.get()); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: warning rasterizes"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + assert!(RASTERIZATIONS.with(|count| count.get()) > before, "{id}: drawing rasterizes"); + } +} + +#[test] +fn check_only_reports_rasterizer_limits_after_measure_succeeds() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + let measured = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + let triangles = meshes.iter().map(|m| m.mesh.triangles.len() as u64).sum::(); + let vertices = meshes.iter().map(|m| m.mesh.positions.len() as u64).sum::(); + for limit in ["triangles", "vertices", "work"] { + let mut limits = Limits::default(); + match limit { + "triangles" => limits.max_triangles = triangles - 1, + "vertices" => limits.max_vertices = vertices - 1, + _ => limits.max_work = u64::from(measured.cols) * u64::from(measured.rows), + } + assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits"); + let before = RASTERIZATIONS.with(|count| count.get()); + let checked = check(&meshes, &lighting, settings, 72.0, &limits); + assert_eq!(checked.as_ref().map_err(String::as_str), Err(TOO_LARGE), "{limit}"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{limit}: check rasterizes"); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits).map(|_| ()), checked, "{limit}"); + } +} + +#[test] +fn check_only_counts_shadow_work_and_lights() { + let n = + solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadow": true})); + let (meshes, lighting) = scene_of(&n); + assert!(!lighting.lights.is_empty()); + assert!(lighting.shadows); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + for limit in ["lights", "shadow work"] { + let mut limits = Limits::default(); + if limit == "lights" { + limits.max_lights = 0; + } else { + // The 512-square draft shadow map takes more work than the 100-square image. + limits.max_work = 30_000; + let mut unlit = lighting.clone(); + unlit.shade = false; + assert!(check(&meshes, &unlit, settings, 72.0, &limits).is_ok()); + assert!(render(&meshes, &unlit, settings, 72.0, false, &limits).is_ok()); + // With Shadows off, no shadow map is made, so the same limit fits. + let mut unshadowed = lighting.clone(); + unshadowed.shadows = false; + assert!(check(&meshes, &unshadowed, settings, 72.0, &limits).is_ok()); + assert!(render(&meshes, &unshadowed, settings, 72.0, false, &limits).is_ok()); + } + assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok()); + assert_eq!(check(&meshes, &lighting, settings, 72.0, &limits), Err(TOO_LARGE.into()), "{limit}"); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.into()), "{limit}"); + } +} + +#[test] +fn check_only_art_reports_overlapping_faces_past_the_work_limit() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); + let (mut meshes, lighting) = scene_of(&n); + for p in &mut meshes[0].mesh.positions { + p[0] *= 40.0; + p[1] *= 40.0; + } + let meshes = vec![meshes[0].clone(); 200]; + let settings = RenderSettings { quality: 0, ..MEDIUM }; + assert!(measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).is_ok()); + let before = RASTERIZATIONS.with(|count| count.get()); + assert_eq!(art(None, NodeId(1), &lighting, &meshes, settings, true).map(|_| ()), Err(TOO_LARGE.into())); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &Limits::default()), Err(TOO_LARGE.into())); +} + +/// The page cells (1 pt squares, by their top-left corner) where the rendered image of `n` shows +/// a shadow: covered past alpha 16 outside the bounds of `n`'s shaded faces without a shadow. +fn shadow_cells(n: &Node) -> Vec<(i64, i64)> { + let mut bare = n.clone(); + bare.appearance.effects[0].params["shadow"] = json!(false); + bare.appearance.effects[0].params["render"] = json!({"mode": "shaded"}); + let solid = faces_bounds(&drawn(&bare)).unwrap(); + let list = images(&drawn(n)); + assert_eq!(list.len(), 1, "one image"); + let i = &list[0]; + let decoded = image::load_from_memory(&i.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); + let [sx, _, _, sy, x0, y0] = i.xf.as_coeffs(); + let mut out = vec![]; + for (x, y, p) in decoded.enumerate_pixels() { + let (px, py) = (x0 + (f64::from(x) + 0.5) * sx, y0 + (f64::from(y) + 0.5) * sy); + if p[3] > 16 && !solid.inflate(1.0, 1.0).contains(Point::new(px, py)) { + out.push((px.floor() as i64, py.floor() as i64)); + } + } + out +} + +/// A 100 pt square extruded face-on under two low lights, from the right and from the left, at +/// Intensity `right` and `left` (percent), with Shadows `shadow`, rendered. +fn two_lights(right: f64, left: f64, shadow: bool) -> Node { + solid_square( + super::super::EXTRUDE, + Color::rgb(0.7, 0.7, 0.7), + json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": shadow, + "lights": [{"rotation": 0, "height": 30, "intensity": right}, {"rotation": 180, "height": 30, "intensity": left}], + "render": {"mode": "rendered", "quality": "low"} + }), + ) +} + +/// Rendered with Shadows on, each light casts its own shadow on the shadow plane: two lights from +/// opposite sides darken one region on each side of the solid. With Shadows off neither appears, +/// and a light at Intensity 0 casts none. +#[test] +fn every_light_casts_a_shadow_on_the_plane() { + let center = 150.0; + let sides = |cells: &[(i64, i64)]| { + let left = cells.iter().filter(|c| (c.0 as f64) < center).count(); + (left, cells.len() - left) + }; + let (left, right) = sides(&shadow_cells(&two_lights(100.0, 100.0, true))); + assert!(left > 50 && right > 50, "two lights: {left} shadow cells on the left, {right} on the right"); + let (left, right) = sides(&shadow_cells(&two_lights(100.0, 0.0, true))); + assert!(left > 50, "the light from the right casts {left} cells to the left"); + assert_eq!(right, 0, "the light at Intensity 0 casts {right} cells to the right"); + let (left, right) = sides(&shadow_cells(&two_lights(0.0, 100.0, true))); + assert!(right > 50 && left == 0, "the light from the left alone: {left} left, {right} right"); + assert_eq!(shadow_cells(&two_lights(100.0, 100.0, false)), vec![], "Shadows off"); +} + +/// Full Softness widens the shadow's transition on the plane by several image pixels at both +/// resolutions, including when the image uses multiple samples per pixel. +#[test] +fn softness_widens_the_shadow_edge_on_the_plane() { + for (resolution, quality) in [(72.0, "low"), (144.0, "medium")] { + let transition = |softness| { + let n = solid_square( + super::super::EXTRUDE, + Color::rgb(0.7, 0.7, 0.7), + json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, + "shadow": true, "shadowDistance": 50, "lightHeight": 45, "lightRotation": 0, + "lightIntensity": 100, "lightSoftness": softness, + "render": {"mode": "rendered", "quality": quality, "resolution": resolution} + }), + ); + let list = images(&drawn(&n)); + assert_eq!(list.len(), 1); + let image = &list[0]; + let decoded = image::load_from_memory(&image.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); + let [sx, _, _, sy, x0, y0] = image.xf.as_coeffs(); + let y = ((150.0 - y0) / sy).floor() as u32; + assert!(y < decoded.height()); + let alpha: Vec = + (0..decoded.width()).filter(|x| x0 + (f64::from(*x) + 0.5) * sx < 99.0).map(|x| decoded.get_pixel(x, y)[3]).collect(); + assert!(alpha.contains(&0), "the plane includes an unshadowed region"); + assert!(alpha.iter().any(|a| *a >= 120), "the plane includes a fully shadowed region"); + alpha.iter().filter(|a| **a > 8 && **a < 120).count() + }; + let (hard, soft) = (transition(0), transition(100)); + assert!(soft > hard + (8.0 * resolution / 72.0) as usize, "{resolution} ppi, {quality}: {hard} hard transition pixels, {soft} soft"); + } +} + +/// Measuring the selection with Use Preview Bounds builds the vector art of a rendered 3D object +/// and makes no image; drawing it makes one. +#[test] +fn preview_bounds_do_not_rasterize() { + let mut doc = vectorcraft_doc::Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + for (k, id) in FOUR.into_iter().enumerate() { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + n.id = NodeId(100 + k as u64); + doc.insert(Some(layer), k, n).unwrap(); + } + let ids: Vec = (0..4).map(|k| NodeId(100 + k)).collect(); + let before = RASTERIZATIONS.with(|count| count.get()); + assert!(crate::preview::bounds_of(&doc, &ids, true).is_some()); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "measuring rasterizes"); + for id in &ids { + assert_eq!(images(&drawn(doc.node(*id).unwrap())).len(), 1, "{id:?}"); + } + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before + 4, "drawing rasterizes once for each object"); +} + +/// Painted measurements include the image rectangle under opposite lights without rasterizing, +/// while preview measurements keep the vector art. +#[test] +fn painted_bounds_include_every_lights_shadow_without_rasterizing() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = two_lights(100.0, 100.0, true); + n.appearance.effects[0].id = id.into(); + let before = RASTERIZATIONS.with(|count| count.get()); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + let bounds = measured.visual_bounds().unwrap(); + let measured_images = images(&measured); + assert_eq!(measured_images.len(), 1, "{id}: measures the rendered image"); + assert!(measured_images[0].pixels.is_none(), "{id}: no pixels for measurement"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: measuring rasterizes"); + let drawn_images = images(&drawn(&n)); + assert_eq!(drawn_images.len(), 1, "{id}: draws the rendered image"); + let image = Node::new(n.id, NodeKind::Image(Box::new(drawn_images[0].clone()))).visual_bounds().unwrap(); + assert!(bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1, "{id}: {bounds:?} holds {image:?}"); + let mut bare = n.clone(); + bare.appearance.effects[0].params["shadow"] = json!(false); + let bare = crate::three_d_bounds_art_in(Some(&doc), &bare).unwrap().visual_bounds().unwrap(); + assert!(bounds.x0 < bare.x0 && bounds.x1 > bare.x1, "{id}: shadows extend on both sides"); + let vector = crate::revolve_art_in(Some(&doc), &n).or_else(|| crate::solid_art_in(Some(&doc), &n)).unwrap(); + assert!(images(&vector).is_empty(), "{id}: preview keeps vector art"); + } +} + +/// Drawing the same object again reuses its image; changing its geometry, its material, the +/// resolution or the document's raster resolution makes a new one. +#[test] +fn rendered_images_are_reused_until_an_input_changes() { + let count = || RASTERIZATIONS.with(|count| count.get()); + let base = json!({"render": {"mode": "rendered", "quality": "low"}}); + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), base.clone()); + let doc = |ppi: f64| { + let mut d = vectorcraft_doc::Document::new(400.0, 400.0); + d.raster_effects_ppi = ppi; + d + }; + let draw = |d: &vectorcraft_doc::Document, n: &Node| images(&super::super::solid_art_drawn_in(Some(d), n).unwrap()).len(); + let start = count(); + assert_eq!(draw(&doc(72.0), &n), 1); + assert_eq!(count(), start + 1); + assert_eq!(draw(&doc(72.0), &n), 1); + assert_eq!(count(), start + 1, "a redraw rasterizes again"); + let mut moved = Node::path(NodeId(1), square(130.0, 100.0, 100.0), Appearance::default()); + moved.appearance = n.appearance.clone(); + assert_eq!(draw(&doc(72.0), &moved), 1); + assert_eq!(count(), start + 2, "moving the object reuses the image"); + let mut rough = n.clone(); + rough.appearance.effects[0].params["material"] = json!({"roughness": 0.9}); + assert_eq!(draw(&doc(72.0), &rough), 1); + assert_eq!(count(), start + 3, "a new roughness reuses the image"); + let mut fine = n.clone(); + fine.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "low", "resolution": 144}); + assert_eq!(draw(&doc(72.0), &fine), 1); + assert_eq!(count(), start + 4, "a new resolution reuses the image"); + assert_eq!(draw(&doc(150.0), &n), 1); + assert_eq!(count(), start + 5, "a new document resolution reuses the image"); +} + +/// A group whose 3D effect holds a member with a blending mode or an opacity mask draws the shaded +/// faces, which apply them; without either, the group draws the image. +#[test] +fn masked_or_blended_members_draw_the_shaded_faces() { + for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + let group = |member: Node| { + let mut g = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + g + }; + let member = + || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let art = drawn(&group(member())); + assert_eq!(images(&art).len(), 1, "{id}: plain member"); + let mut blended = member(); + blended.blend = vectorcraft_doc::color::BlendMode::Multiply; + let art = drawn(&group(blended)); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blended member"); + let mut masked = member(); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(), false))); + let art = drawn(&group(masked)); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: masked member"); + } +} + +/// Revolve on a group, or on a fill or stroke, draws the shaded faces and reports why. +#[test] +fn revolve_on_a_group_or_a_paint_reports_objects_only() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let rendered = || crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap(); + let member = || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member())]); + group.appearance.effects.push(rendered()); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OBJECTS_ONLY), "group"); + assert!(images(&drawn(&group)).is_empty(), "group"); + let mut fill = member(); + fill.appearance.items[0].effects_mut().push(rendered()); + assert_eq!(crate::rendered_warning(&doc, &fill).as_deref(), Some(OBJECTS_ONLY), "fill"); + assert!(images(&drawn(&fill)).is_empty(), "fill"); + assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None); +} + +/// Baking a rendered object's appearance, as an envelope with Distort Appearance does, keeps its +/// image, for Revolve and the other 3D effects. +#[test] +fn baked_appearance_keeps_the_rendered_image() { + for id in FOUR { + let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + let baked = crate::bake_appearance(None, &n).unwrap_or_else(|| panic!("{id}: nothing baked")); + assert_eq!(images(&baked).len(), 1, "{id}: the baked appearance has no image"); + } +} + +/// The page point the clip matrix `m` takes mesh point `p` to over image `rect`: the point goes +/// into the scene's frame (y down), through `m`, and from the image's normalized coordinates onto +/// the page. +fn clipped(m: [[f32; 4]; 4], rect: Rect, p: [f64; 3]) -> Point { + let v = [p[0], -p[1], p[2], 1.0]; + let row = |r: usize| (0..4).map(|c| f64::from(m[r][c]) * v[c]).sum::(); + let w = row(3); + let (x, y) = (row(0) / w, row(1) / w); + Point::new(rect.x0 + (x + 1.0) / 2.0 * rect.width(), rect.y0 + (1.0 - y) / 2.0 * rect.height()) +} + +/// The scene's clip matrix places every mesh point where the effect's projection draws it, within +/// 1e-3 pt, for each of the four effects without perspective and at 60 and 160 degrees. +#[test] +fn the_clip_matrix_places_every_mesh_point_where_the_projection_does() { + for id in FOUR { + for perspective in [0.0, 60.0, 160.0] { + let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": perspective})); + let (meshes, lighting) = scene_of(&n); + let m = measure(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap_or_else(|e| panic!("{id} {perspective}: {e}")); + let mut worst = 0.0f64; + for p in meshes.iter().flat_map(|s| &s.mesh.positions) { + worst = worst.max(clipped(m.clip, m.rect, *p).distance(m.projection.project(*p))); + } + assert!(worst < 1e-3, "{id} at {perspective} degrees: a mesh point lands {worst} pt from its projected point"); + } + } +} + +/// A square facing the viewer covers every pixel more than one pixel inside its outline and none +/// more than one pixel outside it. +#[test] +fn the_image_covers_the_area_the_faces_cover() { + let n = solid_square(super::super::ROTATE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let face = faces_bounds(&super::super::solid_art_in(None, &n).unwrap()).unwrap(); + let (mut inside, mut outside) = (0, 0); + for y in 0..image.rows { + for x in 0..image.cols { + let center = Point::new(image.rect.x0 + f64::from(x) + 0.5, image.rect.y0 + f64::from(y) + 0.5); + let a = pixel(&image, x, y)[3]; + if face.inset(-1.0).contains(center) { + inside += 1; + assert_eq!(a, 255, "pixel {x}, {y} inside the face"); + } else if !face.inset(1.0).contains(center) { + outside += 1; + assert_eq!(a, 0, "pixel {x}, {y} outside the face"); + } + } + } + assert!(inside > 9000, "{inside} pixels inside"); + assert!(outside + inside > 0); +} + +/// The depth buffer decides which surface shows: with the mesh's triangles in reverse order, every +/// pixel inside the turned solid shows the same surface. +#[test] +fn the_nearer_surface_shows_whatever_order_the_triangles_come_in() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 40, "rotationY": 50, "rotationZ": 0, "shade": true})); + let (meshes, lighting) = scene_of(&n); + let mut reversed = meshes.clone(); + for m in &mut reversed { + m.mesh.triangles.reverse(); + } + let a = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let b = render(&reversed, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + assert_eq!((a.cols, a.rows), (b.cols, b.rows)); + let differ = a + .pixels + .chunks(4) + .zip(b.pixels.chunks(4)) + .filter(|(p, q)| p[3] == 255 && q[3] == 255 && p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 2)) + .count(); + let covered = a.pixels.chunks(4).filter(|p| p[3] == 255).count(); + assert!(covered > 5000, "{covered}"); + assert!(differ * 100 <= covered, "{differ} of {covered} covered pixels change with the triangle order"); +} + +/// Cook-Torrance with GGX, Smith-Schlick `k = (r + 1)² / 8` and Schlick's Fresnel, times N·L, for +/// linear base color `base`, `metallic` and `rough` along unit normal `n`, view `v` and light `l`. +fn cook_torrance(base: f64, metallic: f64, rough: f64, n: [f64; 3], v: [f64; 3], l: [f64; 3]) -> f64 { + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let h = [v[0] + l[0], v[1] + l[1], v[2] + l[2]]; + let len = dot(h, h).sqrt(); + let h = h.map(|c| c / len); + let (n_l, n_v, n_h, v_h) = (dot(n, l), dot(n, v), dot(n, h), dot(v, h)); + let a2 = (rough * rough).powi(2); + let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2)); + let k = (rough + 1.0).powi(2) / 8.0; + let g = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)); + let f0 = 0.04 * (1.0 - metallic) + base * metallic; + let f = f0 + (1.0 - f0) * (1.0 - v_h).powi(5); + let spec = d * g / (4.0 * n_v * n_l); + let kd = (1.0 - f) * (1.0 - metallic); + (kd * base / std::f64::consts::PI + f * spec) * n_l * std::f64::consts::PI +} + +/// A face toward the viewer under one light at 45 degrees, Ambient 0, Roughness 0.5, Metallic 0 +/// and 1: its center equals the Cook-Torrance formula times the light's color, within 1e-3 linear. +#[test] +fn a_lit_face_matches_the_shading_formula() { + for metallic in [0.0, 1.0] { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.5, 0.5, 0.5), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 45, "lightIntensity": 100, "ambient": 0, + "material": {"roughness": 0.5, "metallic": metallic}}), + ); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + let scene = scene(&meshes, &lighting, m.projection, m.z, m.clip, (m.cols, m.rows), f64::from(m.cols) / m.rect.width()).unwrap(); + assert_eq!(scene.lights.len(), 1); + let light = &scene.lights[0]; + let target = craft_raster3d::try_render(&scene, &Limits::default()).unwrap(); + let got = target.color[(m.rows / 2 * m.cols + m.cols / 2) as usize]; + let l = light.dir.map(|c| -f64::from(c)); + let base = f64::from(srgb_to_linear(0.5)); + let want = cook_torrance(base, metallic, 0.5, [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], l) * f64::from(light.color[0]); + assert!((f64::from(got[0]) - want).abs() < 1e-3, "metallic {metallic}: {} against {want}", got[0]); + assert_eq!(got[3], 1.0); + } +} + +/// With the default light, Ambient 0, the default material and Softness 0, a face square to the +/// light has the color of the same shaded face within 3 levels. +#[test] +fn a_face_square_to_the_light_has_the_shaded_faces_color() { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.2, 0.5, 0.8), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "ambient": 0, "lightSoftness": 0}), + ); + let mut face = None; + super::super::solid_art_in(None, &n).unwrap().walk(&mut |c| { + if c.path_data().is_some() + && let Some(Paint::Solid { color, .. }) = c.appearance.items.iter().map(|i| i.paint()).find(|p| matches!(p, Paint::Solid { .. })) + { + face.get_or_insert(color.to_rgba8(1.0)); + } + }); + let face = face.unwrap(); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + for c in 0..3 { + assert!(center[c].abs_diff(face[c]) <= 3, "{center:?} against the shaded face's {face:?}"); + } +} + +/// The specular term of the shaded faces (the separable Smith visibility of glTF 2.0) and of the +/// rendered image (Smith-Schlick with `k = (r + 1)² / 8`) differ by at most 0.002 of the light over +/// Roughness 0.05 to 1 and light angles of 0 to 80 degrees from the normal, at a view along it. +#[test] +fn the_two_specular_terms_differ_within_a_bound() { + let mut worst = (0.0f64, 0.0, 0.0); + for r in (1..=20).map(|i| f64::from(i) * 0.05) { + for degrees in (0..=8).map(|i| f64::from(i) * 10.0) { + let t = degrees.to_radians(); + let (n_l, n_v) = (t.cos(), 1.0); + let h_len = (2.0 + 2.0 * n_l).sqrt(); + let n_h = (1.0 + n_l) / h_len; + let a2 = (r * r).powi(2); + let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2)); + let k = (r + 1.0).powi(2) / 8.0; + let schlick = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)) / (4.0 * n_v * n_l); + let one = |x: f64| x + (a2 + (1.0 - a2) * x * x).sqrt(); + let separable = 1.0 / (one(n_l) * one(n_v)); + // F0 0.04, the dielectric default, at the half vector. + let v_h = h_len / 2.0; + let f = 0.04 + 0.96 * (1.0 - v_h).powi(5); + let diff = (d * f * (schlick - separable) * n_l * std::f64::consts::PI).abs(); + if diff > worst.0 { + worst = (diff, r, degrees); + } + } + } + println!("largest specular difference {:.4} at roughness {:.2}, {} degrees", worst.0, worst.1, worst.2); + assert!(worst.0 <= 0.002, "{worst:?}"); +} + +/// An image past the pixel limit at one sample a pixel draws the shaded faces and reports why; the +/// largest mesh the effects make fits the rasterizer's triangle limit. +#[test] +fn an_image_past_the_limits_draws_the_shaded_faces() { + assert!(super::super::MAX_MESH_TRIANGLES as u64 <= Limits::default().max_triangles); + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut n = Node::path(NodeId(1), square(0.0, 0.0, 3000.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + n.appearance + .effects + .push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "quality": "low", "resolution": 2400}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(TOO_LARGE)); + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some()); +} + +/// Rendering a 40 × 80 pt Extrude at 300 ppi, Medium (2 × 2 samples), fits a work limit of twice +/// the samples its triangles' bounding boxes cover plus one for each triangle, and a limit of half +/// those samples is refused. +#[test] +fn a_medium_render_stays_within_its_work_bound() { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40.0, 0.0)); + b.line_to((40.0, 80.0)); + b.line_to((0.0, 80.0)); + b.close_path(); + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "resolution": 300}})).unwrap()); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 1, resolution: Some(300.0), white: false }; + let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + assert_eq!(m.samples, 2); + let samples = u64::from(m.cols) * u64::from(m.rows) * 4; + // Each triangle's bounding box in raster samples, clipped to the raster. + let per_point = f64::from(m.cols * 2) / m.rect.width(); + let mut boxes = 0u64; + let mut triangles = 0u64; + for s in &meshes { + for t in &s.mesh.triangles { + let at: Vec = t.iter().map(|&i| m.projection.project(s.mesh.positions[i as usize])).collect(); + let span = |f: fn(&Point) -> f64, origin: f64, size: f64| { + let lo = at.iter().map(f).fold(f64::INFINITY, f64::min); + let hi = at.iter().map(f).fold(f64::NEG_INFINITY, f64::max); + (((hi - origin) * per_point).ceil().min(size) - ((lo - origin) * per_point).floor().max(0.0) + 1.0).max(0.0) as u64 + }; + boxes += span(|p| p.x, m.rect.x0, f64::from(m.cols * 2)) * span(|p| p.y, m.rect.y0, f64::from(m.rows * 2)); + triangles += 1; + } + } + let mut limits = Limits::default(); + limits.max_work = 2 * boxes + triangles; + assert!(render(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{samples} samples, {boxes} box samples, {triangles} triangles"); + limits.max_work = boxes / 2; + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.to_string()), "the work is counted"); + println!("work bound: {samples} image samples, {boxes} box samples, {triangles} triangles"); +} + +/// Edge values: art with no area makes no image, a mesh with zero-area triangles renders, lights +/// with values that are not numbers are refused, resolutions 1 and 2400 render, and a solid behind +/// the eye at Perspective 160 is refused. +#[test] +fn edge_values_render_or_are_refused() { + let mut empty = Node::path(NodeId(1), PathData::from_bezpath(&BezPath::new()), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + empty.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert!(super::super::solid_art_drawn_in(None, &empty).is_none_or(|a| images(&a).is_empty())); + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (mut meshes, mut lighting) = scene_of(&n); + let first = meshes[0].mesh.triangles[0]; + meshes[0].mesh.triangles.push([first[0], first[0], first[1]]); + assert!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).is_ok(), "zero-area triangle"); + for resolution in [1.0, 2400.0] { + let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false }; + let image = render(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + assert!(image.cols >= 1 && image.rows >= 1, "{resolution} ppi"); + } + lighting.lights[0].intensity = f64::NAN; + lighting.lights[0].rotation = f64::INFINITY; + let bad = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()); + assert!(matches!(bad.as_ref().map_err(String::as_str), Ok(_) | Err(TOO_LARGE)), "{bad:?}"); + let behind = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": 160})); + let (mut meshes, lighting) = scene_of(&behind); + let eye = meshes[0].projection.and_then(|p| p.eye).unwrap(); + meshes[0].mesh.positions[0][2] = eye * 2.0; + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); +} diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 7b84214d29..dbdfbb9c30 100644 --- a/crates/effects/src/solids/shadow.rs +++ b/crates/effects/src/solids/shadow.rs @@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option { let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity); let lit = flag(p, "shade", true) && intensity > 0.0; - (lit && flag(p, "shadow", false)).then(|| Shadow { + (lit && flag(p, "shadow", false)).then(|| settings(p, first)) +} + +/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on +/// when any light lights the art (`lit`), not only the first. +pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option { + let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); + (lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first)) +} + +/// The plane settings of `p`, with the softness of light `first` (the single light's without one). +fn settings(p: &Value, first: Option) -> Shadow { + Shadow { position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(), distance: num(p, "shadowDistance", 0.0) / 100.0, bounds: num(p, "shadowBounds", 100.0) / 100.0, softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness), - }) + } } /// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind. diff --git a/crates/effects/src/solids/tests_material.rs b/crates/effects/src/solids/tests_material.rs index 1c7141dc8d..17f1878fa9 100644 --- a/crates/effects/src/solids/tests_material.rs +++ b/crates/effects/src/solids/tests_material.rs @@ -398,5 +398,7 @@ fn meshes_carry_the_material() { let mut n = square_node(); let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") }; n.appearance.effects.push(fx); - assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default())); + let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("extrude: {e}")); + assert!(!meshes.is_empty(), "extrude"); + assert!(meshes.iter().all(|m| m.material.is_default())); } diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 12ab29423f..8170a3bfa7 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() let (path, rule) = profile(&n).unwrap(); vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] }; - let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap(); + let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap(); let p = crate::merged_params(&fx.id, &fx.params); let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 3c1b3f1f2e..9ad0597c5c 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -21,12 +21,84 @@ use crate::{GeomContext, is_geometry}; pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; /// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of -/// [`RENDER_MODES`]. +/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and +/// `background` ([`RENDER_BACKGROUNDS`]). pub const RENDER: &str = "render"; /// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every -/// face ([`renders_wireframe`]). -pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"]; +/// face ([`renders_wireframe`]), and `rendered` an image of the lit solid with the shadows of its +/// lights ([`render_settings`]). +pub const RENDER_MODES: [&str; 3] = ["shaded", "wireframe", "rendered"]; + +/// The qualities of the rendered image, from fastest to finest: 1, 2 × 2 and 3 × 3 samples a pixel +/// ([`RenderSettings::samples`]). VectorCraft's own values. +pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"]; + +/// What the rendered image shows where no surface is: nothing, or white. +pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"]; + +/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own +/// default). +const DEFAULT_QUALITY: usize = 1; + +/// The settings of a 3D effect's rendered image ([`render_settings`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RenderSettings { + /// The quality, as an index into [`RENDER_QUALITIES`] (0 low, 1 medium, 2 high). + pub quality: usize, + /// Pixels per inch, 1 to 2400; `None` takes Document Raster Effects Settings › Resolution. + pub resolution: Option, + /// A white background, which makes the image opaque; otherwise it is transparent where no + /// surface or shadow is. + pub white: bool, +} + +impl RenderSettings { + /// The samples a pixel takes along each side at this quality: 1, 2 or 3. + pub fn samples(&self) -> u32 { + self.quality.min(2) as u32 + 1 + } +} + +/// The settings of the image 3D effect `id` with parameters `p` draws, when its `render` passes +/// [`validate_render`] and sets `mode` to `rendered`; `None` otherwise, when the effect draws its +/// shaded faces or its wireframe (a loaded file whose `render` breaks the rules draws shaded). +pub fn render_settings(id: &str, p: &Value) -> Option { + let render = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id))?; + if check_render(render).is_err() || render.get("mode").and_then(Value::as_str) != Some("rendered") { + return None; + } + let quality = render.get("quality").and_then(Value::as_str).and_then(|q| RENDER_QUALITIES.iter().position(|k| *k == q)); + Some(RenderSettings { + quality: quality.unwrap_or(DEFAULT_QUALITY), + resolution: render.get("resolution").and_then(Value::as_f64), + white: render.get("background").and_then(Value::as_str) == Some("white"), + }) +} + +/// Does effect `fx` draw as a rendered image ([`render_settings`])? +pub fn renders_image(fx: &Effect) -> bool { + render_settings(&fx.id, &fx.params).is_some() +} + +/// The message a `render` that breaks the rules of [`validate_render`] is refused with. +const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \ + resolution (null or a number from 1 to 2400) and background (transparent or white)"; + +/// Check one `render` value against [`RENDER_RULES`]. +fn check_render(render: &Value) -> Result<(), String> { + let one_of = |v: &Value, list: &[&str]| v.as_str().is_some_and(|s| list.contains(&s)); + let valid = render.as_object().is_some_and(|fields| { + fields.iter().all(|(key, value)| match key.as_str() { + "mode" => one_of(value, &RENDER_MODES), + "quality" => one_of(value, &RENDER_QUALITIES), + "background" => one_of(value, &RENDER_BACKGROUNDS), + "resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)), + _ => false, + }) + }); + if valid { Ok(()) } else { Err(RENDER_RULES.into()) } +} /// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve, /// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface. @@ -50,17 +122,14 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool { } /// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the -/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a -/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take. +/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]), +/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels +/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default: +/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic) +/// effects refuse it as a parameter they do not take. pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> { let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) }; - let valid = render - .as_object() - .is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m)))); - if !valid { - return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into()); - } - Ok(()) + check_render(render) } /// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index b20d0fedf0..f99be96a94 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -418,12 +418,23 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() { assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT))); } -/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and -/// only on the panel's four effects. +/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or +/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background` +/// (transparent or white), and only on the panel's four effects. #[test] fn render_settings_are_validated() { for id in WIRE { - for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] { + for good in [ + json!({}), + json!({"render": {}}), + json!({"render": {"mode": "shaded"}}), + json!({"render": {"mode": "wireframe"}}), + json!({"render": {"mode": "rendered"}}), + json!({"render": {"mode": "rendered", "quality": "high", "resolution": 300, "background": "white"}}), + json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}), + json!({"render": {"resolution": 1}}), + json!({"render": {"resolution": 2400}}), + ] { assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}"); } for bad in [ @@ -431,10 +442,20 @@ fn render_settings_are_validated() { json!({"render": null}), json!({"render": {"mode": "raytrace"}}), json!({"render": {"mode": true}}), - json!({"render": {"mode": "wireframe", "quality": "high"}}), + json!({"render": {"mode": "rendered", "quality": "ultra"}}), + json!({"render": {"mode": "rendered", "resolution": 0.5}}), + json!({"render": {"mode": "rendered", "resolution": 2401}}), + json!({"render": {"mode": "rendered", "resolution": "300"}}), + json!({"render": {"mode": "rendered", "background": "black"}}), + json!({"render": {"mode": "rendered", "samples": 4}}), ] { let e = crate::validate_three_d_params(id, &bad).unwrap_err(); - assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}"); + assert_eq!( + e, + "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \ + or a number from 1 to 2400) and background (transparent or white)", + "{id} {bad}" + ); } // The command check on the object refuses it too. let n = solid_square(id, json!({})); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fe4f7d10e..2487dcd01d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -114,6 +114,8 @@ apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] } zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] } [dev-dependencies] +# DWG files for the `.dwg` open and place tests, written from DXF by craft-dwg. +craft-dwg = { workspace = true } # JPEG XL files for the `.jxl` open and place tests. zune-jpegxl = { workspace = true } zune-core = { workspace = true } diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index ec18bbccd1..ab7a3808ce 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -8,10 +8,12 @@ //! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their //! visual bounds share, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object. +//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object, +//! and Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]). //! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view //! command) are the UI's. +mod artboard_guides; pub mod marks; #[cfg(test)] mod tests; @@ -31,8 +33,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, 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; @@ -75,7 +77,7 @@ pub fn specs() -> Vec { "Swap Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", + "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", exactly_two, swap ), @@ -84,7 +86,7 @@ pub fn specs() -> Vec { "Replace with Top Object", ["Object", "Plug-ins", "Arrange Tools"], None, - "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", + "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", has_multi, replace ), @@ -93,7 +95,7 @@ pub fn specs() -> Vec { "Set Size of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", + "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", has_selection, size ), @@ -102,7 +104,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, 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, and a size that a target has no width or height to take 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 ), @@ -138,12 +140,13 @@ pub fn specs() -> Vec { "Sort Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), corners?: the Scale Corners preference, ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", has_multi, sort ), ] .into_iter() + .chain(artboard_guides::specs()) .chain(marks::specs()) .collect() } @@ -173,10 +176,10 @@ fn size_param(p: &Value, key: &str, cmd: &str) -> Result> { p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose() } -/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes` -/// and, when given, a width and height. -fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { - let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes }); +/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`, +/// Scale Corners `corners` and, when given, a width and height. +fn place(at: Point, size: Option<(f64, f64)>, strokes: bool, corners: bool) -> Value { + let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes, "corners": corners }); if let Some((w, h)) = size { q["width"] = json!(w); q["height"] = json!(h); @@ -185,14 +188,15 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { } /// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects -/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. -/// When every transform is (within rounding) the identity, nothing changes. -fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { +/// scaling with Scale Strokes & Effects `strokes`, corners with Scale Corners `corners`, pattern +/// tiles as the command's params `p` or Transform Pattern Tiles say. When every transform is +/// (within rounding) the identity, nothing changes. +fn transform_each(s: &mut Session, label: &str, p: &Value, strokes: bool, corners: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); if xfs.iter().all(|(_, xf)| still(xf)) { return Ok(()); } - let p = json!({ "strokes": strokes }); + let p = scaling_params(p, strokes, corners); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &ids)?; @@ -206,6 +210,17 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A }) } +/// The params [`scaling`] and [`transform_patterns`] read: Scale Strokes & Effects `strokes`, Scale +/// Corners `corners`, and the `patterns` value of the command's params `p`. That one is absent on a +/// first run, which takes the preference, and present when its journal entry is replayed. +fn scaling_params(p: &Value, strokes: bool, corners: bool) -> Value { + let mut q = json!({ "strokes": strokes, "corners": corners }); + if let Some(v) = p.get("patterns").filter(|v| v.is_boolean()) { + q["patterns"] = v.clone(); + } + q +} + /// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the /// command's journal entry, so replaying it scales the same way whatever the preference is then. fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { @@ -214,6 +229,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { Ok(on) } +/// The `corners` value of a replayed journal entry, else the Scale Corners preference. The value +/// joins the command's journal entry, so replaying it scales corners the same way. +fn scale_corners(s: &mut Session, p: &Value, cmd: &str) -> Result { + let on = switch_or(p, "corners", s.prefs.scale_corners, cmd)?; + s.note_journal("corners", json!(on)); + Ok(on) +} + /// The box of object `id` as `object.setBounds` measures it. fn box_of(s: &Session, id: NodeId) -> Result { s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) @@ -271,7 +294,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { .enumerate() .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) .collect(); - transform_each(s, "Arrange in Grid", false, &xfs)?; + transform_each(s, "Arrange in Grid", p, false, s.prefs.scale_corners, &xfs)?; Ok(json!({ "count": n })) } @@ -308,7 +331,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { if !moves { return Ok(json!({ "count": items.len() })); } - let p = json!({ "strokes": false }); + let p = scaling_params(p, false, s.prefs.scale_corners); let ids: Vec = items.iter().map(|(id, _, _)| *id).collect(); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &ids)?; @@ -362,12 +385,13 @@ fn swap(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.swap"; let size = switch_or(p, "size", false, C)?; let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let roots = selected_roots(s)?; let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); - let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes, corners); let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; - transform_each(s, "Swap Objects", strokes, &xfs)?; + transform_each(s, "Swap Objects", p, strokes, corners, &xfs)?; Ok(json!({})) } @@ -375,6 +399,7 @@ fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.replace"; let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let keep = switch_or(p, "keep", false, C)?; let roots = selected_roots(s)?; let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { @@ -394,9 +419,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { } _ => None, }; - xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes, corners), top)?)); } - let p = json!({ "strokes": strokes }); + let p = scaling_params(p, strokes, corners); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &[top])?; let ids = s.edit("Replace with Top Object", |d, sel| { @@ -426,7 +451,8 @@ fn size(s: &mut Session, p: &Value) -> Result { let proportional = switch_or(p, "proportional", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; - let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + let corners = scale_corners(s, p, C)?; + let mut q = json!({ "reference": reference, "strokes": strokes, "corners": corners, "proportional": proportional && (width.is_none() || height.is_none()) }); if let Some(w) = width { q["width"] = json!(w); } @@ -439,7 +465,7 @@ fn size(s: &mut Session, p: &Value) -> Result { xfs.push((id, object_bounds_transform(s, &q, id)?)); } } - transform_each(s, "Set Size of Each", strokes, &xfs)?; + transform_each(s, "Set Size of Each", p, strokes, corners, &xfs)?; Ok(json!({ "count": xfs.len() })) } @@ -471,6 +497,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let stacking = switch_or(p, "stacking", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?; if size == "none" && !rotate && !stacking { return Err(bad(C, "give `size`, `rotate` or `stacking`")); @@ -502,6 +529,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 { @@ -518,36 +550,29 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let mut q = q.clone(); q["reference"] = json!(reference); q["strokes"] = json!(strokes); - xf = object_bounds_transform(s, &q, id)?; + q["corners"] = json!(corners); + // Any scale the source's size asks for, however small. + xf = object_bounds_transform_keeping(s, &q, id, 0.0)?; } + // Rotation and the fit below keep the reference point in place. + let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + let turned = Affine::rotate_about(-turn.to_radians(), at); if turn.abs() > 1e-9 { - // Rotation uses the reference point that sizing keeps in place. - let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); - xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + 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 sc = scaling(s, &json!({ "strokes": strokes })); - let d = &s.doc()?.doc; - let symbols = d.symbol_boxes(); - let measure = |xf| { - d.node(id).and_then(|n| { - let mut n = n.clone(); - transform_node(&mut n, xf, sc, true); - let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO }; - effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure()) - }) - }; - let misses = |measured: Option| { - measured.is_none_or(|r| match size { - "width" => (r.width() - w).abs() > 1e-6, - "height" => (r.height() - h).abs() > 1e-6, - _ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6, - }) - }; - // The sized and turned object, measured in its final frame, must have the size asked for. - if misses(measure(xf)) { - return Err(bad(C, format!("object {} can't take the requested size", id.0))); - } + let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners }; + xf = fit_turned(s, id, (xf, turned), fit).ok_or_else(|| bad(C, format!("object {} can't take the requested size", id.0)))?; } xfs.push((id, xf)); } @@ -564,6 +589,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"))); } @@ -574,15 +625,30 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { if xfs.is_empty() && !restack { return Ok(count); } - let q = json!({ "strokes": strokes, "patterns": patterns }); + let q = json!({ "strokes": strokes, "corners": corners, "patterns": patterns }); 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)?; @@ -590,11 +656,113 @@ 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) } +/// The size a target of Match Objects ends with: for `size` "width" ("height") the source's width +/// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the +/// source's width and height. +fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] { + let follow = |side: f64, from: f64, to: f64| if from > 0.0 { side * to / from } else { side }; + match size { + "width" => [w, follow(b.height(), b.width(), w)], + "height" => [follow(b.width(), b.height(), h), h], + _ => [w, h], + } +} + +/// What [`fit_turned`] fits a target of Match Objects to. +struct Fit { + /// The target's reference point, which stays in place. + at: Point, + /// That point's index on the 9-point grid. + refi: usize, + /// The width and height wanted ([`match_goal`]). + goal: [f64; 2], + /// Scale Strokes & Effects. + strokes: bool, + /// Scale Corners. + corners: bool, +} + +/// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within +/// 1e-9 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object +/// ends in. When it misses, for example when a stroke or an effect does not turn with the art, +/// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone, +/// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to +/// Pixel Grid snaps it, as every transform snaps it after. `None` when no scale gives the size. +fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: Fit) -> Option { + let Fit { at, refi, goal, strokes, corners } = fit; + let sc = scaling(s, &json!({ "strokes": strokes, "corners": corners })); + let how = s.bounds_measure(); + let d = &s.doc().ok()?.doc; + let symbols = d.symbol_boxes(); + let n = d.node(id)?; + let moved = |xf: Affine| { + let mut n = n.clone(); + n.transform(xf, sc); + n + }; + // The angle the object's box ends at after `xf`, as `Node::transform` sets it (a layer keeps its own). + let angle_after = |xf: Affine| if n.is_layer() { n.bbox_angle } else { vectorcraft_doc::orient::transformed_angle(n.bbox_angle, xf) }; + // The frame the turn gives; sizing can leave the art without a width or a height to show it. + let frame = OrientedBox { angle: angle_after(turned), rect: Rect::ZERO }; + let to_local = frame.to_doc().inverse(); + let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how); + let tolerances = goal.map(|side| 1e-9 * side.max(1.0)); + let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t); + let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(angle_after(xf) - frame.angle).abs() <= 1e-6; + let rp = frame.to_local(at); + // The object turned by `turned`, then scaled by `sx` and `sy` in the frame about the reference point. + let scaled = |sx: f64, sy: f64| { + frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned + }; + // `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke + // or an effect that does not turn with the art moves it. + let placed = |xf: Affine| -> Option<(Affine, Rect)> { + let b = measure(xf)?; + let correction = rp - vectorcraft_geom::reference_point(b, refi); + if correction.x.abs() <= 1e-12 && correction.y.abs() <= 1e-12 { + return Some((xf, b)); + } + let xf = frame.conjugate(Affine::translate(correction)) * xf; + Some((xf, measure(xf)?)) + }; + let accepts = |xf: Affine, b: Rect| fits(b) && keeps_angle(xf); + if let Some((xf, _)) = placed(xf).filter(|(xf, b)| accepts(*xf, *b)) { + return Some(xf); + } + // The sizing above can leave the art without a width or a height that the turned object needs, + // so the fit starts again from the object as it is, turned. + let now = measure(turned)?; + let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 }; + let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height())); + let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?; + placed(scaled(sx, sy)).filter(|(xf, b)| accepts(*xf, *b)).map(|(xf, _)| xf) +} + /// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, /// chains included, among items of the same key (parent). A sweep along x: only the rects still /// open where each one starts are compared with it. @@ -841,6 +1009,7 @@ fn sort(s: &mut Session, p: &Value) -> Result { let distribute = switch_or(p, "distribute", false, C)?; let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let ids = checked_ids_or_selection(s, p, C)?; if ids.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); @@ -923,17 +1092,17 @@ fn sort(s: &mut Session, p: &Value) -> Result { let q = match apply { "x" => json!({ "x": v, "reference": 0 }), "y" => json!({ "y": v, "reference": 0 }), - "width" => json!({ "width": v, "strokes": strokes }), - "height" => json!({ "height": v, "strokes": strokes }), + "width" => json!({ "width": v, "strokes": strokes, "corners": corners }), + "height" => json!({ "height": v, "strokes": strokes, "corners": corners }), // An area: both sides in proportion; an object without one keeps its size. _ => { let (w, h) = (o.b.rect.width(), o.b.rect.height()); let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 }; - json!({ "width": w * k, "height": h * k, "strokes": strokes }) + json!({ "width": w * k, "height": h * k, "strokes": strokes, "corners": corners }) } }; xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); } - transform_each(s, "Sort Objects", strokes, &xfs)?; + transform_each(s, "Sort Objects", p, strokes, corners, &xfs)?; Ok(count) } diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs new file mode 100644 index 0000000000..d849047fb9 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -0,0 +1,202 @@ +//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen +//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named +//! Artboard Guides. Its dialog is the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; + +use super::super::super::panelcmds::{artboard_at, listed_artboards}; +use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; +use super::{LIMIT, number_in}; +use crate::sanity::rect_in_range; +use crate::{DocState, Result, Session}; + +/// The command. +pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides"; +/// The top-level layer the guides go on, made when the document has none of that name. +pub(crate) const LAYER: &str = "Artboard Guides"; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.arrange.artboardGuides", + "Add Artboard Guides", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}", + has_artboards, + artboard_guides + )] +} + +/// A document with at least one artboard is open. +fn has_artboards(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) } +} + +/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no +/// longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &DocState) -> usize { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0) +} + +/// The topmost top-level layer named [`LAYER`]. +fn guide_layer(d: &Document) -> Option { + d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) +} + +/// `r`'s corners as an exact hash key, whichever way round `r` runs. +fn rect_key(r: Rect) -> [u64; 4] { + let r = r.abs(); + [r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() }) +} + +#[cfg(test)] +thread_local! { + static GUIDE_NODES_VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { + let mut rects = HashSet::new(); + if let Some(n) = layer.and_then(|id| d.node(id)) { + n.walk(&mut |c| { + #[cfg(test)] + GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1)); + // The anchors' bounds: `traces` only accepts segments that stay between their anchors. + if let NodeKind::Path { path, guide: true, .. } = &c.kind + && let [sp] = &path.subpaths[..] + && let Some(first) = sp.anchors.first() + { + let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p)); + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + if traces(path, &corners) { + rects.insert(rect_key(r)); + } + } + }); + } + rects +} + +/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b` +/// without turning back? Its handles lie on that line, and the curve's position along it never reverses. +fn straight(a: &Anchor, b: &Anchor) -> bool { + let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| { + if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) { + return false; + } + let s = (f(b.p) - f(a.p)).signum(); + let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s); + // The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1]. + let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2); + let curve = u - 2.0 * v + w; + let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 }; + u >= 0.0 && w >= 0.0 && vertex >= 0.0 + }; + if a.p == b.p { + return a.h_out == a.p && b.h_in == a.p; + } + along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x) +} + +/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? +fn traces(path: &PathData, corners: &[Point; 4]) -> bool { + let [sp] = &path.subpaths[..] else { return false }; + if !sp.closed || sp.anchors.len() < 4 { + return false; + } + let n = sp.anchors.len(); + if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) { + return false; + } + let points: Vec = sp + .anchors + .iter() + .enumerate() + .filter_map(|(i, a)| { + let prev = sp.anchors[(i + sp.anchors.len() - 1) % sp.anchors.len()].p; + let next = sp.anchors[(i + 1) % sp.anchors.len()].p; + let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y)) + || (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x)); + (!interior).then_some(a.p) + }) + .collect(); + let [first, second, _, _] = &points[..] else { return false }; + let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else { + return false; + }; + // 1 runs the way `corners` does, 3 the other way. + let step = (next + 4 - start) % 4; + (step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4]) +} + +fn artboard_guides(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?; + let all = switch_or(p, "all", false, C)?; + let listed = p.get("artboards").filter(|v| !v.is_null()); + if all && listed.is_some() { + return Err(bad(C, "give `all` or `artboards`, not both")); + } + let st = s.doc()?; + let d = &st.doc; + if d.artboards.is_empty() { + return Err(bad(C, "the document has no artboards")); + } + // The active artboard: the one the app passes, else the view's, recorded for a replay. + let active = artboard_at(d, p, "artboard", C)?; + let indices: Vec = match listed { + Some(v) => listed_artboards(d, v, "artboards", C)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![active.unwrap_or_else(|| active_artboard(st))], + }; + if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) { + s.note_journal("artboard", json!(i)); + } + let st = s.doc()?; + let d = &st.doc; + let layer = guide_layer(d); + let mut existing = guide_rectangles(d, layer); + let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0); + for i in indices { + let Some(board) = d.artboards.get(i) else { continue }; + let r = board.rect.inflate(offset, offset); + if !(r.width() > 0.0 && r.height() > 0.0) { + return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name))); + } + if !rect_in_range(r) { + return Err(bad(C, "the guide would reach past the edge of the canvas")); + } + if !existing.insert(rect_key(r)) { + skipped += 1; + } else { + rects.push(r); + } + } + if rects.is_empty() { + return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped })); + } + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let (layer, ids) = s.edit("Add Artboard Guides", |d, _| { + let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER))); + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default()); + look.apply(d, &mut n); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + Ok((layer, ids)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs new file mode 100644 index 0000000000..5152dcffe9 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -0,0 +1,312 @@ +//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer +//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused +//! without a change. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::{COMMAND, LAYER}; +use crate::Session; + +/// A new document with one 400 × 300 pt artboard and a second one beside it. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn board(s: &Session, i: usize) -> Rect { + s.doc().unwrap().doc.artboards[i].rect +} + +fn ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() +} + +/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`. +fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect { + let d = &s.doc().unwrap().doc; + let n = d.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path"); + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer"); + n.geometric_bounds().unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +#[test] +fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() { + let mut s = session(); + let n = steps(&s); + let before = layer_names(&s); + let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let layer = NodeId(r["layer"].as_u64().unwrap()); + assert_eq!(r["skipped"], json!(0)); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + // The active artboard is the first when the view has not picked one. + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id)); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others"); + assert_eq!(d.layers.last().unwrap().display_name(), LAYER); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide"); +} + +#[test] +fn the_active_artboard_is_the_one_the_view_keeps() { + let mut s = session(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges"); + assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay"); + // The artboard the app passes wins over the view's. + let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0))); + assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard"); +} + +#[test] +fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() { + let mut s = session(); + let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap(); + let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s)); + let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for every artboard"); + assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused"); + assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added"); + let added = ids(&r); + assert_eq!(added.len(), 2); + for (i, id) in added.into_iter().enumerate() { + assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}"); + } + let l = s.doc().unwrap().doc.node(layer).unwrap().clone(); + assert!(l.locked && !l.visible, "the layer keeps its lock and visibility"); +} + +#[test] +fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0))); + // Again: nothing to add, and no undo step. + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before); + // Both artboards: only the new one is added. + let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap(); + assert_eq!(both["skipped"], json!(1)); + let [first] = ids(&both)[..] else { panic!("one guide: {both}") }; + assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0))); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn a_guide_grouped_inside_the_layer_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group)); + assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id)); + let (before, n) = (d.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); +} + +#[test] +fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0).inflate(5.0, 5.0); + let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)]; + // Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one. + for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] { + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = PathData::single(SubPath::polyline(&points, true)); + } + let n = steps(&s); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}"); + assert_eq!(steps(&s), n); + } +} + +#[test] +fn collinear_midpoints_do_not_add_another_guide_or_history_step() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let points = [ + Point::new(b.center().x, b.y0), + Point::new(b.x1, b.y0), + Point::new(b.x1, b.center().y), + Point::new(b.x1, b.y1), + Point::new(b.center().x, b.y1), + Point::new(b.x0, b.y1), + Point::new(b.x0, b.center().y), + Point::new(b.x0, b.y0), + ]; + for reverse in [false, true] { + let mut points = points.to_vec(); + if reverse { + points.reverse(); + } + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(SubPath::polyline(&points, true)); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1})); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } +} + +#[test] +fn handles_along_a_side_still_match_and_handles_off_it_do_not() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let mid = Point::new(b.center().x, b.y0); + let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)]; + let corner = points[1]; + let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| { + let mut sp = SubPath::polyline(&points, true); + sp.anchors[0].h_in = h_in; + sp.anchors[0].h_out = h_out; + sp.anchors[1].h_in = corner_in; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(sp); + }; + // The extra anchor's handles lie along the top side: the guide still matches. + // Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths). + let eighth = (corner.x - mid.x) / 8.0; + for (h_out, corner_in) in + [(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))] + { + set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } + // A handle off the side bends it: the path is not that guide, so one is added. + set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner); + let other = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(other["skipped"], json!(0)); + assert_eq!(ids(&other).len(), 1); +} + +#[test] +fn every_artboard_shares_one_walk_of_existing_guides() { + let mut s = session(); + s.execute(COMMAND, &json!({"all": true})).unwrap(); + super::GUIDE_NODES_VISITED.with(|count| count.set(0)); + s.execute(COMMAND, &json!({})).unwrap(); + let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0)); + assert!(single > 0); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"all": true})).unwrap(); + assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single); + assert!(ids(&r).is_empty()); + assert_eq!(r["skipped"], json!(2)); + assert_eq!(steps(&s), n); +} + +#[test] +fn release_guides_gives_back_a_rectangle_path() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(n.kind, NodeKind::Path { guide: false, .. })); + assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0))); +} + +#[test] +fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() { + let mut s = session(); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + // The second artboard is 100 pt tall: an inset of 50 leaves it no height. + for p in [ + json!({"offset": -50, "all": true}), + json!({"offset": -200}), + json!({"offset": "9 pt"}), + json!({"offset": 1_000_001}), + json!({"offset": -1e308}), + json!({"all": 1}), + json!({"all": true, "artboards": [0]}), + json!({"artboards": []}), + json!({"artboards": [2]}), + json!({"artboards": [-1]}), + json!({"artboards": [0.5]}), + json!({"artboards": "0"}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); + let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string(); + assert!(e.contains("no width or height"), "{e}"); +} + +#[test] +fn a_guide_past_the_edge_of_the_canvas_is_refused() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap(); + let n = steps(&s); + let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string(); + assert!(e.contains("past the edge of the canvas"), "{e}"); + assert_eq!(steps(&s), n); + s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap(); +} + +#[test] +fn it_is_off_without_artboards() { + let mut s = session(); + let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled; + assert!(enabled(&s)); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + assert!(!enabled(&s)); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index bb38e9437e..b98d45ae0a 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -439,6 +439,19 @@ fn match_gives_the_others_the_key_objects_size() { assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c)); } +#[test] +fn match_keeps_the_proportion_of_a_very_thin_target() { + let b = Rect::new(0.0, 0.0, 1e-10, 1.0); + let [w, h] = super::match_goal("width", (1.0, 5.0), b); + assert_eq!(w, 1.0); + assert!((h - 1e10).abs() <= 1.0, "{h}"); + let [w, h] = super::match_goal("height", (5.0, 1.0), Rect::new(0.0, 0.0, 1.0, 1e-10)); + assert!((w - 1e10).abs() <= 1.0, "{w}"); + assert_eq!(h, 1.0); + // A target with no width keeps its height. + assert_eq!(super::match_goal("width", (1.0, 5.0), Rect::new(0.0, 0.0, 0.0, 3.0)), [1.0, 3.0]); +} + #[test] fn match_takes_the_top_or_the_bottom_object_without_a_key() { let mut s = session(); @@ -512,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] { @@ -638,6 +712,44 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) { assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s)); } +/// Running `cmd` with Scale Corners on doubles the 2 pt corner radius of a 10 pt rounded square, +/// and replaying its journal entry after the preference is turned off scales the corners the same way. +fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "radius": 2})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + let radius = |s: &Session| match s.doc().unwrap().doc.node(a).unwrap().live_shape() { + Some(vectorcraft_doc::LiveShape::Rectangle { radii, xf, .. }) => radii[0] * xf.as_coeffs()[0], + _ => panic!("not a live rectangle"), + }; + select(&mut s, &[a, b]); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap(); + s.execute(cmd, &p).unwrap(); + assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", radius(&s)); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.replay(&id, &q).unwrap(); + assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", radius(&s)); +} + +#[test] +fn match_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20})); +} + +#[test] +fn swap_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + #[test] fn match_stacking_leaves_a_clipping_path_in_place() { let mut s = session(); @@ -664,6 +776,16 @@ fn match_size_refuses_a_target_with_no_width() { assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line)); } +#[test] +fn match_size_refuses_a_target_with_no_width_for_a_narrow_tall_source() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 0.05, 100000.0); + select(&mut s, &[line, b]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both"})]); +} + #[test] fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() { let mut s = session(); @@ -750,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"})); @@ -765,6 +1115,169 @@ fn swap_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); } +/// Running `cmd` with Scale Corners on scales the 2 pt corners of two rounded squares with them, +/// and replaying its journal entry after the preference is turned off scales them the same way. +fn replays_the_corner_shapes_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let square = |s: &mut Session, x: f64, w: f64| { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": w, "height": w, "radius": 2})).unwrap()["id"].as_u64().unwrap()) + }; + let a = square(&mut s, 0.0, 10.0); + let b = square(&mut s, 100.0, 20.0); + let shapes = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind))); + out.sort(); + out + }; + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap(); + select(&mut s, &[a, b]); + s.execute(cmd, &p).unwrap(); + let ran = shapes(&s); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.replay(&id, &q).unwrap(); + assert_eq!(shapes(&s), ran, "{cmd} replayed with other corners"); +} + +#[test] +fn match_replays_two_rounded_squares_with_the_corners_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_two_rounded_squares_with_the_corners_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.size", json!({"width": 30, "height": 30})); +} + +#[test] +fn swap_replays_two_rounded_squares_with_the_corners_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + +#[test] +fn replace_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.replace", json!({"fit": "bounds"})); +} + +#[test] +fn match_size_reaches_a_size_that_pixel_alignment_then_snaps() { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + select(&mut s, &[target]); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 15.5, 15.5); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "width"})).unwrap(); + let b = bounds(&s, target); + assert!((b.width() - 15.5).abs() <= 1.0 && (b.height() - 15.5).abs() <= 1.0, "{b:?}"); +} + +#[test] +fn match_size_fits_a_transform_copy_once_the_target_is_turned() { + for size in ["width", "both"] { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 30.0, 20.0); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": size, "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}"); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}"); + if size == "both" { + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}"); + } + } +} + +#[test] +fn match_size_fits_a_turned_target_whose_copy_fills_the_height_before_the_turn() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveV": 10, "copies": 1}})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 20.0, 5.0); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}"); +} + +#[test] +fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 2000.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap(); + let center = s.transform_box(&[target]).unwrap().center(); + let source = rect(&mut s, 100.0, 100.0, 11.0, 20.0); + s.execute("object.rotate", &json!({"angle": 180})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}"); +} + +#[test] +fn match_size_refuses_a_width_below_a_fixed_transform_copy() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 100000.05, "copies": 1}})).unwrap(); + let before = s.transform_box(&[target]).unwrap(); + assert!((before.rect.width() - 100020.05).abs() < 1e-6, "{before:?}"); + let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let out = s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})); + assert!(out.is_err(), "{out:?} {:?}", s.transform_box(&[target])); +} + +#[test] +fn match_size_refuses_dimensions_a_fixed_rotated_copy_cannot_reach_together() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute( + "effect.apply", + &json!({"effect": "distort.transform", "item": null, "params": {"rotate": 90, "reference": 4, "moveH": 99990.05, "copies": 1}}), + ) + .unwrap(); + let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]); +} + +#[test] +fn match_size_takes_a_huge_object_down_to_a_point() { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 20000.0, 20000.0); + let source = rect(&mut s, 100.0, 0.0, 1.0, 1.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap(); + let b = bounds(&s, target); + assert!((b.width() - 1.0).abs() < 1e-6 && (b.height() - 1.0).abs() < 1e-6, "{b:?}"); +} + #[test] fn match_refuses_bad_params() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs index 7fc935546e..43e8948118 100644 --- a/crates/engine/src/cmd/addons/shapes.rs +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -298,7 +298,7 @@ fn star(s: &mut Session, p: &Value) -> Result { pie, arc_mode, }; - insert_custom(s, "Star", None, cs) + insert_custom(s, "Star", cs.to_live_shape(), cs) } fn spiral(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs index bc5f1359e2..274678dd62 100644 --- a/crates/engine/src/cmd/addons/shapes/tests.rs +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -144,6 +144,68 @@ fn shape_of(s: &Session, id: NodeId) -> CustomShape { CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap() } +#[test] +fn configuring_a_live_star_keeps_its_live_shape() { + let mut s = new_session(); + for cmd in ["shape.star", "addon.shapes.star"] { + let id = id_of(&mut s, cmd, json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(live), .. } if matches!(live.as_ref(), LiveShape::Star { points: 5, .. }))); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Polygon { sides: 5, spoke_ratio: Some(_), .. }))); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 7})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert_eq!(path, &live.to_path()); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert!((live.star_ratio().unwrap() - 0.4).abs() < 1e-9); + assert_eq!(path, &live.to_path()); + } +} + +/// A live star with a ratio below 0.01, which `object.setLiveShape` accepts, keeps its inner +/// radius and stays live when it is configured without a ratio. +#[test] +fn configuring_a_live_star_keeps_a_small_ratio() { + let mut s = new_session(); + let id = id_of(&mut s, "shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 60.0, "radius2": 30.0, "points": 5})); + s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": 0.0001})).unwrap(); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 6})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { r1, r2, points: 6, .. } if *r1 == 60.0 && (r2 - 0.006).abs() < 1e-9), "{live:?}"); + assert_eq!(path, &live.to_path()); +} + +/// Angles configured on a whole shape stay live and are kept for a later arc mode. +#[test] +fn angles_configured_on_a_whole_shape_are_kept_for_a_later_arc_mode() { + let mut s = new_session(); + let shapes = [ + ("shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})), + ("shape.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5})), + ("shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 50.0})), + ("shape.ellipse", json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})), + ]; + for (cmd, p) in shapes { + let id = id_of(&mut s, cmd, p); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "startAngle": 0.0, "endAngle": 90.0})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(_), .. }), "{cmd} stays live"); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "arcMode": "pie"})).unwrap(); + let pie = match CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()) { + Some(CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. }) => pie, + other => panic!("{cmd}: {other:?}"), + }; + assert_eq!(pie, (0.0, 90.0), "{cmd}"); + } +} + /// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they /// were. fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) { diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index bff15c6540..54c1db0f41 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -140,6 +140,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); } graph_families(node, visit); } @@ -198,6 +206,20 @@ pub(super) fn plan_import(source: Vec, source_families: BTreeSet< 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()) { @@ -226,12 +248,18 @@ pub(super) fn plan_import(source: Vec, source_families: BTreeSet< 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/create.rs b/crates/engine/src/cmd/create.rs index 083cfa65d9..934151589b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}: a live star whose points and ratio object.setLiveShape changes", has_doc, star ), @@ -655,14 +655,11 @@ fn star(s: &mut Session, p: &Value) -> Result { let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32; let rot = f64_or(p, "rotation", 0.0); - let turn = vectorcraft_geom::rotate_deg(rot); // A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly. - let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) { - shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn) - } else { - shapes::star(c, r1, r2, n, rot) - }; - add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) + let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + // The star stays live: its point count and ratio can change later (`object.setLiveShape`). + let live = LiveShape::Star { r1, r2, points: n, xf, radii: vec![], kinds: vec![], radii_relative: false }; + add_art_turned(s, "Star", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot)) } fn line(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 60a7aaba29..073c35e88c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -289,6 +289,15 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result { Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed})) } +/// Report the first rendered 3D effect that keeps its shaded faces after an edit. +fn with_render_warning(s: &Session, ids: &[NodeId], mut out: Value) -> Result { + let d = &s.doc()?.doc; + if let Some(message) = ids.iter().filter_map(|id| d.node(*id)).find_map(|n| effects::rendered_warning(d, n)) { + out["warning"] = json!(message); + } + Ok(out) +} + fn ids_json(ids: &[NodeId]) -> Value { json!(ids.iter().map(|i| i.0).collect::>()) } @@ -569,7 +578,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { }; let landed = first.and_then(|n| at.effects_item(&n.appearance, C).ok().flatten()); let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1)); - Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) + with_render_warning(s, &ids, json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } /// The selected objects a Pathfinder effect should group before it applies: it combines the @@ -891,7 +900,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let ids: Vec<&str> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect(); if !ids.is_empty() && ids.iter().all(|id| *id == to) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // Pathfinder effects given the values they already evaluate with, and nothing else to change, @@ -900,7 +909,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // An SVG filter is named by its id: another filter renames the effect. @@ -947,7 +956,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); if !fx.is_empty() && fx.iter().all(|e| three_d_edit_changes_nothing(e, ¶ms)) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // The effect edited, when every target has one at `index` and all are the same: a dialog's @@ -982,7 +991,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { true }) })?; - Ok(json!({ "ids": ids_json(&ids) })) + with_render_warning(s, &ids, json!({ "ids": ids_json(&ids) })) } /// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fad6df1e40..67e6981139 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -74,7 +74,7 @@ use serde_json::{Value, json}; pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; -pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; +pub use dxf::{UNSUPPORTED, Unsupported, unsupported, write_hint}; pub use encode::{ ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds, note_texts, @@ -246,6 +246,8 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; +#[cfg(test)] +mod tests_dwgimport; #[cfg(test)] mod tests_dxfimport; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index c341f03e69..04aef3563a 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -29,6 +29,14 @@ const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under th const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque"; const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out"; const DAMAGED: &str = "damaged parts of the drawing were left out"; +/// Shown with [`UNSUPPORTED_OBJECTS`] or [`TOO_DEEP`]: `craft-cdr` opens a PowerClip frame whose +/// contents were all left out as a plain shape. Its warnings name neither the kinds of objects +/// left out nor the frames that lost their contents, so this line is shown whenever objects were +/// left out. Once `craft-cdr` reports which frames lost their contents, show it only for those. +const EMPTY_FRAMES: &str = "CDR PowerClip frames whose contents were left out opened empty, as plain shapes"; +/// The first version, in hundreds, whose PowerClip frames `craft-cdr` reads: earlier versions +/// store their objects' styles inline, and the reader opens none of them as frames. +const FRAMES_FROM: u16 = 400; const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; const CMX_UNSUPPORTED_OBJECTS: &str = @@ -103,7 +111,11 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { } why => err(format!("this CDR drawing can't be read ({why})")), })?; - Ok(build(&d, note, PAGES_CUT)) + let (doc, mut warnings) = build(&d, note, PAGES_CUT); + if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) { + warnings.push(EMPTY_FRAMES.to_string()); + } + Ok((doc, warnings)) } /// Is `bytes` a `.cmx` file, of any byte order or coordinate size? diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index bddd245b71..c35ad702f4 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8004234c07..c92d9b8ad0 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -1,6 +1,7 @@ //! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As //! → DXF Options): the options parsed from the params, one drawing per artboard with Use -//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead. +//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to +//! use instead. use std::sync::Arc; @@ -99,20 +100,12 @@ pub struct Unsupported { } /// Formats people ask for that VectorCraft doesn't read or write. Append-only. -pub const UNSUPPORTED: &[Unsupported] = &[ - Unsupported { - id: "dwg", - label: "DWG", - extensions: &["dwg"], - hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open", - }, - Unsupported { - id: "pmd", - label: "PageMaker", - extensions: &["pmd"], - hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here", - }, -]; +pub const UNSUPPORTED: &[Unsupported] = &[Unsupported { + id: "pmd", + label: "PageMaker", + extensions: &["pmd"], + hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here", +}]; /// The unsupported format an id or extension (any case, leading dot allowed) names. pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { @@ -120,6 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str())) } +/// Formats VectorCraft opens but doesn't write, with what to export instead. +const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")]; + +/// What to write instead of the format an id or extension (any case, leading dot allowed) names, +/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG). +pub fn write_hint(id_or_ext: &str) -> Option<&'static str> { + let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase(); + unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint)) +} + impl Unsupported { pub fn to_json(&self) -> Value { json!({ "id": self.id, "label": self.label, "extensions": self.extensions, "hint": self.hint }) diff --git a/crates/engine/src/cmd/fileio/dxfimport.rs b/crates/engine/src/cmd/fileio/dxfimport.rs index eef7aca4cd..2d16034c09 100644 --- a/crates/engine/src/cmd/fileio/dxfimport.rs +++ b/crates/engine/src/cmd/fileio/dxfimport.rs @@ -1,4 +1,4 @@ -//! Opening and placing DXF drawings: the `dxf` options `document.open` and `file.place` read +//! Opening and placing DXF and DWG drawings: the `dxf` options `document.open` and `file.place` read //! (layout, scale or fit, lineweights, centring, merged layers) and `document.dxfInfo` (layouts, //! layers, units) for the DXF Import Options dialog. @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "DXF Info", [], None, - "{path} or {name?, dataBase64} what a DXF drawing holds → {version (2018, R12…), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}; a DWG answers an error saying to save it as DXF", + "{path} or {name?, dataBase64} what a DXF or DWG drawing holds → {version (2018, R12…; a DWG's is that of the DXF it converts to), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}", always, dxf_info )] @@ -70,7 +70,7 @@ pub(super) fn options(cmd: &str, p: Option<&Value>) -> Result { }) } -/// Import a DXF drawing → the document and import notes. +/// Import a DXF or DWG drawing → the document and import notes. pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec)> { let r = vectorcraft_cad::import(bytes, o).map_err(err)?; Ok((r.document, r.warnings)) diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 4fee998d8e..f8da5b941c 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -561,6 +561,9 @@ pub const FORMATS: &[Format] = &[ // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size // composite, the layers combined, or the preview with a note. Exports don't write them. reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), + // DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF + // reader with the DXF import options. Exports don't write them. + reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -622,6 +625,7 @@ pub const OPEN_EXTS: &[&str] = &[ "cdt", "cmx", "pcraft", + "dwg", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to @@ -629,11 +633,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft` -/// documents either. +/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` +/// documents or DWG drawings either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -724,6 +728,7 @@ pub const PLACE_EXTS: &[&str] = &[ "cdt", "cmx", "pcraft", + "dwg", "txt", "rtf", "docx", @@ -1087,6 +1092,8 @@ pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::r Ok(f) } else if TEMPLATE_FORMATS.contains(&f.id) { Err(format!("{} files are written by file.saveAsTemplate", f.label)) + } else if let Some(hint) = super::dxf::write_hint(f.id) { + Err(hint.to_string()) } else { Err(format!("{} files can be opened but not written (see document.formats)", f.label)) } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 53cac16bee..f152132c69 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -47,12 +47,12 @@ impl Loaded { /// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or /// what an importer plug-in reads, as the reference app opens such files (#5820). A native /// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the - /// units of its root's size, pixels when it gives none), a DXF drawing (the unit it was read - /// in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows + /// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was + /// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows /// change, not its art. pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self { let records_units = - self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf"); + self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg"); if !records_units { self.doc.units = crate::units::pref_unit(&prefs.units_general); } @@ -125,6 +125,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_cad::is_dxf(bytes) { return format("dxf"); } + if vectorcraft_cad::is_dwg(bytes) { + return format("dwg"); + } if let Some(kind) = vectorcraft_metafile::sniff(bytes) { return format(kind.id()); } @@ -560,7 +563,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } read } - "dxf" => { + // A DWG drawing is read as the DXF craft-dwg converts it to. + "dxf" | "dwg" => { let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?; (doc, warnings, false) } diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 954a345ae0..005cc4a557 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -176,8 +176,8 @@ impl LoadOptions { self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages } - /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible + /// `.ai` with Illustrator private data opens on its trim boxes by default, /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { @@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page /// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box; -/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the +/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the /// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box, /// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the /// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens @@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?, }; let bounding = o.crop == CropTo::Bounding; - // A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]). - let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; + // A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]); + // an explicit crop-box request keeps its crop boxes. + let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; let mut doc = Document::new(1.0, 1.0); let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?; doc.artboards.clear(); diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 2645e86c76..2e4d82822b 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -89,6 +89,8 @@ fn versions_3_and_4_open_and_place_as_editable_art() { assert_eq!(r["format"], "cdr", "{version} {name}"); let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}"); + // The reader opens PowerClip frames from version 4 on. + assert_eq!(w.iter().any(|w| w.contains("PowerClip")), version >= 400, "{version}: {w:?}"); } let doc = &s.doc().unwrap().doc; assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}"); @@ -535,6 +537,35 @@ fn containers_open_as_clipping_groups() { assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); } +/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or +/// whose group holds a container of that same group, opens as a plain shape, and the warnings +/// say that such frames opened empty. +#[test] +fn containers_whose_contents_were_left_out_are_named_in_the_warnings() { + let v = V(1100); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let open = |clipped: Vec| { + let doc = list(b"doc ", vec![synth::clpt(vec![(5, clipped)])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]); + super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap() + }; + let frames = "PowerClip frames whose contents were left out opened empty"; + let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]); + let p = paths(&doc); + let [frame] = p.as_slice() else { panic!("{p:?}") }; + assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind); + assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); + // The inner container names the group already being read, so it is left out at the limit. + let (_, warnings) = open(vec![rect(10.0, vec![synth::container(5)])]); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); +} + /// An object with a lens or transparency opens opaque, and the warnings say so. #[test] fn lenses_and_transparency_are_named_in_the_warnings() { diff --git a/crates/engine/src/cmd/fileio/tests_dwgimport.rs b/crates/engine/src/cmd/fileio/tests_dwgimport.rs new file mode 100644 index 0000000000..d4aa2ad348 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_dwgimport.rs @@ -0,0 +1,113 @@ +//! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG +//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read +//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32 +//! and FreeBSD on aarch64. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; + +use super::tests_dxfimport::plan; +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// The DXF test drawing as a DWG 2004 file, written by craft-dwg. +fn plan_dwg() -> Vec { + vectorcraft_cad::dwg::allow_in_process(); + craft_dwg::dxf_to_dwg_as(&plan(), "AC1018").unwrap() +} + +fn open(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> crate::Result { + let mut p = json!({"name": name, "dataBase64": b64(bytes)}); + if let (Some(p), Value::Object(e)) = (p.as_object_mut(), extra) { + p.extend(e); + } + s.execute("document.open", &p) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().filter_map(|l| l.name.clone()).collect() +} + +fn leaves(s: &Session) -> Vec { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| { + if n.children().is_none() { + out.push(n.clone()); + } + }); + out +} + +#[test] +fn document_open_reads_a_dwg_drawing_as_its_dxf() { + let mut s = Session::new(); + open(&mut s, "plan.dxf", &plan(), json!({})).unwrap(); + let (want_layers, want_board, want_leaves) = (layer_names(&s), s.doc().unwrap().doc.artboards[0].rect, leaves(&s).len()); + let r = open(&mut s, "plan.dwg", &plan_dwg(), json!({})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dwg"))); + assert_eq!(layer_names(&s), want_layers); + let st = s.doc().unwrap(); + let board = st.doc.artboards[0].rect; + assert!((board.width() - want_board.width()).abs() < 1e-6 && (board.height() - want_board.height()).abs() < 1e-6, "{board:?}"); + assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters); + assert_eq!(leaves(&s).len(), want_leaves); + assert_eq!(leaves(&s).iter().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).count(), 2, "the block's two inserts"); + // The DXF options apply. + open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"fit": true, "mergeLayers": true}})).unwrap(); + assert_eq!(layer_names(&s), ["Layer 1"]); + assert!(open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"layout": "Sheet 9"}})).is_err()); +} + +#[test] +fn a_dwg_opened_is_never_written_back_as_dwg() { + let dir = std::env::temp_dir().join(format!("vc-dwg-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plan.dwg"); + let dwg = plan_dwg(); + std::fs::write(&path, &dwg).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("not DWG"), "{e}"); + let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string(); + assert!(e.contains("export DXF instead"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn dxf_info_and_place_read_a_dwg() { + let mut s = Session::new(); + let dxf = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan())})).unwrap(); + let dwg = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan_dwg())})).unwrap(); + for k in ["units", "layouts", "unit", "scale"] { + assert_eq!(dwg[k], dxf[k], "{k}"); + } + let layers: Vec<&str> = dwg["layers"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(layers.contains(&"Walls") && layers.contains(&"Notes"), "{layers:?}"); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("file.place", &json!({"name": "plan.dwg", "dataBase64": b64(&plan_dwg()), "dxf": {"fit": true}})).unwrap(); + assert_eq!(r["format"], "dwg"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + assert!((b.width() - 600.0).abs() < 1.0 && (b.center().y - 200.0).abs() < 0.5, "fitted to the artboard: {b:?}"); +} + +#[test] +fn dwg_is_read_only_and_detected_by_content() { + let f = format("dwg").unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg")); + assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells"); + let mut s = Session::new(); + let r = s.execute("document.formats", &json!({})).unwrap(); + assert!(r["readable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg")); +} diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index b5129d1910..7a04d93ddc 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -1,5 +1,5 @@ //! DXF export through the commands: options, artboards, selection, images, and the formats that -//! can't be written (DWG, PageMaker). +//! can't be written (DWG, which opens, and PageMaker). use serde_json::{Value, json}; @@ -293,7 +293,7 @@ fn formats_list_dxf_and_what_can_not_be_written() { } assert!(r["writable"].as_array().unwrap().contains(&json!("dxf"))); let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect(); - assert_eq!(unsupported, ["dwg", "pmd"]); + assert_eq!(unsupported, ["pmd"]); } #[test] @@ -301,7 +301,7 @@ fn dwg_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] { let e = s.execute("document.export", &p).unwrap_err().to_string(); - assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}"); + assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}"); } // PICT opens; it isn't written. let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); @@ -315,7 +315,8 @@ fn dwg_and_pagemaker_say_what_to_use_instead() { .execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")})) .unwrap_err() .to_string(); - assert!(e.contains("DWG is not available"), "{e}"); + // A DWG that can't be converted says so (DWG drawings open: see tests_dwgimport). + assert!(e.contains("DWG"), "{e}"); let e = s .execute("document.open", &json!({"name": "brochure.PMD", "dataBase64": vectorcraft_format::base64_encode(b"PageMaker")})) .unwrap_err() diff --git a/crates/engine/src/cmd/fileio/tests_dxfimport.rs b/crates/engine/src/cmd/fileio/tests_dxfimport.rs index d3dcdcb86c..524913dcb7 100644 --- a/crates/engine/src/cmd/fileio/tests_dxfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dxfimport.rs @@ -14,7 +14,7 @@ fn b64(bytes: &[u8]) -> String { /// A millimetre drawing: a 200 × 100 rectangle on layer Walls, a circle on layer Notes, a block /// "Mark" (a short line) inserted twice, and a paper layout holding a line. -fn plan() -> Vec { +pub(super) fn plan() -> Vec { let pairs: &[(i32, &str)] = &[ (0, "SECTION"), (2, "HEADER"), diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3a52534ac8..ca4a9d7022 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard (unless it is new art there that is still selected), and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -1051,7 +1051,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when - // the path was, or when the compound path it leaves was. + // the path was, or when the compound path it leaves was. A compound path that is + // pixel-aligned snaps the path it takes in. if let Some(c) = into { let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { @@ -1061,9 +1062,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result { *live = None; } } - if aligned && let Some(cn) = d.node_mut(c) { - cn.extras_mut().pixel_aligned = true; - super::object::snap_if_aligned(cn); + if let Some(cn) = d.node_mut(c) { + aligned |= cn.extras().pixel_aligned; + if aligned { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } } } if let Some((appearance, aligned)) = out_of diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 62a84418b0..3851aeefac 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -44,7 +44,7 @@ pub fn specs() -> Vec { "{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}", has_doc, show_missing_links), cmd!(query "links.marked", "Marked Missing Links", [], None, - "{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}", + "{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off; a caller whose read folders do not cover the same files as the document's, or a script command, gets its own answer and the canvas markers stay as they are → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}", has_doc, marked), cmd!( query "links.check", @@ -2693,7 +2693,19 @@ fn marked(s: &mut Session, _: &Value) -> Result { Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]})) }) .collect(); - st.missing_link_markers = Some((st.doc.clone(), ids)); + // The canvas draws the markers the link watch finds with the read roots the document was + // opened with ([`Session::start_link_scan`]). An answer found with other read roots stays the + // caller's, as is one found by a script command, whose file-read gate the link watch does + // not have. + let same_roots = !crate::file_access::in_script_command() + && match (crate::file_access::current(), &st.opened_by) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(&a, b) || a.same_reads(b), + _ => false, + }; + if same_roots { + st.missing_link_markers = Some((st.doc.clone(), ids)); + } Ok(json!({"on": st.show_missing_links, "images": images})) } 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 413405ba4f..f9c30205f0 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -33,12 +33,12 @@ mod transform; pub(crate) use align::choice; pub(crate) use arrange::group_nodes; -pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; +pub(crate) use bounds::{bounds_rewrite, object_bounds_transform, object_bounds_transform_keeping, refit_drawn}; 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/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index a24e71c9a6..b184dbeccb 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -45,7 +45,13 @@ pub(crate) fn bounds_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<( /// `object.setBounds` measures them (Use Preview Bounds, `strokes`, `reference`, `proportional`), /// whatever anchors are direct-selected. The art keeps at least 1e-4 of its width and height. pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Result { - match bounds_transform(s, p, vec![id], 1e-4, false)? { + object_bounds_transform_keeping(s, p, id, 1e-4) +} + +/// [`object_bounds_transform`] with the art keeping at least `least` of its width and height +/// (0: any scale the values ask for). +pub(crate) fn object_bounds_transform_keeping(s: &Session, p: &Value, id: NodeId, least: f64) -> Result { + match bounds_transform(s, p, vec![id], least, false)? { Bounds::Objects(_, xf) => Ok(xf), Bounds::Anchors(..) => Err(EngineError::Other("no bounds".into())), } @@ -163,7 +169,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor // smaller than that reach. Strokes and effects that scale shrink the reach with the art, so // the search then starts from the size wanted over the size as drawn. let seed = |s: f64, size: f64, now: f64| if s <= 0.0 && size > 0.0 && now > 1e-9 { size / now } else { s }; - refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9]) + refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9], None) } else { Spans::measure(d, &ids, &frame, strokes).refit(rp, refi, [w, h], (sx, sy, new_rp)) }; @@ -186,26 +192,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor /// change with the y scale and the height with the x scale (a geometry effect can turn the art). A /// scale that `free` marks false stays as it is. The search stops when both sizes are within 1e-9 /// of the sizes wanted (of the largest of 1 and those sizes), when no scale moves, when `measure` -/// finds no box, or after 16 steps, and returns the scales that came nearest. `None` when `measure` -/// finds no box for `start`. -fn refit_drawn( +/// finds no box, or after 16 steps. It returns the scales whose box met both stopping tolerances, +/// and otherwise the scales whose box came nearest. `None` when `measure` +/// finds no box for `start`. Each stopping tolerance in `tolerances`, when given, is capped at +/// the default tolerance. +pub(crate) fn refit_drawn( measure: impl Fn(f64, f64) -> Option, refi: usize, size: [f64; 2], start: (f64, f64), free: [bool; 2], + tolerances: Option<[f64; 2]>, ) -> Option<(f64, f64, Point)> { let [w, h] = size; let tolerance = 1e-9 * w.max(h).max(1.0); + let tolerances = tolerances.unwrap_or([tolerance; 2]).map(|t| t.min(tolerance)); let miss = |b: Rect| (b.width() - w).abs() + (b.height() - h).abs(); + let met = |b: Rect| (b.width() - w).abs() <= tolerances[0] && (b.height() - h).abs() <= tolerances[1]; let (mut sx, mut sy) = start; let mut b = measure(sx, sy)?; let mut best = (sx, sy, b); for _ in 0..16 { - let f = [b.width() - w, b.height() - h]; - if f[0].abs() <= tolerance && f[1].abs() <= tolerance { + if met(b) { break; } + let f = [b.width() - w, b.height() - h]; // How the width and the height change with the x scale (`a`) and the y scale (`c`). let change = |x: bool| -> Option<[f64; 2]> { let (on, s) = if x { (free[0], sx) } else { (free[1], sy) }; @@ -235,7 +246,8 @@ fn refit_drawn( } let Some(next) = measure(nx, ny) else { break }; (sx, sy, b) = (nx, ny, next); - if miss(b) < miss(best.2) { + // A box that meets both tolerances wins over a nearer sum that misses one of them. + if met(b) || miss(b) < miss(best.2) { best = (sx, sy, b); } } @@ -291,3 +303,28 @@ fn scaling_box(d: &Document, ids: &[NodeId], frame: &OrientedBox) -> Option Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), 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/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b8bd5ff8c6..79a26dd73f 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -103,7 +103,7 @@ fn corners_param(p: &Value) -> Result>> { /// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live /// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. fn takes_rounding(live: Option<&LiveShape>) -> bool { - matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. } | LiveShape::Path { .. })) } /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about @@ -130,6 +130,16 @@ fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option bool { + fn layout(l: &LiveShape) -> Option>> { + let path = l.to_path(); + LiveCorners::new(&path, Some(l)).map(|c| c.sources().to_vec()) + } + old.star_points().is_some() && (old.star_points() != new.star_points() || layout(old) != layout(new)) +} + /// The transform that takes live shape `old` to `new` where they differ only in place, angle and /// size (a new Rectangle, Ellipse or Polygon Angle, Polygon Radius, Side Length, Make Sides Equal, /// Line Length or Line Angle): what moves, turns and scales the rest of the object (a linked @@ -175,7 +185,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"], "object.setLiveShape", )?; - check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; + check_numbers(p, &["radius", "sides", "points", "ratio"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { None => None, @@ -240,6 +250,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } else { number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64) }; + // A star's Star Properties: its point count (a whole number from 2 to 1000, as `shape.star` + // takes it) and its ratio (inner radius over outer radius, above 0 and up to 1). Both are + // checked on replay too: no recording predates them. + let points = number("points", |n| n.fract() == 0.0 && (2.0..=1000.0).contains(&n), "a whole number from 2 to 1000")?.map(|n| n as u64); + let ratio = number("ratio", |r| r > 0.0 && r <= 1.0, "a ratio above 0 and up to 1")?; + // A new point count lays a star's corners out again, so the corners a radius or kind would set + // can't be told from the anchors selected before it. + if points.is_some() && (radius.is_some() || kind.is_some()) { + return Err(bad("object.setLiveShape", "`points` can't be set with `radius` or `kind`: set the corners in a call of their own")); + } // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); @@ -292,6 +312,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } else { ids }; + // A ratio is the inner radius over the outer one: a star whose outer radius is 0 has none to set. + if ratio.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).and_then(|n| n.live_shape()), Some(LiveShape::Star { r1, .. }) if *r1 <= 0.0)) + { + return Err(bad("object.setLiveShape", "a star whose outer radius is 0 has no ratio to set")); + } // The lines that Line Length or Line Angle changes, as they become. A line that would reach // past the document's coordinate limit is an error before anything changes. let mut lines = std::collections::BTreeMap::new(); @@ -321,6 +346,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { { return false; } + Some(l @ LiveShape::Star { points: now, .. }) + if !(points.is_none_or(|n| n.clamp(2, 1000) == u64::from(*now)) + && ratio.is_none_or(|r| l.star_ratio().is_some_and(|k| (k - r).abs() < 1e-12))) => + { + return false; + } Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => { return false; } @@ -386,6 +417,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } edited = true; } + if let l @ LiveShape::Star { .. } = &mut new + && (points.is_some() || ratio.is_some()) + { + if let Some(n) = points { + l.set_points(n); + } + if let Some(r) = ratio { + l.set_star_ratio(r); + } + edited = true; + } if let Some(a) = rectangle_angle && let l @ LiveShape::Rectangle { .. } = &mut new { @@ -411,6 +453,14 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { reshaped.insert(*id, ((**old).clone(), new)); } } + // A ratio that changes which corners a rounded star cuts lays its anchors out again, as a new + // point count does, so the corners a radius or kind would set can't be told apart. + if ratio.is_some() && (radius.is_some() || kind.is_some()) && reshaped.values().any(|(old, new)| star_relaid(old, new)) { + return Err(bad( + "object.setLiveShape", + "this `ratio` changes the star's anchors, so it can't be set with `radius` or `kind`: set the corners in a call of their own", + )); + } // A shape that moves, turns or scales takes the rest of the object along as a transform does: // Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the // preferences, and are noted in the journal so a replay does the same. Corner radii in the rest @@ -439,6 +489,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *live = Some(Box::new(new.clone())); *path = new.to_path(); } + // A new point count, or a ratio that changes which corners the rounded star cuts, lays its + // anchors out again: anchors and segments selected on the old layout would name others, + // or none. + if star_relaid(old, new) { + sel.anchors.remove(id); + sel.segments.remove(id); + } } for id in &ids { let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; 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.rs b/crates/engine/src/cmd/place.rs index abef066227..9d145853b9 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -357,9 +357,9 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let (natural, warnings) = (s.frame, s.warnings.clone()); return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None }); } - let anchored = format.id == "dxf" && (opts.dxf.fit || !opts.dxf.center); + let anchored = matches!(format.id, "dxf" | "dwg") && (opts.dxf.fit || !opts.dxf.center); let (mut doc, warnings) = { - // Of the open options, only a DXF drawing's apply (the colour mode stays the file's). + // Of the open options, only a DXF or DWG drawing's apply (the colour mode stays the file's). let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() }; let mut l = fileio::load_with(src.name, &src.bytes, &o)?; // An Affinity file whose native document couldn't be read is only its preview: it @@ -380,7 +380,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored); let layers = std::mem::take(&mut doc.layers); let symbols = doc.symbol_boxes(); - let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") { + let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "dwg" | "hpgl") { // An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard), // as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By // default, as Illustrator places one, it is its art's bounds. diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 483503f190..c32aff52e1 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) { +fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec, BTreeSet) { let mut used = Used::default(); - let composites = !src.composite_fonts.is_empty(); let mut families = BTreeSet::new(); let mut note_family = |name: &mut String| { families.insert(name.to_lowercase()); @@ -596,10 +595,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) = collect_resources(src, nodes); + let composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty(); + let (used, mut src_brushes, 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, dst, cmd)?) }; + let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dst, cmd)?) }; let staged; let mut aliased = false; let src = if let Some(plan) = &plan { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5f970bb568..b08207d904 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -4,6 +4,7 @@ /// Commands a plug-in may call when its manifest lists them, in order. pub(super) const ALLOWED: &[&str] = &[ + "addon.arrange.artboardGuides", "addon.arrange.grid", "addon.arrange.groupOverlapping", "addon.arrange.groupRows", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 0ee0340542..41b50dbeca 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -174,6 +174,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ choice(&[("touching", "Touching"), ("enclosed", "Fully Enclosed"), ("directional", "Drag Direction")]) ), p!("objectSelectionByPathOnly", "Selection & Anchor Display", "Selection", "Object Selection by Path Only", bool), + p!("selectInsideUnfilledShapes", "Selection & Anchor Display", "Selection", "Select Inside Unfilled Shapes", bool), p!("snapToPointTolerance", "Selection & Anchor Display", "Selection", "Snap to Point", num(1.0, 8.0, "px")), p!("ctrlClickSelectsBehind", "Selection & Anchor Display", "Selection", "Command Click to Select Objects Behind", bool), p!("zoomToSelection", "Selection & Anchor Display", "Selection", "Zoom to Selection", bool), @@ -401,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/command_sets.rs b/crates/engine/src/command_sets.rs index 753c315a9a..e3bbe41d23 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -4,8 +4,10 @@ use super::{NodeId, Value, cmd, find_command}; /// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute /// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on /// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art -/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none. -pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [ +/// on it, and Add Artboard Guides puts its guide around it. A `command.batch` given `artboard` +/// passes it on to each of their steps that names none. +pub const ON_ACTIVE_ARTBOARD: [&str; 11] = [ + "addon.arrange.artboardGuides", "edit.copy", "edit.cut", "edit.pasteInPlace", @@ -37,10 +39,11 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 38] = [ +const REPLAY_ONLY: [(&str, &str); 39] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), + ("addon.arrange.artboardGuides", "artboard"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), ("file.saveAs", "modified"), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index b5b77aef35..dc428b71a6 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -163,6 +163,13 @@ impl AutomationRoots { within(&self.read, &other.read) && within(&self.write, &other.write) } + /// Whether these roots and `other` let the same files be read: each read root of either lies + /// inside a read root of the other. + pub(crate) fn same_reads(&self, other: &Self) -> bool { + let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved))); + within(&self.read, &other.read) && within(&other.read, &self.read) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 31cfe000de..814990daba 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -46,6 +46,9 @@ pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; pub use journal::Journal; pub use tooling::{UiRequest, ViewInfo}; +/// DWG drawings are converted in a child process: a program calls `dwg::serve_if_asked` first in +/// `main` and `dwg::use_own_worker` at startup. +pub use vectorcraft_cad::dwg; pub use vectorcraft_doc as doc; pub use vectorcraft_doc::cancel; pub use vectorcraft_pathops::{SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, simplify_level_tolerance}; @@ -455,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 f5528f0471..0cb1cf613f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -134,6 +134,9 @@ pub struct Prefs { /// Selection-tool marquee: touching (default), enclosed, or screen drag direction. pub marquee_selection: String, pub object_selection_by_path_only: bool, + /// Off (the default), a selection tool click inside a closed path with no fill starts a + /// marquee; on, it selects the path when no other object is hit there (#9175). + pub select_inside_unfilled_shapes: bool, pub snap_to_point_tolerance: f64, pub ctrl_click_selects_behind: bool, pub zoom_to_selection: bool, @@ -303,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; @@ -593,6 +605,7 @@ impl Default for Prefs { selection_tolerance: 3.0, marquee_selection: "touching".into(), object_selection_by_path_only: false, + select_inside_unfilled_shapes: false, snap_to_point_tolerance: 2.0, ctrl_click_selects_behind: true, zoom_to_selection: true, @@ -694,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 18b6b5f65d..b85e3fede4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,7 +38,8 @@ //! - After `documents[0]`, documents are listed from the one active most recently to the one //! active longest ago. A change a script makes to a document in the back does not move it. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the -//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the +//! order of a layer's, a group's and a compound path's lists. An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. //! - Script coordinates are points with Y up from the bottom of the first artboard //! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of @@ -117,9 +118,12 @@ mod tracing; mod transform; mod variables; +pub(super) use colors::of_color as color_data; #[cfg(test)] pub(crate) use paths::POINT_LOOKS; #[cfg(test)] +pub(crate) use paths::index_builds; +#[cfg(test)] pub(crate) use print::postscript_name; #[cfg(test)] pub(crate) use save_open::with_extension; @@ -146,6 +150,8 @@ pub const STALE_ITEM: &str = "Stale page item"; const TRACING_NAME: &str = "The name of a tracing cannot be changed"; /// The error for the tracing's name given to a group that holds an image first. const NOT_A_TRACING: &str = "Only Image Trace can make a tracing"; +/// The error of `move` and `remove()` for a tracing's source image. +const SOURCE_STAYS: &str = "a tracing's source image cannot leave its tracing"; /// The error for a document that was closed, or that came from an earlier run. pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. @@ -205,14 +211,18 @@ thread_local! { /// written yet, how many times each path's points went stale and each path as the run last saw its /// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each /// `DocumentPreset` the run made, with the size of the values they hold now and the most they may -/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool +/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and +/// layers its layers and groups gave, the active artboard of each document, and the tool /// `app.selectTool` chose last. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, - /// The last list of each document's paths ([`paths`]), kept while that document is unchanged. - paths: RefCell>, + locked: RefCell>, + /// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's + /// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is + /// unchanged. + paths: RefCell>, /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, @@ -231,14 +241,13 @@ pub(super) struct State { /// The item the object model is changing ([`edit_item`]), whose points stay valid through the /// change. editing: Cell>, - locked: RefCell>, saving: Cell, /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently /// used first, each kept while its document is unchanged. art: RefCell>, - /// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used - /// first, each kept while its document is unchanged. - layers: RefCell>, + /// The last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first, + /// each kept while its document is unchanged. + layer_lists: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it. @@ -328,24 +337,6 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); -/// The most documents whose lists [`State`] keeps at once, the least recently listed going first. -const KEPT_LISTS: usize = 8; - -/// The list kept in `lists` for the document `st`, while that document is unchanged. -fn kept_list(lists: &RefCell>, st: &DocState) -> Option>> { - lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone()) -} - -/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had. -fn keep_list(lists: &RefCell>, st: &DocState, ids: &Rc>) { - let mut l = lists.borrow_mut(); - l.retain(|(uid, ..)| *uid != st.uid); - if l.len() >= KEPT_LISTS { - l.remove(0); - } - l.push((st.uid, st.doc.clone(), ids.clone())); -} - /// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for /// each object of a layer or sublayer asked about then, whether it was on a locked artboard. type LockedList = (u64, Arc, Arc>, HashMap); @@ -627,6 +618,15 @@ fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] { [float(h.run), float(st.uid), high, low, float(st.reverts)] } +/// The handle of a collection that lists the art of the layer, group or compound path `id` in the +/// document `uid`, with the document's revert count as [`node_handle`] gives it, so that a +/// collection read before File > Revert is stale. +fn scoped_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] { + let [high, low] = id_parts(id); + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); + [float(h.run), float(uid), high, low, float(reverts)] +} + fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> { let &[run, uid, high, low, reverts] = handle else { return None }; let doc = find_doc(h, run, uid)?; @@ -695,7 +695,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id))) } Some(t) => host_ref(t, &node_handle(h, st, id)), - None => host_ref("Layer", &node_handle(h, st, id)), + None => layers::layer_ref(h, st.uid, id), }, None => Data::Null, } @@ -870,7 +870,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; } else { // One `select.anchorsMany` selects every object in its order: a partly selected path with - // its anchors, a whole path with all of them and any other object with none. + // its anchors, a whole path with all of them and any other object with none. A path with + // only segments selected gets no anchors here, so `select.segments` below selects it with + // just those segments. let items: Vec = kept .iter() .map(|i| { @@ -1159,12 +1161,25 @@ 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. fn path_key(p: &str) -> String { + path_key_on(p, cfg!(windows)) +} + +/// [`path_key`] treating every path as a Windows path when `windows`, else only one that starts +/// with a drive letter. +pub(crate) fn path_key_on(p: &str, windows: bool) -> String { let b = p.as_bytes(); - let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); + let windows = windows || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } @@ -1618,9 +1633,17 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { // Letter) with `presetSettings` over it, given in full so that a saved preset of the same name // does not stand in for it. Settings the built-in preset refuses are an error. let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + let mut shadowed_by = None; if let Some(first) = first { - p.insert("preset".into(), json!(first.name)); - let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?; + let full = first.clone().with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?; + let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim())); + if shadowed { + // `file.new` would find the saved preset of that name first, so the name is left out + // and the built-in preset's settings, with `presetSettings` over them, go as params. + shadowed_by = Some(first.clone()); + } else { + p.insert("preset".into(), json!(first.name)); + } if let Value::Object(settings) = full.to_json() { for key in BUILT_IN_SETTINGS { if let Some(v) = settings.get(*key) { @@ -1639,6 +1662,15 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { let reason = e["reason"].as_str().unwrap_or_default(); return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); } + // The built-in preset's settings went as params: Recent keeps its name, as `file.new` + // keeps a preset's name, unless its size changed (turning it doesn't count). + if let Some(first) = &shadowed_by { + let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); + let mut s = h.session.borrow_mut(); + if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) { + r.name.clone_from(&first.name); + } + } // Each warning from reading the profile's file goes to the console. for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); @@ -2226,7 +2258,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_length(h, a); } let doc = items_doc(h, a)?; @@ -2235,7 +2267,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer { } fn items_typename(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_typename(h, a); } items_doc(h, a)?; @@ -2243,7 +2275,7 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer { } fn items_to_string(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { layers::scoped_typename(h, a)?; return Ok(text("[PageItems]")); } @@ -2252,7 +2284,7 @@ fn items_to_string(h: &Host, a: &[Data]) -> Answer { } fn items_parent(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_parent(h, a); } let doc = items_doc(h, a)?; @@ -2265,30 +2297,55 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } +/// The answer of an indexer called with a name, from `found`, the collection's `getByName`: a +/// name nothing has gives `undefined` for `name in collection` ([`probing`]) and throws otherwise. +fn by_name_or_probe(a: &[Data], found: Answer) -> Answer { + match found { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + } +} + /// The position an indexer key names when it is an array index, 0 to 2^32 - 2. fn position(n: f64) -> Option { whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) } +/// The arguments of an indexer called with a number that is not an array index, such as `-1` or +/// `1.5`, with that key given as the text of the number, the name it is looked up by: a key such +/// as `"-1"` reaches an indexer as a number. +fn number_named(a: &[Data]) -> Option> { + let Data::Number(n) = arg(a, 1) else { return None }; + if position(*n).is_some() { + return None; + } + let mut named = a.to_vec(); + named[1] = text(vectorcraft_js::number_to_string(*n)); + Some(named) +} + +/// The answer of an indexer for a number key looked up as a name ([`number_named`]), from `found`, +/// the collection's `getByName`: `undefined` when nothing has the name. +fn named_or_undefined(found: Answer) -> Answer { + match found { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + } +} + /// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a /// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is /// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_at(h, a); } let doc = items_doc(h, a)?; match arg(a, 1) { - Data::String(_) => match items_by_name(h, a) { - Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), - r => r, - }, + Data::String(_) => by_name_or_probe(a, items_by_name(h, a)), Data::Number(n) => match position(*n) { Some(i) => item_at(h, doc, i), - None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { - Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), - r => r, - }, + None => named_or_undefined(items_named(h, doc, &vectorcraft_js::number_to_string(*n))), }, _ => Ok(Data::Undefined), } @@ -2300,7 +2357,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer { } fn items_by_name(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_by_name(h, a); } let doc = items_doc(h, a)?; @@ -2319,7 +2376,7 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_index(h, a); } match arg(a, 1) { @@ -2339,7 +2396,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { /// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, /// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; @@ -2671,8 +2728,8 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { /// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and /// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as -/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping -/// path's. +/// the visible bounds leave them out, a clip group or clipping layer gives only its clipping +/// path's, and the source art a Shaper Group or a tracing keeps is left out. fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { *steps += 1; if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { @@ -2682,7 +2739,7 @@ fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { *steps += 1; r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); } - let children = n.children().map_or(&[][..], Vec::as_slice); + let children = n.editing_children(); let children = if n.clips() { &children[..children.len().min(1)] } else { children }; for c in children { r = take_in_handles(c, r, steps); @@ -2844,7 +2901,8 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or /// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] -/// refuses it. A compound path whose last path this is stays, empty. +/// refuses it. A tracing's source image is refused when it is shown as well. A compound path whose +/// last path this is stays, empty. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (whole, on_locked) = with_doc(h, item.doc, |_, st| { @@ -2856,6 +2914,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // A tracing keeps its source image when a script has shown it, as `move` keeps it there. + if with_doc(h, item.doc, |_, st| crate::cmd::is_trace_source(&st.doc, item.id)) { + return Err(HostError::Error(SOURCE_STAYS.into())); + } // An image left first in an ordinary group named as a tracing would make that group one. if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { return Err(HostError::Error(NOT_A_TRACING.into())); @@ -3082,7 +3144,7 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul if d.parent_of(id) == Some(to.parent) { return Ok(0); } - return Err(HostError::Error("a tracing's source image cannot leave its tracing".into())); + return Err(HostError::Error(SOURCE_STAYS.into())); } let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; // The clipping path itself, put back where it is, stays the clipping path. @@ -3285,7 +3347,7 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer { } /// `toString()` of an object without a name: `[Class]`. -fn class_text(name: &'static str) -> HostMember { +pub(super) fn class_text(name: &'static str) -> HostMember { HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) } @@ -3385,6 +3447,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..95ef993284 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,7 +12,7 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's +//! `pageItems`, `groupItems`, `compoundPathItems`, `pathItems` and `textFrames`, and a compound path's //! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes @@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_ use super::{ Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, - arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, - later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity, - returns, text, typed, typename, whole, with_doc, + arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method, + named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename, + whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -66,8 +66,6 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, - /// Paths (`PathItem`). - Path, /// Type (`TextFrame`), whose collection's other members are in `text.rs`. Text, } @@ -78,7 +76,6 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", - Kind::Path => "PathItems", Kind::Text => "TextFrames", } } @@ -88,7 +85,6 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), - Kind::Path => typename(n) == Some("PathItem"), Kind::Text => typename(n) == Some("TextFrame"), } } @@ -109,14 +105,16 @@ fn result_id(v: &Value, key: &str) -> Option { /// The layer `d` names, which must still be a layer of its document. pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> { let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) }; - if handle.len() != 5 { - return Err(type_error("Layer")); - } - // A layer read before File › Revert is stale like the page items read with it. - let (doc, id) = node_of(h, &handle).ok_or_else(|| { - let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some()); - HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into()) - })?; + let [run, uid, high, low, _] = handle.as_slice() else { return Err(type_error("Layer")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + // A layer read before its document was reverted is stale as the page items read then are. + let (doc, id) = super::node_of(h, &handle).filter(|(d, _)| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + held_layer(h, doc, id) +} + +/// The layer `id` of `doc`, which must still be a layer of the document. +fn held_layer(h: &Host, doc: Doc, id: NodeId) -> Result<(Doc, NodeId)> { let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer)); if !ok { return Err(HostError::Error(STALE_LAYER.into())); @@ -128,14 +126,12 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { layer_of(h, arg(a, 0)) } -fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { - host_ref("Layer", &layer_handle(h, uid, id)) -} - -/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it. -fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] { - let [high, low] = id_parts(id); - [float(h.run), float(uid), high, low, float(reverts_of(h, uid))] +pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { + let s = h.session.borrow(); + match s.documents().iter().find(|d| d.uid == uid) { + Some(st) => host_ref("Layer", &super::node_handle(h, st, id)), + None => Data::Null, + } } /// Reads the layer `this` names with `f`. @@ -285,22 +281,23 @@ fn layer_parent(h: &Host, a: &[Data]) -> Answer { })) } +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + fn layer_typename(h: &Host, a: &[Data]) -> Answer { this_layer(h, a)?; Ok(text("Layer")) } -fn layer_to_string(h: &Host, a: &[Data]) -> Answer { - named_text("Layer", layer_name(h, a)) -} - /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// not counted. The list comes from [`layer_ids`], so reading it for each layer of a loop /// lists the layers once. Each read is still charged for the search through the list. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let list = layers_listed(h, st, st.doc.parent_of(id))?; + let list = layer_ids(h, st, st.doc.parent_of(id))?; + // The scan is charged by itself: a list kept from an earlier read was charged once. h.charge_call(list.len() as u64)?; Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) })?; @@ -535,8 +532,9 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) }; match handle.as_slice() { [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), - [run, uid, high, low, reverts] => { - let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low, *reverts]))?; + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its layer is. + let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?; Ok((doc, Some(id))) } _ => Err(type_error("Layers")), @@ -554,33 +552,33 @@ fn layer_list(d: &Document, parent: Option) -> Vec { list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() } -/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top -/// level) and the layers it listed then. +/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers. pub(super) type LayerList = (u64, Arc, Option, Rc>); -/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while -/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list -/// is charged by the objects it looks at. -fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result>> { +/// How many lists of layers [`super::State`] keeps at once. +pub(super) const LAYER_LISTS: usize = 4; + +/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a +/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at. +fn layer_ids(h: &Host, st: &DocState, parent: Option) -> Result>> { { - let mut lists = h.dom.layers.borrow_mut(); - let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); - if let Some(at) = at { + let mut lists = h.dom.layer_lists.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) { let list = lists.remove(at); let ids = list.3.clone(); lists.push(list); return Ok(ids); } } - let looked_at = match parent { + let looked = match parent { None => st.doc.layers.len(), Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), }; - h.charge_call(looked_at as u64)?; + h.charge_call(looked as u64)?; let ids = Rc::new(layer_list(&st.doc, parent)); - let mut lists = h.dom.layers.borrow_mut(); + let mut lists = h.dom.layer_lists.borrow_mut(); lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); - if lists.len() >= ART_LISTS { + if lists.len() >= LAYER_LISTS { lists.remove(0); } lists.push((st.uid, st.doc.clone(), parent, ids.clone())); @@ -589,12 +587,12 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result Answer { let (doc, id) = this_layer(h, a)?; - Ok(host_ref("Layers", &layer_handle(h, doc.uid, id))) + Ok(host_ref("Layers", &super::scoped_handle(h, doc.uid, id))) } fn layers_length(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; - Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64))) + Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -607,30 +605,26 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("Layers")) } -/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when -/// nothing has the name, as the document's `pageItems` does. -fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer { - match by_name(h, a) { - Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), - r => r, - } -} - +/// `layers[i]`, and `layers["name"]` as `getByName` reads it. A number key that is not an array +/// index, such as `-1`, is looked up as a name, as `pageItems` looks it up. fn layers_at(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; if let Data::String(_) = arg(a, 1) { - return read_by_name(h, a, layers_by_name); + return super::by_name_or_probe(a, layers_by_name(h, a)); + } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(layers_by_name(h, &named)); } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) + let Some(i) = super::position(*n) else { return Ok(Data::Undefined) }; + with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) } fn layers_by_name(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = layers_listed(h, st, parent)?; + let ids = layer_ids(h, st, parent)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -640,6 +634,8 @@ fn layers_by_name(h: &Host, a: &[Data]) -> Answer { fn layers_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => layers_by_name(h, a), + // A number is a position here, never a name ([`layers_at`]). + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match layers_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -673,7 +669,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { if parent.is_none() { return Err(HostError::Error("a document needs at least one layer".into())); } - let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?; + let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?; // `layer.delete` takes at most this many rows; more is refused before anything is deleted. if ids.len() > crate::cmd::layer::MAX_ROWS { return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS))); @@ -692,13 +688,11 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) }; match handle.as_slice() { [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), - [run, uid, high, low, reverts] => { - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - // A collection read before File › Revert is stale like its container. + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its container is. + let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let holds = with_doc(h, doc, |_, st| { - whole(*reverts) == Some(st.reverts) - && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) }); if !holds { return Err(HostError::Error(STALE_ITEM.into())); @@ -755,23 +749,15 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R Ok(ids) } -/// Whether a `PageItems` or `PathItems` object's handle names its container. -pub(super) fn is_scoped(a: &[Data], class: &str) -> bool { - host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5) -} - -fn scoped_kind(a: &[Data]) -> Kind { - if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any } -} - -/// How many times File › Revert has reloaded the document with uid `uid`. -fn reverts_of(h: &Host, uid: u64) -> u64 { - h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts) +/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle +/// names the container. +pub(super) fn is_scoped(a: &[Data]) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5) } fn collection(h: &Host, kind: Kind, container: Option, uid: u64) -> Data { match container { - Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]), + Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)), None => host_ref(kind.class(), &[float(h.run), float(uid)]), } } @@ -787,26 +773,19 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } +/// `collection[i]`, and `collection["name"]` as `getByName` reads it. A number key that is not an +/// array index, such as `-1`, is looked up as a name, as the document's `pageItems` looks it up. fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; if let Data::String(_) = arg(a, 1) { - return match art_by_name(h, a, kind) { - Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), - r => r, - }; + return super::by_name_or_probe(a, art_by_name(h, a, kind)); + } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(art_by_name(h, &named, kind)); } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) { - Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))), - // The text of a number that is not an array index is looked up as a name. - None => with_doc(h, doc, |_, st| { - let ids = art_list(h, st, kind, c)?; - h.charge_call(ids.len() as u64)?; - let name = vectorcraft_js::number_to_string(*n); - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); - Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id))) - }), - } + let Some(i) = super::position(*n) else { return Ok(Data::Undefined) }; + with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { @@ -814,6 +793,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { let ids = art_list(h, st, kind, c)?; + // The scan is charged by itself: a list kept from an earlier read was charged once. h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -823,8 +803,9 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { match arg(a, 1) { Data::String(_) => art_by_name(h, a, kind), - // A number is a position only. A stale collection throws its stale error first. - Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + // A number is a position here, never a name ([`art_at`]). A stale collection throws its + // stale error first. + Data::Number(n) if super::position(*n).is_none() => { art_scope(h, arg(a, 0), kind.class())?; Err(HostError::Error(NOT_FOUND.into())) } @@ -839,7 +820,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| { @@ -852,36 +834,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); let locks = d.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - // A clipping path whose group or layer keeps other art would leave the next object clipping it. - // Deleting every path of a compound path would leave it empty, so a compound path that - // clips counts as deleted too. - let mut going: std::collections::HashSet = ids.iter().copied().collect(); - let mut seen = std::collections::HashSet::new(); - let mut emptied: Vec = Vec::new(); - for p in ids.iter().filter_map(|i| d.parent_of(*i)) { - if going.contains(&p) || !seen.insert(p) { - continue; - } - let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id))); - if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) { - emptied.push(p); - } - } - going.extend(emptied.iter().copied()); - let masks: Vec = ids - .iter() - .chain(&emptied) - .filter(|i| { - d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| { - let kids = p.children().map_or(&[][..], Vec::as_slice); - p.clips() - && kids.first().is_some_and(|f| f.id == **i) - && kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) - }) - }) - .map(|i| i.0) - .take(20) - .collect(); + let masks = kept_clipping_paths(d, &ids); Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { @@ -892,12 +845,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } - if !masks.is_empty() { - let list = masks.iter().map(u64::to_string).collect::>().join(", "); - return Err(HostError::Error(format!( - "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" - ))); - } + refuse_kept_clipping_paths(&masks)?; // Deleting the objects above an image in an ordinary group named as a tracing would make it one. if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { return Err(HostError::Error(super::NOT_A_TRACING.into())); @@ -908,29 +856,75 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { Ok(Data::Undefined) } -/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]). +/// The ids (at most 20) among `ids` that are the clipping path of a group or layer that keeps other +/// objects once `ids` are deleted. Deleting one would leave the next object clipping the rest. +/// Deleting every path of a compound path would leave it empty, so a compound path that clips +/// counts as deleted too. +pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec { + let mut going: std::collections::HashSet = ids.iter().copied().collect(); + let mut seen = std::collections::HashSet::new(); + let mut emptied: Vec = Vec::new(); + for p in ids.iter().filter_map(|i| d.parent_of(*i)) { + if going.contains(&p) || !seen.insert(p) { + continue; + } + let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id))); + if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) { + emptied.push(p); + } + } + going.extend(emptied.iter().copied()); + ids.iter() + .chain(&emptied) + .filter(|i| { + d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| { + let kids = p.children().map_or(&[][..], Vec::as_slice); + p.clips() + && kids.first().is_some_and(|f| f.id == **i) + && kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + }) + }) + .map(|i| i.0) + .take(20) + .collect() +} + +/// The error of a `removeAll()` that would delete the clipping paths `masks`, or `Ok` when there +/// are none. +pub(super) fn refuse_kept_clipping_paths(masks: &[u64]) -> std::result::Result<(), HostError> { + if masks.is_empty() { + return Ok(()); + } + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))) +} + +/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their +/// handle names one ([`is_scoped`]). pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { - art_length(h, a, scoped_kind(a)) + art_length(h, a, Kind::Any) } pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { - art_parent(h, a, scoped_kind(a)) + art_parent(h, a, Kind::Any) } pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { - art_at(h, a, scoped_kind(a)) + art_at(h, a, Kind::Any) } pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { - art_by_name(h, a, scoped_kind(a)) + art_by_name(h, a, Kind::Any) } pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { - art_index(h, a, scoped_kind(a)) + art_index(h, a, Kind::Any) } pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { - art_remove_all(h, a, scoped_kind(a)) + art_remove_all(h, a, Kind::Any) } fn groups_length(h: &Host, a: &[Data]) -> Answer { @@ -976,7 +970,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { - art_typename(h, a, scoped_kind(a)) + art_typename(h, a, Kind::Any) } fn groups_typename(h: &Host, a: &[Data]) -> Answer { art_typename(h, a, Kind::Group) @@ -986,15 +980,20 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer { } /// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the -/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. -/// → the new object. +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. A +/// Live Paint group takes none. → the new object. fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; if let Some(c) = c { - let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let (compound, live) = with_doc(h, doc, |_, st| { + (st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })), super::paths::is_live_paint_group(st, c)) + }); if compound { return Err(HostError::Error("a compound path holds only paths".into())); } + if live { + return Err(HostError::Error(super::paths::LIVE_PAINT_CONTAINER.into())); + } } let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); if kind == Kind::Compound @@ -1039,10 +1038,6 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Any) } -fn held_paths(h: &Host, a: &[Data]) -> Answer { - held(h, a, Kind::Path) -} - fn held_groups(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Group) } @@ -1051,6 +1046,24 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]). +fn held_paths(h: &Host, a: &[Data]) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(super::paths::held_path_items(h, doc.uid, id)); + } + let item = this_item_of(h, a, "GroupItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + +/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it +/// ([`super::paths`]). +fn compound_paths(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + fn held_text(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Text) } @@ -1126,12 +1139,13 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("pathItems", get(l, held_paths), listed("PathItems")), ("textFrames", get(l, held_text), listed("TextFrames")), ]); - m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths), listed("PathItems"))]), _ => Vec::new(), } } @@ -1195,19 +1209,22 @@ fn board_index(st: &DocState, id: u32) -> Option { st.doc.artboards.iter().position(|a| a.id == id) } +/// The artboard `d` names. An artboard read before its document was reverted is stale, as a page +/// item is: the loaded document's artboard with the same id is another artboard. fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> { let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) }; let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) }; let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; - // An artboard read before File › Revert is stale, as the page items read with it are. let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts))) .ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; Ok((Board { doc }, index)) } +/// An `Artboard` for the artboard `id` of the document `uid`, with the document's revert count. fn board_ref(h: &Host, uid: u64, id: u32) -> Data { - host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))]) + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); + host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)]) } fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> { @@ -1434,13 +1451,18 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) } +/// `artboards[i]`, and `artboards["name"]` as `getByName` reads it. A number key that is not an +/// array index, such as `-1`, is looked up as a name, as `pageItems` looks it up. fn boards_at(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; if let Data::String(_) = arg(a, 1) { - return read_by_name(h, a, boards_by_name); + return super::by_name_or_probe(a, boards_by_name(h, a)); + } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(boards_by_name(h, &named)); } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let Some(i) = super::position(*n) else { return Ok(Data::Undefined) }; Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) } @@ -1457,6 +1479,8 @@ fn boards_by_name(h: &Host, a: &[Data]) -> Answer { fn boards_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => boards_by_name(h, a), + // A number is a position here, never a name ([`boards_at`]). + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match boards_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -1542,7 +1566,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { } { let mut chosen = h.dom.chosen_artboards.borrow_mut(); - let reverts = reverts_of(h, doc.uid); + let reverts = with_doc(h, doc, |_, st| st.reverts); if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { *generation = reverts; } else { @@ -1600,13 +1624,14 @@ pub(super) fn classes(l: &Link) -> Vec { ("printable", property(l, layer_printable, layer_set_printable), typed("boolean")), ("preview", property(l, layer_preview, layer_set_preview), typed("boolean")), ("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")), - ("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")), + ("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), ("color", property(l, layer_color, layer_set_color), typed("RGBColor")), ("parent", get(l, layer_parent), typed("*")), ("layers", get(l, layers_of), listed("Layers")), ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("pathItems", get(l, held_paths), listed("PathItems")), ("textFrames", get(l, held_text), listed("TextFrames")), ("zOrderPosition", get(l, layer_z_position), typed("number")), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")), @@ -1616,9 +1641,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ("toString", method(l, layer_to_string), returns("string", &[])), ]); - layer.extend( - ["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), - ); + layer.extend(["symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m))); vec![ class("Layer", None, layer, None), class( @@ -1679,7 +1702,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("name", property(l, board_name, board_set_name), typed("string")), ("parent", get(l, board_parent), typed("Document")), ("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin), typed("Array")), - ("rulerPAR", property(l, board_par, board_set_par), typed("number")), + ("rulerPAR", property(l, board_par, board_set_par), MemberInfo { min: Some(0.1), max: Some(10.0), ..typed("number") }), ("showCenter", property(l, board_center, board_set_center), typed("boolean")), ("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")), ("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index da8ac4c6b0..cc1cbe6a62 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -13,7 +13,9 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside -//! groups and compound paths included. +//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in +//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden +//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing //! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked @@ -26,8 +28,8 @@ //! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever -//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's +//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -68,9 +70,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point, - point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, + Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command, + coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -168,8 +170,16 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &handle) } +#[cfg(test)] +thread_local! { + /// How many times [`point_starts`] counted the points of a path on this thread. + static INDEX_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// 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 { @@ -206,6 +216,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result std::result::Result std::result::Result u64 { + INDEX_BUILDS.with(std::cell::Cell::get) +} + /// The subpath and the place in it of point `i`, among the subpaths `subs`. fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { for (s, sp) in subs.iter().enumerate() { @@ -265,7 +285,20 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its /// points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { - forget_waiting_starts(h); + edit_points_keeping(h, item, false, f) +} + +/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as +/// they are, so the [`starts`] of the waiting changes stay kept. +fn edit_points_keeping( + h: &super::Host, + item: Item, + counts_kept: bool, + f: impl FnOnce(&mut Vec) -> T, +) -> std::result::Result { + if !counts_kept { + forget_waiting_starts(h); + } if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { @@ -306,7 +339,7 @@ fn forget_waiting_starts(h: &super::Host) { fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> { let counted = point_starts(h, item)?; let at = locate_at(&counted, i); - edit_points(h, item, |subs| { + edit_points_keeping(h, item, true, |subs| { if let Some((s, j)) = at && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { @@ -452,19 +485,48 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { r } -// ---- Document.pathItems ---- +// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ---- -/// The ids of a document's paths, in the order of its page items. Building the list again counts -/// the page items it looks through against the run's host-call allowance. -fn path_items(h: &super::Host, st: &DocState) -> Result>, HostError> { - if let Some(ids) = super::kept_list(&h.dom.paths, st) { - return Ok(ids); +/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the +/// document's), and the ids it listed then. +pub(super) type PathList = (u64, Arc, Option, Rc>); + +/// How many lists of paths [`super::State`] keeps at once. +pub(super) const PATH_LISTS: usize = 4; + +/// The ids of a document's paths, in the order of its page items, or of the paths directly in the +/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their +/// documents are unchanged, so a loop over a collection builds its list once. A new list is +/// charged by the objects it looks at. +fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + { + let mut lists = h.dom.paths.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } } - let all = super::page_items(h, st)?; - h.charge_call(all.len() as u64)?; - let ids: Rc> = - Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); - super::keep_list(&h.dom.paths, st, &ids); + let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. }); + let ids: Rc> = match container { + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect()) + } + None => { + let all = super::page_items(h, st)?; + h.charge_call(all.len() as u64)?; + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) + } + }; + let mut lists = h.dom.paths.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= PATH_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), container, ids.clone())); Ok(ids) } @@ -473,54 +535,66 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } -fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { - if super::layers::is_scoped(a, "PathItems") { - return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into())); +/// The `pathItems` of the layer or group `id` in the document `uid`. +pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { + host_ref("PathItems", &super::scoped_handle(h, uid, id)) +} + +/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths +/// of, if any. +fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)), + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its container is. + let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let holds = with_doc(h, doc, |_, st| { + st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + }); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(HostError::Type("this is not a PathItems".into())), } - doc_of(h, arg(a, 0), "PathItems") } /// `typename` of the paths of a document that is still open. fn items_typename(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_typename(h, a); - } - items_doc(h, a)?; + items_scope(h, a)?; Ok(Data::String("PathItems".into())) } fn items_length(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_length(h, a); - } - let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) + let (doc, c) = items_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_parent(h, a); - } - let doc = items_doc(h, a)?; - Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) + let (doc, c) = items_scope(h, a)?; + Ok(match c { + None => host_ref("Document", &[float(h.run), float(doc.uid)]), + Some(c) => with_doc(h, doc, |_, st| { + if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) } + }), + }) } /// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a /// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is /// looked up as that name, giving `undefined` when no path has it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_at(h, a); - } - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; match arg(a, 1) { Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), r => r, }, Data::Number(n) => match super::position(*n) { - Some(i) => item_at(h, doc, i), - None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Some(i) => item_at(h, doc, c, i), + None => match items_named(h, doc, c, &vectorcraft_js::number_to_string(*n)) { Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), r => r, }, @@ -530,23 +604,20 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { } /// The path at position `i` of `pathItems`, or `undefined` past the end. -fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer { - with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) +fn item_at(h: &super::Host, doc: Doc, c: Option, i: usize) -> Answer { + with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_by_name(h, a); - } - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; - items_named(h, doc, name) + items_named(h, doc, c, name) } /// The first path of `pathItems` named `name`, or `Not found`. -fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { +fn items_named(h: &super::Host, doc: Doc, c: Option, name: &str) -> Answer { with_doc(h, doc, |_, st| { - let ids = path_items(h, st)?; + let ids = path_items(h, st, c)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -554,14 +625,11 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_index(h, a); - } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { - let doc = items_doc(h, a)?; - match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? { + let (doc, c) = items_scope(h, a)?; + match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, c, i)).transpose()? { Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())), Some(d) => Ok(d), } @@ -570,18 +638,17 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } } -/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before -/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or -/// layer that keeps other objects, or a compound path or group that clips one and would be left -/// with no visible path or visible type that lays out glyphs to clip by. +/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or +/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it +/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's +/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does. +/// It also throws and deletes nothing when it would delete the clipping path of a group or layer +/// that keeps other objects, or leave a compound path or group that clips one with no visible path +/// or visible type that lays out glyphs to clip by. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_remove_all(h, a); - } - let doc = items_doc(h, a)?; - let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st)?; + let (doc, c) = items_scope(h, a)?; + let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| { + let ids = path_items(h, st, c)?; let d = &st.doc; if h.session.borrow().menu.guides_locked && let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) @@ -623,8 +690,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let mut masks = Vec::new(); for n in nodes.into_iter().rev() { let kids = n.children().map_or(&[][..], Vec::as_slice); - // Clear removes compound paths emptied of direct members, but keeps empty groups. - if matches!(n.kind, NodeKind::Compound { .. }) + // Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps + // empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty. + if c.is_none() + && matches!(n.kind, NodeKind::Compound { .. }) && !kids.is_empty() && kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id)) { @@ -657,7 +726,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { masks.push(mask.id.0); } } - Ok::<_, HostError>((ids, refused, on_locked, masks)) + let going: Vec = going.into_iter().collect(); + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + let tracing = super::removal_makes_tracing(d, &going); + Ok::<_, HostError>((ids, refused, on_locked, masks, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -667,14 +739,13 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } - if !masks.is_empty() { - let list = masks.iter().map(u64::to_string).collect::>().join(", "); - return Err(HostError::Error(format!( - "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" - ))); + super::layers::refuse_kept_clipping_paths(&masks)?; + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": c.is_some()}); + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?; } Ok(Data::Undefined) } @@ -685,13 +756,66 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, -/// and reverses the new path's direction when `reversed`. → the new path. Selecting the new path -/// and putting the selection back load the selected objects' paint and stroke width into new art, -/// so new art's paint from before, the defaults a script set included, is put back. -fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { - let made = keeping_paint(h, || { - on_doc(h, doc.uid, true, |h| { +/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or +/// locked layer or group. +pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group"; + +/// The error of an object made in a Live Paint group, which would join the group's paths instead +/// of staying in the group's own list. +pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group"; + +/// Whether `id` is a Live Paint group, which takes no new objects from the object model. +pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool { + st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint) +} + +/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the +/// selection and the current layer kept. With a layer or group `container`, the container's layer +/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made +/// outside the container then moves on top of its contents in the same step; a container that is +/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`] +/// before anything is made, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → the new path. +fn make_in( + h: &super::Host, + doc: Doc, + container: Option, + make: impl FnOnce(&super::Host) -> std::result::Result, +) -> Answer { + if let Some(c) = container { + let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c))); + if !open { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + if live { + return Err(HostError::Error(LIVE_PAINT_CONTAINER.into())); + } + } + let made = match container { + // Making a path can take more than one command (a stroke, a reversal): a failure of a later + // one undoes the path too. + None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?, + Some(c) => super::atomically(h, |h| { + let id = on_doc(h, doc.uid, true, |h| { + command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; + make(h) + })?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?, + }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s +/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. +/// Selecting the new path and putting the selection back load the selected objects' paint and +/// stroke width into new art, so new art's paint from before, the defaults a script set included, +/// is put back. +fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { + keeping_paint(h, || { + make_in(h, doc, container, |h| { let parent = with_doc(h, doc, |_, st| new_path_layer(st)); let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { @@ -699,10 +823,7 @@ fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> } Ok(id) }) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } /// Argument `i`, or `default` when it is left out. @@ -743,13 +864,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result /// `rectangle(top, left, width, height, reversed?)`. fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); let reversed = flag(a, 5, "reversed")?; let p = corner(h, doc, left, top)?; - make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the @@ -789,7 +910,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { /// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, /// reversed = false)`: a closed path with `path.create`. fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); @@ -797,12 +918,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { let reversed = flag(a, 7, "reversed")?; let p = corner(h, doc, left, top)?; let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); - make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) + make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) } /// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); @@ -811,7 +932,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); } let p = corner(h, doc, left, top)?; - make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The center of a polygon or star, in document coordinates. @@ -823,37 +944,38 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r = size(a, 3, Some(50.0), "radius")?; let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; let reversed = flag(a, 5, "reversed")?; - make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) + make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) } /// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = /// false)`. fn items_star(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r1 = size(a, 3, Some(50.0), "radius")?; let r2 = size(a, 4, Some(20.0), "innerRadius")?; let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; let reversed = flag(a, 6, "reversed")?; - make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) + make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with -/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open -/// path is set back to none in the same step, and new art keeps the paint it had before. +/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or +/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art. +/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set +/// back to none in the same step, and new art keeps the paint it had before. fn items_add(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; // New art's paint is read with the document active, since activating a document can load its // selection's appearance into new art. Selecting the new path loads its temporary stroke into // new art, and putting the selection back does not undo that, so new art's paint from before // the path is put back. - let made = keeping_paint(h, || { - on_doc(h, doc.uid, true, |h| { + keeping_paint(h, || { + make_in(h, doc, into, |h| { let unpainted = { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() @@ -865,10 +987,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { } Ok(id) }) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } // ---- PathItem geometry ---- @@ -887,13 +1006,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| { - if subs.is_empty() && closed { - subs.push(SubPath::new(Vec::new(), closed)); - } else { - subs.iter_mut().for_each(|sp| sp.closed = closed); - } - })?; + // A path with no subpath gets an empty closed one to keep the value in; any other change keeps + // the number of points, so the kept starts of the waiting changes stay valid. + if closed && read_points(h, item, |subs| subs.is_empty())? { + edit_points(h, item, |subs| subs.push(SubPath::new(Vec::new(), closed)))?; + } else { + edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + } Ok(Data::Undefined) } @@ -1902,18 +2021,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(); @@ -2124,6 +2242,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])), ("add", point_method(l, points_add), returns("PathPoint", &[])), ("removeAll", point_method(l, points_remove_all), returns("undefined", &[])), + ("toString", class_text("PathPoints"), returns("string", &[])), ]), Some(super::point_function(l, points_at)), ), @@ -2143,6 +2262,7 @@ pub(super) fn classes(l: &Link) -> Vec { typed("PathPointSelection"), ), ("remove", point_method(l, pt_remove), returns("undefined", &[])), + ("toString", class_text("PathPoint"), returns("string", &[])), ]), None, ), 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..b50ee6b858 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2644,11 +2644,10 @@ impl Session { RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } - // One more allowance may still leave the growth past it: the person is asked again - // while they may be, and past that the run ends unkept. - if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) { - let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }; - return Some(self.script_failed(job, &e)); + // What the script added must fit the allowance the last answer gave: past it, the + // person is asked again, as a running script is at its next charge. + if let Err(e) = job.host.charge_growth(0, 0) { + return Some(self.script_failed(job, &end_flush_error(e))); } if job.host.waiting.get() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); @@ -2682,14 +2681,24 @@ impl Session { self.script_key = Some(key); None } - // The point changes written as the script ended went past the growth allowance. - Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => { - job.finished = true; - JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); - self.script_key = Some(key); - None + Ok(Ok(Progress::Done(_))) => { + // What the script added must fit the allowance the last answer gave, which one + // answer can leave short of what the script had already added. + if !job.host.waiting.get() + && let Err(e) = job.host.charge_growth(0, 0) + { + return Some(self.script_failed(job, &end_flush_error(e))); + } + // The point changes written as the script ended, or what it added before, went past + // the growth allowance. + if job.host.waiting.get() { + job.finished = true; + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + return None; + } + Some(self.script_ended(job)) } - Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)), } } @@ -3188,6 +3197,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/css.rs b/crates/engine/src/tests/css.rs index 982bf51d24..3d86e558b6 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -173,12 +173,12 @@ fn export_writes_the_sheet_and_rasterized_art() { // Without a path: the CSS as data, the pictures as base64. let r = run(&mut s, "css.export", json!({"scope": "all", "rasterize": true})); let data = r["data"].as_str().unwrap(); - assert!(data.contains(".rectangle {") && data.contains(".path {\n") && data.contains("background-image: url(path.png);"), "{data}"); + assert!(data.contains(".rectangle {") && data.contains(".star {\n") && data.contains("background-image: url(star.png);"), "{data}"); assert!(data.ends_with("}\n")); assert_eq!(r["rules"], json!(2)); let images = r["images"].as_array().unwrap(); assert_eq!(images.len(), 1, "only the star is rasterized"); - assert_eq!(images[0]["name"], json!("path.png")); + assert_eq!(images[0]["name"], json!("star.png")); let png = vectorcraft_format::base64_decode(images[0]["dataBase64"].as_str().unwrap()).unwrap(); assert!(png.starts_with(b"\x89PNG")); // The selection alone (the star, selected last). @@ -263,9 +263,9 @@ fn export_to_a_path_puts_the_pictures_next_to_the_sheet() { let path = dir.join("site.css"); let r = run(&mut s, "css.export", json!({"path": path.to_string_lossy(), "rasterize": true})); let written = std::fs::read_to_string(&path).unwrap(); - assert!(written.contains("url(path.png)"), "{written}"); + assert!(written.contains("url(star.png)"), "{written}"); assert_eq!(r["bytes"], json!(written.len())); - let png = dir.join("path.png"); + let png = dir.join("star.png"); assert_eq!(r["images"], json!([png.to_string_lossy()])); assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG")); std::fs::remove_dir_all(&dir).ok(); 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/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 34e01bf31e..23f703af6a 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Node; +use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use crate::*; @@ -181,3 +182,240 @@ fn warps_keep_the_map_their_version_names() { } assert_eq!(node(&s, id).appearance.effects.len(), 2); } + +#[test] +fn rendered_warning_is_in_effect_command_results() { + let (mut s, _) = session_with_rect(); + run( + &mut s, + "paint.setFill", + json!({"gradient": {"kind": "linear", "stops": [ + {"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"} + ]}}), + ); + let warning = vectorcraft_render::effects::rendered::OPAQUE_ONLY; + let applied = run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered"}}})); + assert_eq!(applied["warning"], warning); + let shaded = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded"}}})); + assert!(shaded.get("warning").is_none()); + let params = json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered"}}}); + assert_eq!(run(&mut s, "effect.setParams", params.clone())["warning"], warning); + assert_eq!(run(&mut s, "effect.setParams", params)["warning"], warning, "unchanged settings still report the fallback"); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + let plain = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}})); + assert!(plain.get("warning").is_none()); +} + +/// The color space of each color image (not a soft mask) in PDF `bytes`, in order. +fn image_spaces(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes); + let mut out = vec![]; + for (at, _) in text.match_indices("/Subtype/Image") { + let start = text[..at].rfind(" obj").unwrap_or(0); + let end = text[at..].find("stream").map_or(text.len(), |e| at + e); + let dict = &text[start..end]; + let Some(cs) = dict.find("/ColorSpace") else { continue }; + let name = dict[cs + "/ColorSpace".len()..].trim_start_matches(['[', ' ', '/']); + let space: String = name.chars().take_while(|c| c.is_ascii_alphanumeric()).collect(); + if space != "DeviceGray" { + out.push(space); + } + } + out +} + +/// In a CMYK document, PDF export writes a rendered 3D object as it writes a raster effect: one +/// image in the color space a drop shadow's image takes, kept in RGB by default and converted to +/// CMYK by Press Quality. +#[test] +fn a_rendered_3d_object_in_a_cmyk_pdf_is_written_as_raster_effects_are() { + let spaces = |effect: &str, params: Value, preset: Option<&str>| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params})); + let v = s.execute("document.exportPdf", &preset.map_or(json!({}), |name| json!({"preset": name}))).unwrap(); + image_spaces(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()) + }; + let rendered = json!({"render": {"mode": "rendered", "quality": "low"}}); + let shadow = json!({"x": 6.0, "y": 6.0, "blur": 3.0, "opacity": 75.0}); + for preset in [None, Some("Press Quality")] { + let three_d = spaces("threeD.extrude", rendered.clone(), preset); + let dropped = spaces("stylize.dropShadow", shadow.clone(), preset); + assert_eq!(three_d.len(), 1, "{preset:?}: one image of the rendered object: {three_d:?}"); + assert_eq!(dropped.len(), 1, "{preset:?}: {dropped:?}"); + assert_eq!(three_d, dropped, "{preset:?}: the rendered image takes the drop shadow's color space"); + } + assert_eq!(spaces("threeD.extrude", rendered, Some("Press Quality")), vec!["DeviceCMYK".to_string()]); +} + +/// A selected 100 pt square filled blue with no stroke, rendered by Extrude at Low quality, and +/// `after` (effect, params) applied after it. +fn rendered_square(after: &[(&str, Value)]) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}})); + for (effect, params) in after { + run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params})); + } + s +} + +/// The `/Width` of each color image (not a soft mask) in PDF `bytes`. +fn image_widths(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes); + let mut out = vec![]; + for (at, _) in text.match_indices("/Subtype/Image") { + let start = text[..at].rfind(" obj").unwrap_or(0); + let end = text[at..].find("stream").map_or(text.len(), |e| at + e); + let dict = &text[start..end]; + if dict.contains("/DeviceGray") { + continue; + } + if let Some(w) = dict.find("/Width") { + out.push(dict[w + "/Width".len()..].trim_start().chars().take_while(char::is_ascii_digit).collect::().parse().unwrap()); + } + } + out +} + +/// PDF and SVG export write one image for a rendered 3D object, and Expand Appearance leaves one +/// embedded image of the same size in pixels that covers the object. +#[test] +fn export_and_expand_write_one_image_of_a_rendered_3d_object() { + let mut s = rendered_square(&[]); + let pdf = s.execute("document.exportPdf", &json!({})).unwrap(); + let widths = image_widths(&vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap()); + assert_eq!(widths.len(), 1, "{widths:?}"); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert_eq!(svg.matches("= 200.0 - 1e-6, "the image spans {x0} to {x1}"); +} + +/// PNG export draws a rendered 3D object as the canvas draws it at export quality. The rendered image takes as many +/// pixels as the shaded faces' bounds times the resolution over 72, rounded up to whole pixels as a +/// raster effect's image is (`effect_region` in `crates/engine/src/cmd/rasterfx.rs`), at the +/// effect's own resolution and at the document's raster effects resolution. +#[test] +fn png_export_matches_the_canvas_and_the_image_takes_the_raster_effect_size() { + for (doc_ppi, resolution) in [(72.0, Some(150.0)), (150.0, None), (300.0, Some(37.0))] { + let what = format!("document {doc_ppi} ppi, effect {resolution:?}"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300, "rasterEffectsPpi": doc_ppi})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + let render = json!({"mode": "rendered", "quality": "low", "resolution": resolution}); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": render}})); + let png = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap(); + let png = image::load_from_memory(&vectorcraft_format::base64_decode(png["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let doc = &s.doc().unwrap().doc; + // The canvas drawn at export quality (precise, supersampled and with templates left out) and + // at the resolution PNG export takes by default, the document's raster resolution. + let quality = RasterExportOptions::default().render_options(RasterFormat::Png); + let canvas = vectorcraft_render::Renderer::new().render_region_with(doc, doc.artboards[0].rect, doc_ppi / 72.0, &quality); + assert_eq!((png.width(), png.height()), (canvas.width, canvas.height), "{what}"); + let changed = png.as_raw().chunks(4).zip(canvas.to_straight().chunks(4)).filter(|(a, b)| a != b).count(); + assert_eq!(changed, 0, "{what}: pixels of the PNG export that differ from the canvas"); + let drawn = |s: &Session| { + let doc = &s.doc().unwrap().doc; + let mut object = None; + for layer in &doc.layers { + layer.walk(&mut |n| { + if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") { + object = Some(n.clone()); + } + }); + } + vectorcraft_render::effects::solid_art_drawn_in(Some(doc), &object.unwrap()).unwrap() + }; + let mut images = vec![]; + drawn(&s).walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + images.push((**im).clone()); + } + }); + assert_eq!(images.len(), 1, "{what}"); + run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded"}}})); + let mut faces: Option = None; + drawn(&s).walk(&mut |n| { + if let Some(b) = n.path_data().and_then(vectorcraft_geom::PathData::bounds) { + faces = Some(faces.map_or(b, |f| f.union(b))); + } + }); + let faces = faces.unwrap(); + let scale = resolution.unwrap_or(doc_ppi) / 72.0; + let expected = ((faces.width() * scale).ceil().max(1.0) as u32, (faces.height() * scale).ceil().max(1.0) as u32); + assert_eq!((images[0].width, images[0].height), expected, "{what}: the image's pixels for faces {faces:?}"); + } +} + +/// The page bounds, in whole points, of the pixels the canvas covers in session `s`. +fn covered(s: &Session) -> (Vec, [u32; 4]) { + let img = + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), 1.0, false); + let mut b = [u32::MAX, u32::MAX, 0, 0]; + for (i, p) in img.pixels.chunks(4).enumerate() { + if p[3] > 8 { + let (x, y) = (i as u32 % img.width, i as u32 / img.width); + b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)]; + } + } + (img.pixels, b) +} + +/// Gaussian Blur spreads a rendered 3D image past its edges and Transform moves it. Roughen +/// draws the shaded faces instead and reports why. +#[test] +fn effects_after_a_rendered_3d_effect_keep_the_image_or_reshape_the_faces() { + let (_, at) = covered(&rendered_square(&[])); + let (_, blurred) = covered(&rendered_square(&[("blur.gaussian", json!({"radius": 5.0}))])); + assert!(blurred[0] + 2 <= at[0] && blurred[2] >= at[2] + 2, "blurred {blurred:?} against {at:?}"); + let (_, moved) = covered(&rendered_square(&[("distort.transform", json!({"moveH": 50.0}))])); + assert_eq!([moved[0], moved[2]], [at[0] + 50, at[2] + 50], "moved {moved:?} against {at:?}"); + let rough = rendered_square(&[("distort.roughen", json!({"size": 5.0}))]); + let doc = &rough.doc().unwrap().doc; + let mut object = None; + for layer in &doc.layers { + layer.walk(&mut |n| { + if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") { + object = Some(n.clone()); + } + }); + } + let object = object.unwrap(); + let art = vectorcraft_render::effects::solid_art_drawn_in(Some(doc), &object).unwrap(); + let mut has_image = false; + let mut has_faces = false; + art.walk(&mut |n| { + has_image |= matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)); + has_faces |= n.path_data().is_some(); + }); + assert!(!has_image); + assert!(has_faces); + assert_eq!( + vectorcraft_render::effects::rendered_warning(doc, &object).as_deref(), + Some("A later effect reshapes the 3D object's paths; showing the shaded faces instead") + ); +} 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/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 42e39552aa..46a4ace011 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -334,7 +334,7 @@ fn corners_of_a_non_square_rectangle_are_alike_circles() { assert_spans(&s, id, [8.0; 4]); } -/// A selected five-pointed star at (200, 200) of radii 60 and 30: a plain path. +/// A selected five-pointed live star at (200, 200) of radii 60 and 30. fn star(s: &mut Session) -> NodeId { NodeId(s.execute("shape.star", &json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap()) } @@ -357,8 +357,8 @@ fn radii(s: &Session, id: NodeId) -> [f64; N] { std::array::from_fn(|k| c.radius(k)) } -/// #511: a star (a plain path) rounds all ten corners as one step, keeps them editable (a new -/// radius cuts the outline again rather than the cut path), and is the plain star again at 0. +/// #511: a live star rounds all ten corners as one step, keeps them editable (a new radius cuts +/// the outline again rather than the cut path), and is the sharp star again at 0. #[test] fn a_star_rounds_its_corners_and_keeps_them_live() { let (mut s, _) = session(); @@ -370,17 +370,102 @@ fn a_star_rounds_its_corners_and_keeps_them_live() { assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); let (path, live) = node_path(&s, id); assert_eq!(path.anchor_count(), 20); - assert!(matches!(&live, Some(LiveShape::Path { base, .. }) if *base == sharp), "{live:?}"); + assert!(matches!(&live, Some(l @ LiveShape::Star { points: 5, .. }) if l.polygon_outline() == sharp), "{live:?}"); assert_eq!(style(&s, id), (Some(4.0), Some(CornerKind::Round), 10)); - assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Path"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Star"); run(&mut s, json!({"radius": 6, "kind": "chamfer"})); assert_eq!((node_path(&s, id).0.anchor_count(), style(&s, id)), (20, (Some(6.0), Some(CornerKind::Chamfer), 10))); run(&mut s, json!({"radius": 0, "kind": "round"})); - assert_eq!(node_path(&s, id), (sharp, None)); + let (path, live) = node_path(&s, id); + assert_eq!(path, sharp); + assert!(matches!(&live, Some(LiveShape::Star { radii, kinds, .. }) if radii.is_empty() && kinds.is_empty()), "{live:?}"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(style(&s, id).0, Some(6.0)); } +/// #4339: a live star takes a new point count and ratio from `object.setLiveShape` in one undo +/// step each, keeps the corner radius its corners shared, and records nothing when the values +/// are the ones it has. A count or ratio out of range is an error that changes nothing. +#[test] +fn a_live_star_takes_a_new_point_count_and_ratio() { + let (mut s, _) = session(); + let id = star(&mut s); + assert_eq!(node_path(&s, id).0.anchor_count(), 10); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, json!({"points": 8})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let (path, live) = node_path(&s, id); + assert_eq!(path.anchor_count(), 16); + assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(8)); + // The same count again: no undo step. + run(&mut s, json!({"points": 8})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, json!({"ratio": 0.25})); + let (_, live) = node_path(&s, id); + assert!(matches!(live, Some(LiveShape::Star { r1, r2, .. }) if r1 == 60.0 && (r2 - 15.0).abs() < 1e-9)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2); + // The shared corner radius spreads to the new corners. + run(&mut s, json!({"radius": 3})); + run(&mut s, json!({"points": 6})); + assert_eq!(style(&s, id), (Some(3.0), Some(CornerKind::Round), 12)); + for bad in [ + json!({"points": 1}), + json!({"points": 1001}), + json!({"points": 5.5}), + json!({"ratio": 1.5}), + json!({"ratio": -0.1}), + json!({"ratio": 0}), + json!({"points": 7, "radius": 2}), + ] { + let before = node_path(&s, id); + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(node_path(&s, id), before, "{bad}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let (path, live) = node_path(&s, id); + assert_eq!(path.anchor_count(), 10); + assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(5)); + // Anchors selected on the old layout are dropped with a new point count. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 8]], "mode": "set"})).unwrap(); + run(&mut s, json!({"id": id.0, "points": 3})); + assert_eq!(selected_anchors(&s, id), None); + // A star whose outer radius is 0 has no ratio to set. + let flat = NodeId(s.execute("shape.star", &json!({"cx": 50, "cy": 50, "radius1": 0, "radius2": 10})).unwrap()["id"].as_u64().unwrap()); + let before = node_path(&s, flat); + assert!(s.execute("object.setLiveShape", &json!({"id": flat.0, "ratio": 0.5})).is_err()); + assert_eq!(node_path(&s, flat), before); +} + +/// A ratio that changes how many anchors a rounded star draws can't come with a radius: the +/// corners selected before it would no longer name the same corners. A ratio alone still drops +/// the stale anchor selection. +#[test] +fn a_ratio_that_relays_a_rounded_star_is_not_set_with_a_radius() { + let (mut s, _) = session(); + // At this ratio the inner points lie on the lines between the outer ones. + let flat = 36f64.to_radians().cos(); + let id = star(&mut s); + run(&mut s, json!({"id": id.0, "radius": 4})); + let rounded = node_path(&s, id).0.anchor_count(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let before = (node_path(&s, id), selected_anchors(&s, id)); + let err = s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": flat, "radius": 6})).unwrap_err(); + assert!(err.to_string().contains("`ratio`"), "{err}"); + assert_eq!((node_path(&s, id), selected_anchors(&s, id)), before); + // The same ratio alone lays the anchors out again and drops the selection. + run(&mut s, json!({"id": id.0, "ratio": flat})); + assert_ne!(node_path(&s, id).0.anchor_count(), rounded); + assert_eq!(selected_anchors(&s, id), None); + // A ratio that keeps the anchors still goes with a radius. + let other = star(&mut s); + run(&mut s, json!({"id": other.0, "radius": 4})); + run(&mut s, json!({"id": other.0, "ratio": 0.4, "radius": 5})); + assert_eq!(style(&s, other).0, Some(5.0)); +} + /// Each corner stops at its own limit: its cut reaches halfway along its shorter side, so a /// star's neighbouring corners meet without overlapping. #[test] @@ -389,7 +474,8 @@ fn star_corners_stop_at_their_own_limit() { let id = star(&mut s); run(&mut s, json!({"radius": 1000})); let (path, live) = node_path(&s, id); - let Some(LiveShape::Path { base, .. }) = live else { panic!("live corners") }; + let Some(l @ LiveShape::Star { .. }) = live else { panic!("live corners") }; + let base = l.polygon_outline(); // Every cut ends at the middle of a side: each side's two cuts meet there. let sp = &base.subpaths[0]; for (i, a) in sp.anchors.iter().enumerate() { diff --git a/crates/engine/src/tests/missing_links.rs b/crates/engine/src/tests/missing_links.rs index e74d9fe545..0e2b0ff2d7 100644 --- a/crates/engine/src/tests/missing_links.rs +++ b/crates/engine/src/tests/missing_links.rs @@ -76,6 +76,27 @@ fn missing_link_markers_follow_files_relink_update_and_embed() { assert!(marked(&mut s).is_empty()); } +/// A caller confined to other folders sees a linked file outside them as missing, but its answer +/// does not replace the markers drawn on the canvas. +#[test] +fn a_confined_marked_query_leaves_the_canvas_markers_alone() { + let dir = Folder::new("marker-confined"); + let path = dir.file("art.png"); + write(&path, &png(40, 40, RED)); + let other = dir.0.join("other"); + std::fs::create_dir_all(&other).unwrap(); + let mut s = session(); + let id = place(&mut s, &path); + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + assert!(marked(&mut s).is_empty()); + let roots = crate::file_access::AutomationRoots::new(&[other.as_path()], &[]).unwrap(); + assert_eq!(crate::file_access::confine(roots.as_ref(), || marked(&mut s)), vec![id.0], "the caller cannot read the file"); + assert!(s.doc().unwrap().marked_missing_links().is_empty(), "the canvas keeps no marker for a file that is there"); + std::fs::remove_file(&path).unwrap(); + assert_eq!(marked(&mut s), vec![id.0]); + assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]); +} + #[test] fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() { for mode in ["automatically", "askWhenModified", "manually"] { diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 21cc4af602..6da71137fd 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -558,6 +558,22 @@ fn align_new_objects_to_pixel_grid_follows_the_preset() { assert!(!align(&old)); } +#[test] +fn saved_rows_past_the_limit_read_as_the_limit_and_others_stay() { + let mut s = Session::new(); + let saved = json!({"newDocPresets": [ + {"name": "Many", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 1001}, + {"name": "Four", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 4}, + ]}); + s.apply_prefs(serde_json::from_value(saved).unwrap()); + for (name, rows) in [("Many", 1000), ("Four", 4)] { + let layout = presets(&mut s, "Saved").iter().find(|p| p["name"] == name).unwrap()["artboardLayout"].clone(); + assert_eq!(layout["rows"], json!(rows), "{name}"); + // `file.new` takes the layout `file.newPresets` lists. + s.execute("file.new", &json!({"preset": name, "artboardLayout": layout})).unwrap(); + } +} + #[test] fn rearrange_keeps_its_grid() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index c99f58359f..d1ae98e29a 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -1136,6 +1136,30 @@ fn new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it() { batches_and_isolation_keep_new_art_protected(&mut s, pasted); } +/// A compound path pasted onto a locked artboard takes a path through node.move while it is still +/// selected, and is refused as a destination once the selection leaves it out. +#[test] +fn node_move_into_new_compound_path_on_a_locked_artboard() { + let mut s = session(); + let p = rect(&mut s); + let q = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let c = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let e = NodeId(s.execute("shape.rectangle", &json!({"x": 340, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let pasted = ids(&s.execute("edit.paste", &json!({"center": [1200, 200]})).unwrap()["ids"]); + assert_eq!(pasted.len(), 2); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), [compound], "the new compound path is selected"); + s.execute("node.move", &json!({"id": p.0, "parent": compound, "index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(p), Some(NodeId(compound)), "new art takes the path"); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("node.move", &json!({"id": q.0, "parent": compound, "index": 0})).is_err(), "no longer new art"); + assert_ne!(s.doc().unwrap().doc.parent_of(q), Some(NodeId(compound))); +} + /// The batch, isolation and group cases of [`new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it`], /// with the pasted art `pasted` selected. fn batches_and_isolation_keep_new_art_protected(s: &mut Session, pasted: Vec) { diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 3dd4959489..5166c820c4 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -731,6 +731,68 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() { assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins"); } +#[test] +fn linked_pages_of_a_file_with_editing_data_keep_an_explicit_crop_box() { + let dir = Folder::new("open-pdf-link-pages-explicit-crop"); + let src = dir.file("editable.ai"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": src, "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&src).unwrap(), None)); + let board = |s: &Session| { + let r = s.doc().unwrap().doc.artboards[0].rect; + (r.width(), r.height()) + }; + // No box named: the trim box, as the file opens as art. + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); + // An explicit crop box is the crop box, which takes in the bleed. + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "crop"})).unwrap(); + let (w, h) = board(&s); + assert!(w > 100.0 && h > 50.0, "{w} x {h}"); + s.execute("document.open", &json!({"path": src, "linkPages": true, "crop": "crop"})).unwrap(); + assert_eq!(board(&s), (w, h)); +} + +#[test] +fn linked_pages_with_only_a_native_attachment_default_to_crop_boxes() { + let dir = Folder::new("open-pdf-link-pages-native-crop"); + let src = dir.file("editable.pdf"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "document.exportPdf", + &json!({"path": src, "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + let bytes = std::fs::read(&src).unwrap(); + assert!(vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact)); + assert!(!vectorcraft_pdf::has_illustrator_data(&bytes, None)); + let board = |s: &Session| { + let r = s.doc().unwrap().doc.artboards[0].rect; + (r.width(), r.height()) + }; + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + let (w, h) = board(&s); + assert!(w > 100.0 && h > 50.0, "{w} x {h}"); + for key in ["cropTo", "crop"] { + let mut params = json!({"path": src, "linkPages": true}); + params[key] = json!("crop"); + s.execute("document.open", ¶ms).unwrap(); + assert_eq!(board(&s), (w, h), "{key}"); + } + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); +} + #[test] fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { use vectorcraft_testkit::pdf::{PdfPage, pdf}; 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..54926e1659 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(); @@ -1862,6 +1878,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() { assert!(s.active().unwrap().doc.node(a).is_none()); } +/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round. +#[test] +fn a_path_made_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);"); + assert_eq!(out, vec![json!("big")]); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big")); +} + +/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and +/// leaves the selection as it was; `null` still clears it. +#[test] +fn assigning_undefined_to_the_selection_throws() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];"); + assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn only_class_constructors_construct() { let (mut s, _, _) = doc(); @@ -2007,14 +2049,41 @@ fn note_is_the_attributes_note() { assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } +#[test] +fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "colorMode": "rgb"})).unwrap(); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); + assert_eq!(out[0], json!([612, 792, "DocumentColorSpace.CMYK"])); + // Recent keeps the built-in preset's name, as it does when no saved preset has it. + assert_eq!(s.prefs.recent_new_docs[0].name, "Letter"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var e = app.documents.addDocument('Print', p); vc.log([e.width, e.height]);"); + assert_eq!(out[0], json!([300, 792])); + assert_eq!(s.prefs.recent_new_docs[0].name, "Custom"); +} + #[test] fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() { let mut s = Session::new(); - s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap(); + s.execute( + "file.newPresets.save", + &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb", "artboardLayout": "row"}), + ) + .unwrap(); let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]); let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);"); assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset"); + // Several artboards are laid out as the built-in preset lays them out when no saved preset + // has its name, and the title is kept. + let three = "var p = new DocumentPreset(); p.numArtboards = 3; p.title = 'Three';\ + p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; p.artboardSpacing = undefined; var d = app.documents.addDocument('Print', p);\ + var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); vc.log([d.name, r]);"; + let out = log(&mut s, three); + let unshadowed = log(&mut Session::new(), three); + assert_eq!(out[0][0], json!("Three")); + assert_eq!(out[0][1].as_array().map(Vec::len), Some(3), "{out:?}"); + assert_eq!(out, unshadowed, "the saved preset changes nothing"); } #[test] @@ -2495,6 +2564,57 @@ fn wrappers_go_stale_after_revert() { } } +/// A layer's collections read before File › Revert do not list the loaded document's art, even +/// where the loaded layer has the same id. +#[test] +fn a_layers_collections_read_before_a_revert_are_stale() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-lists"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pathItems", "pageItems", "groupItems", "compoundPathItems", "layers"] { + let source = format!( + "var d = app.activeDocument, c = d.layers[0].{list}; vc.log(c.length >= 0); d.pageItems[0].name = 'changed'; vc.run('file.revert');\ + try {{ c.length; vc.log('ran'); }} catch (e) {{ vc.log('stale'); }} vc.log(d.layers[0].{list}.length >= 0);" + ); + assert_eq!(log(&mut s, &source), vec![json!(true), json!("stale"), json!(true)], "{list}"); + } +} + +/// An artboard read before File › Revert is stale, even though the loaded artboard has the same +/// id; the document's `artboards` read before it lists the loaded ones. +#[test] +fn an_artboard_read_before_a_revert_is_stale() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-artboard"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, bs = d.artboards, b = bs[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\ + try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(bs[0].name == saved);", + ); + assert_eq!(out, vec![json!("Stale artboard"), json!(true)]); +} + +/// A key that is the text of a number but not an array index reaches an indexer as a number, and +/// a layer's collections and `artboards` look it up as a name, as the document's `pageItems` does. +/// `index()` still takes a number as a position. +#[test] +fn scoped_collections_find_names_that_are_numbers() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, l = d.layers[0], i = l.pageItems[0]; i.name = '-1'; l.layers.add().name = '1.5';\ + d.artboards[0].name = '-1';\ + vc.log(l.pageItems['-1'] === i); vc.log(l.pathItems['-1'] === i); vc.log(l.layers['1.5'].name);\ + vc.log(d.artboards['-1'].name); vc.log(l.pageItems['-2'] === undefined); vc.log(l.pageItems.index(0) === i);\ + try { l.pageItems.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }\ + try { d.artboards.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!(true), json!(true), json!("1.5"), json!("-1"), json!(true), json!(true), json!("Not found"), json!("Not found")]); +} + /// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does. #[test] fn a_layers_page_items_read_names_as_the_documents_do() { @@ -2681,6 +2801,9 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { "app.activeDocument.groupItems.getByName('locked').pageItems", "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", + "app.activeDocument.pathItems", + "app.activeDocument.groupItems.getByName('locked').pathItems", + "app.activeDocument.compoundPathItems[0].pathItems", ] { // The error is caught, so the run keeps whatever `removeAll()` did before it threw. let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);")); @@ -3005,6 +3128,18 @@ fn an_unknown_menu_command_throws_and_names_it() { assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu")); } +/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a +/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`. +#[test] +fn get_is_file_open_compares_paths_by_the_platform_s_rules() { + use crate::script::dom::path_key_on; + assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false)); + assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false)); + assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false)); + assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true)); + assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true)); +} + #[test] fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let (mut s, _, _) = doc(); @@ -3296,6 +3431,202 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); } +#[test] +fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() { + let (mut s, _, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the + // document's list holds all three, the layer's only `a`, and a sublayer's path is its own. + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\ + vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ + vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ + var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ + sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\ + vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); vc.log(P[1] === undefined);", + ); + let expected = + [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; + assert_eq!(out[..11], expected); + // With the sublayer's path above the group, the layer's own path and both of the group's paths + // named `B`, each collection's named lookups give its own topmost path. + assert_eq!(out[11..], [json!(true), json!(true), json!(true), json!(true)]); +} + +#[test] +fn a_loop_over_a_groups_path_items_builds_the_list_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list + // of 1,000 paths is not built again for each read. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19))); + let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap()["log"], json!([1000])); +} + +#[test] +fn a_layers_path_items_make_their_paths_on_top_of_that_layer() { + let (mut s, ..) = doc(); + let bottom = s.active().unwrap().doc.layers[0].id; + let selected = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + // A new layer becomes the current one; each creator of the first layer's `pathItems` still + // puts its path on top of that layer. + let out = log( + &mut s, + "var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\ + var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\ + function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\ + for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\ + vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);", + ); + let mut expected = Vec::new(); + for i in 0..6 { + expected.extend([json!(true), json!(format!("m{i}"))]); + } + expected.extend([json!(true), json!(0), json!(8)]); + assert_eq!(out, expected); + assert_eq!(undo_steps(&s), steps + 1); + let st = s.active().unwrap(); + let kids = st.doc.node(bottom).unwrap().children().unwrap(); + assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5")); + assert!(st.selection == selected); +} + +#[test] +fn a_groups_path_items_add_puts_the_path_in_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\ + vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\ + var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);", + ); + assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + let top: Vec> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect(); + assert_eq!(top, [Some("R"), Some("N")]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { + const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let lid = s.active().unwrap().doc.layers[0].id; + let before = format!("{:?}", s.active().unwrap().doc.layers); + s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap(); + let locked = format!("{:?}", s.active().unwrap().doc.layers); + for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] { + assert!(failure(&mut s, src).contains(REFUSED), "{src}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); + } + // Caught inside the script, each refusal leaves both collections as they were, and the group, + // shown and unlocked itself, is refused for its locked layer. + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\ + var n = [L.pathItems.length, g.pathItems.length];\ + try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 3, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(out[1], out[2], "the collections are unchanged inside the script"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); + s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); + let hidden = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A group's `pathItems` read after the group is gone throw. + let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;"); + assert!(msg.contains("Stale page item"), "{msg}"); +} + +/// A collection read with a name gives what its `getByName` gives, in a layer's or a group's +/// collections as in the document's, and a name nothing has is not `in` it. +#[test] +fn collections_read_with_a_name_give_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0], r = g.pageItems[0]; r.name = 'Logo'; g.name = 'G';\ + vc.log([g.pageItems['Logo'] === r, g.pathItems['Logo'] === r, d.pathItems['Logo'] === r, d.groupItems['G'] === g,\ + d.layers[0].groupItems['G'] === g, d.layers['Layer 1'] === d.layers[0], d.artboards[d.artboards[0].name] === d.artboards[0]]);\ + vc.log(['Logo' in g.pageItems, 'missing' in g.pageItems, 'missing' in g.pathItems, 'missing' in d.layers, 'missing' in d.artboards]);\ + var m = ''; try { g.pageItems['missing']; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out[0], json!([true, true, true, true, true, true, true]), "{out:?}"); + assert_eq!(out[1], json!([true, false, false, false, false]), "{out:?}"); + assert_eq!(out[2], json!("Not found"), "{out:?}"); +} + +/// A compound path's `pathItems.removeAll()` leaves it, empty, as `remove()` of its last path +/// does. +#[test] +fn clearing_the_paths_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let out = log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length]);"); + assert_eq!(out, vec![json!(["CompoundPathItem", 0])]); + let d = &s.active().unwrap().doc; + assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); +} + +/// A Live Paint group's collections make nothing in it: what they made would join the group's +/// paths instead of being one of its objects. +#[test] +fn collections_of_a_live_paint_group_make_nothing() { + const REFUSED: &str = "Cannot add an object to a Live Paint group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], m = [];\ + try { g.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.groupItems.add(); } catch (e) { m.push(e.message); }\ + try { g.compoundPathItems.add(); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 4, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); @@ -3337,6 +3668,18 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { assert!(failure(&mut s, src).contains("only paths"), "{src}"); } assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // Caught inside the run, the refused move leaves the object where it was and the compound + // path's members as they were. + for (make, to) in + [("d.groupItems.add()", "C"), ("d.groupItems.add()", "C.pathItems[0], ElementPlacement.PLACEBEFORE"), ("d.compoundPathItems.add()", "C")] + { + let src = format!( + "var d = app.activeDocument, C = d.compoundPathItems.getByName('C'), o = {make};\ + try {{ o.move({to}); vc.log('moved'); }} catch (e) {{ vc.log(String(e).indexOf('only paths') >= 0); }}\ + vc.log(o.parent.typename); vc.log(C.pathItems.length); vc.log(C.pathItems[0].parent.typename);" + ); + assert_eq!(log(&mut s, &src), [json!(true), json!("Layer"), json!(2), json!("CompoundPathItem")], "{src}"); + } assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); } @@ -4127,6 +4470,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { assert!(!d.node(a).unwrap().extras().pixel_aligned); } +/// A pixel-aligned compound path snaps a path that was not aligned when it takes it in. +#[test] +fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let loose = rect(&mut s, 200.25, 20.5, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(loose).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": loose.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(loose), Some(cid)); + // Both paths have a 1 pt stroke, so the grid puts their edges where it put the aligned path's. + let (b, at) = (d.node(loose).unwrap().geometric_bounds().unwrap(), d.node(a).unwrap().geometric_bounds().unwrap()); + assert_ne!(b.x0, 200.25); + for (v, w) in [(b.x0, at.x0), (b.y0, at.y0), (b.x1, at.x1), (b.y1, at.y1)] { + assert_eq!(v.fract(), w.fract(), "{b:?} is on the pixel grid as {at:?} is"); + } +} + /// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid /// with the compound path's other paths. #[test] @@ -4170,18 +4536,39 @@ fn a_compound_paths_path_items_are_page_items() { out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)] ); - for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] { + // The path creation methods make the new path inside the compound path. + for (made, call) in + ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] + .into_iter() + .enumerate() + { let source = format!( "var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);" ); let out = log(&mut s, &source); - assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}"); - assert_eq!(out[1], json!(2)); + assert_eq!(out, [json!("made"), json!(made + 3)], "{call}"); } run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap(); assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); } +#[test] +fn a_compound_paths_path_items_add_makes_the_path_inside_it() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.layers[0].compoundPathItems.add(); var p = c.pathItems.add(); p.setEntirePath([[0, 0], [10, 0], [10, 10]]);\ + var r = c.pathItems.rectangle(50, 20, 10, 10); vc.log(c.pathItems.length); vc.log(p.parent.typename); vc.log(r.parent.typename);\ + vc.log(c.pathItems[0].width);", + ); + assert_eq!(out, [json!(2), json!("CompoundPathItem"), json!("CompoundPathItem"), json!(10)]); + let d = &s.active().unwrap().doc; + let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(compound.children().unwrap().len(), 2); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); +} + #[test] fn art_collections_follow_edits_between_reads() { let (mut s, _, _) = doc(); @@ -4327,6 +4714,18 @@ fn has_selected_artwork_keeps_selected_objects_in_other_layers() { } } +#[test] +fn layer_lists_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.length; for (var i = 0; i < L.length; i++) L[i];\ + var made = L.add(); made.name = 'Top'; vc.log(L.length - n); vc.log(L[0].name); vc.log(L.getByName('Top').name);\ + made.remove(); vc.log(L.length - n);", + ); + assert_eq!(out, [json!(1), json!("Top"), json!("Top"), json!(0)]); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 7486a07d33..153e348cd9 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::*; @@ -281,6 +282,43 @@ fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// A clipping group's `pathItems` lists only its clipping path when its other art is a group: +/// `removeAll()` throws and deletes nothing, as `pageItems.removeAll()` does, so the group does not +/// become the clipping path. +#[test] +fn path_items_remove_all_refuses_a_clipping_path_whose_group_keeps_other_objects() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); + let inner = s.active().unwrap().doc.parent_of(b).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, inner.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let clip = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("object.setProps", &json!({"ids": [clip.0], "name": "clip"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.groupItems.getByName('clip').pathItems.removeAll();"); + assert!(e.contains("cannot delete a clipping path") && e.contains(&a.0.to_string()), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// The document's `pathItems.removeAll()` deletes a compound path whose paths it all lists, so a +/// clipping group that holds only its clipping path and that compound path is left with nothing +/// and is not refused. +#[test] +fn path_items_remove_all_counts_compound_paths_it_empties() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(b).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, compound.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none() && d.node(compound).is_none()); +} + #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); @@ -338,6 +376,76 @@ fn shape_creators_reject_bad_sizes_without_change() { assert_eq!(undo_steps(&s), steps); } +#[test] +fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { + // `pathItems[1]` is `b`. + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + let sel = &st.selection; + // A removal renumbers the direct selection: the selected anchor after the removed one moves + // down one place. + assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0)]), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // Moving a point keeps the anchors selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); +} + +/// Points are found by their index across subpaths, through changes that wait to be written and +/// removals that change how many points a subpath has or remove a subpath. +#[test] +fn points_are_found_across_subpaths_as_their_counts_change() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false}); + let subs = json!([ + {"anchors": [pt(0.0), pt(1.0)], "closed": false}, + {"anchors": [pt(2.0)], "closed": false}, + {"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false}, + ]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\ + for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\ + vc.log(q[2].anchor); vc.log(q[5].anchor);\ + q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\ + q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);", + ); + let want = + [json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)]; + assert_eq!(out, want); + let n = node(&s, a); + let counts: Vec = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect(); + assert_eq!(counts, vec![1, 3]); +} + +/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points +/// start: the index is built again only when a change adds or removes points. +#[test] +fn moving_each_point_keeps_the_index_of_the_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let subs: Vec = + (0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect(); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let before = crate::script::dom::index_builds(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);", + ); + assert_eq!(out, vec![json!([49, 7])]); + let built = crate::script::dom::index_builds() - before; + assert!(built <= 3, "the index was built {built} times"); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); @@ -357,6 +465,34 @@ fn set_entire_path_replaces_points_and_keeps_closed() { assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); } +#[test] +fn control_bounds_take_in_direction_handles() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\ + var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\ + n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);", + ); + assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds"); + let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::>(); + let (control, visible) = (edges(&out[2]), edges(&out[3])); + assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}"); + assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}"); +} + +/// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as +/// it is from the visible bounds. +#[test] +fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);"); + assert_eq!(out[0], out[1]); +} + #[test] fn hostile_set_entire_path_input_is_bounded() { let (mut s, _, _) = doc(); @@ -420,6 +556,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")); @@ -1064,6 +1203,29 @@ fn identity_transforms_of_an_empty_path_do_nothing() { } } +#[test] +fn turning_or_scaling_an_empty_path_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);"); + assert_eq!(undo_steps(&s), 1, "only the path is added"); +} + +/// Scaling stroke weights and effects by the scale itself without moving the object is refused for +/// a path with no anchors as it is for one with bounds, and the stroke weight stays. +#[test] +fn scaling_line_widths_alone_is_refused_for_an_empty_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;"); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(50, 50, false, false, false, false, 50);"); + assert!(e.contains("changeLineWidths other than 100 with changePositions false"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(4)]); +} + /// The paint of the fill (`fill`) or stroke of `id`. fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { let n = node(s, id); @@ -1788,6 +1950,39 @@ fn filled_and_stroked_true_give_the_new_art_paint() { } } +/// The pattern of a path with no anchors turns and scales about the origin, as a path without +/// points takes any transformation; each call is one undo step. +#[test] +fn transforming_the_pattern_of_an_empty_path_turns_it() { + for source in [ + "app.activeDocument.pathItems[0].rotate(90, true, true, true, true);", + "app.activeDocument.pathItems[0].resize(50, 50, true, true, true, true);", + "app.activeDocument.pathItems[0].resize(50, 50, false, true, false, true);", + ] { + let (mut s, _) = doc_with_paints(); + s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].fillColor.typename);"), vec![json!("PatternColor")]); + let (before, steps) = (art(&s), undo_steps(&s)); + log(&mut s, source); + assert_ne!(art(&s), before, "{source}: the pattern transforms"); + assert_eq!(undo_steps(&s), steps + 1, "{source}: one undo step"); + } +} + +/// Scaling a path with no anchors with its stroke weights scales its own stroke weight. +#[test] +fn scaling_an_empty_path_with_line_widths_scales_its_stroke() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 10; n.strokeDashes = [3, 4];"); + let steps = undo_steps(&s); + log(&mut s, "app.activeDocument.pathItems[0].resize(200, 200, true, false, true, false, 200);"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(20)]); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeDashes);"), vec![json!([6, 8])], "the dashes scale too"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); +} + #[test] fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() { let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) }; @@ -2385,6 +2580,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..7213172f14 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"); @@ -1125,6 +1164,28 @@ fn the_source_image_cannot_leave_its_tracing() { let _ = std::fs::remove_dir_all(base); } +/// A tracing's shown source image cannot be removed, which would leave the tracing without it, and +/// the refused remove leaves the document as it was. +#[test] +fn a_shown_source_image_cannot_be_removed() { + let base = folder("source-removed"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;"); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.pageItems[0], m = 'none';\ + try { p.tracing.sourceArt.remove(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); 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/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 3952955779..8042d5da37 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1493,6 +1493,93 @@ fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() { assert_eq!(state(&s), before); } +/// A script that ends past the allowance the person's last answer gave is asked again before its +/// changes are kept. +#[test] +fn a_finished_run_past_its_last_allowance_asks_again() { + let draw = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('shape.rectangle', {x:2,y:1,width:1,height:1});"; + let point = "var P = app.activeDocument.pathItems, q = P[0];\ + for (var k = 1; k < P.length; k++) if (P[k].pathPoints.length > q.pathPoints.length) q = P[k];\ + var p = q.pathPoints; for (var i = 0; i < p.length; i++) p[i].anchor = [i * 3, -4 - i];"; + // The path the script moves has 600 anchors, so its point changes weigh more than the + // rectangles do. + let two_docs = || { + let mut s = two_docs(); + let id = s.documents()[1].doc.layers[0].children().unwrap()[0].id; + let anchors: Vec = (0..600) + .map(|i| json!({"x": f64::from(i), "y": f64::from(i % 7), "in": [f64::from(i), 0.0], "out": [f64::from(i), 0.0], "smooth": false})) + .collect(); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + s + }; + let added = |source: &str| { + let mut s = two_docs(); + let start = s.documents()[1].doc.clone(); + assert_eq!(run(&mut s, source).unwrap()["ok"], true); + start.retained_bytes_each(&s.documents()[1].doc).1 as u64 + }; + let whole = format!("{draw} {point}"); + let (m, p) = (added(draw), added(&whole) - added(draw)); + // The rectangles go past one object, which asks once, and stay within twice the bytes; the + // point changes, written as the script ends, then go past the second allowance and also past + // the third. + let b = (m + p - 1) / 3; + assert!(m <= 2 * b && 3 * b < m + p && m + p <= 4 * b, "m {m}, p {p}, b {b}"); + TEST_GROWTH.with(|g| g.set(Some(1))); + TEST_GROWTH_BYTES.with(|g| g.set(Some(b))); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &whole).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + TEST_GROWTH_BYTES.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance"); +} + +/// A script that ends with nothing left to write, past the allowance the person's last answer +/// gave, is asked again before its changes are kept. +#[test] +fn a_run_that_ends_past_its_last_allowance_with_nothing_to_write_asks_again() { + TEST_GROWTH.with(|g| g.set(Some(20))); + // 21 rectangles go past the first allowance, and the 45 the document opens go past the + // second and stay within twice it, which leaves them past the third. + let rects: String = (0..45).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + let data = vectorcraft_format::base64_encode(svg.as_bytes()); + let source = format!( + "for (var i = 0; i < 21; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\ + vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}});" + ); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &source).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked for the rectangles, for the document, and again as the script ended"); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); diff --git a/crates/engine/src/tests/strokereach.rs b/crates/engine/src/tests/strokereach.rs index a04388af89..87a9b64917 100644 --- a/crates/engine/src/tests/strokereach.rs +++ b/crates/engine/src/tests/strokereach.rs @@ -62,8 +62,12 @@ fn a_click_outside_an_outside_stroke_selects_it() { s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap(); s.execute("select.none", &json!({})).unwrap(); assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach"); - // With it off, a click inside the unfilled square selects it (#9175). + // With it off, a click inside the unfilled square selects nothing by default, and selects the + // square with Select Inside Unfilled Shapes on (#9175). s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(click(&mut s, 116.0, 200.0).is_empty(), "off by default"); + s.execute("prefs.set", &json!({"key": "selectInsideUnfilledShapes", "value": true})).unwrap(); assert_eq!(click(&mut s, 116.0, 200.0), [r]); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 37d1282f26..4655bbaa61 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -21,6 +21,7 @@ pub(crate) struct HoverKey { last_tools: (Option<&'static str>, Option<&'static str>), ctrl_click_selects_behind: bool, object_selection_by_path_only: bool, + select_inside_unfilled_shapes: bool, type_selection_by_path_only: bool, selection_tolerance: f64, anchor_size: u32, @@ -364,6 +365,7 @@ impl Session { last_tools: (self.last_selection_tool, self.last_part_selection_tool), ctrl_click_selects_behind: p.ctrl_click_selects_behind, object_selection_by_path_only: p.object_selection_by_path_only, + select_inside_unfilled_shapes: p.select_inside_unfilled_shapes, type_selection_by_path_only: p.type_selection_by_path_only, selection_tolerance: p.selection_tolerance, anchor_size: p.anchor_size, @@ -652,6 +654,7 @@ impl Session { }, anchor_size: self.prefs.anchor_size, path_only: self.prefs.object_selection_by_path_only, + unfilled_interiors: self.prefs.select_inside_unfilled_shapes, type_path_only: self.prefs.type_selection_by_path_only, double_click_isolate: self.prefs.double_click_to_isolate, double_click_adds_anchor: self.prefs.double_click_adds_anchor_points, @@ -750,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; @@ -1865,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. @@ -1893,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 => { @@ -1965,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 3d3c5d2857..d7595f4201 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=", ), @@ -150,7 +151,7 @@ const INSIDE: &[(&str, &str)] = &[ "Layer.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ - locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ toString typename visible visible= zOrder zOrderPosition", ), @@ -159,7 +160,7 @@ const INSIDE: &[(&str, &str)] = &[ ("GroupItem.", "prototype"), ( "GroupItem.prototype.", - "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \ rasterItems rasterItems= symbolItems symbolItems= textFrames", ), ("GroupItems.", "prototype"), @@ -238,12 +239,12 @@ const INSIDE: &[(&str, &str)] = &[ strokeWidth strokeWidth= stroked stroked=", ), ("PathPoints.", "prototype"), - ("PathPoints.prototype.", "add constructor index length parent removeAll typename"), + ("PathPoints.prototype.", "add constructor index length parent removeAll toString typename"), ("PathPoint.", "prototype"), ( "PathPoint.prototype.", "anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \ - rightDirection= selected selected= typename", + rightDirection= selected selected= toString typename", ), ("Tags.", "prototype"), ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 55f1f4976f..cd033801ab 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -1057,6 +1057,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/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index 41f9f0e7e2..3ba1adbb43 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -53,7 +53,9 @@ pub(in crate::ai_editing) const SYMBOL_COUNT: &str = "symbols past 4,096 are lef pub(super) fn redrawn(n: &Node) -> bool { let rounded = |l: &vectorcraft_doc::LiveShape| match l { vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii.iter().any(|r| *r > 0.0), - vectorcraft_doc::LiveShape::Polygon { radii, .. } | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), + vectorcraft_doc::LiveShape::Polygon { radii, .. } + | vectorcraft_doc::LiveShape::Star { radii, .. } + | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), vectorcraft_doc::LiveShape::Ellipse { .. } | vectorcraft_doc::LiveShape::Line { .. } => false, }; match &n.kind { diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index e020dda9c3..f48032c020 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -22,7 +22,7 @@ flate2 = { workspace = true } # file's access ACL on Linux (`keep_permissions`). Already in Cargo.lock (tempfile), so this adds # no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "fs"] } +rustix = { workspace = true, features = ["std", "fs", "process"] } [dev-dependencies] vectorcraft-testkit = { workspace = true } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 1e353f309f..3f5683841e 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -153,13 +153,19 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { - // A missing target is created by `create_target`, after the last check. An existing one is - // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. - if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { - return Err(io::ErrorKind::NotFound.into()); + // Opened without `O_CREAT`: a missing target, one removed meanwhile included, is created + // only by `create_target`, after the last check. + #[cfg(test)] + if write && let Some(hook) = BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()) { + hook(); } - let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; - Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) + // `O_NONBLOCK`: a FIFO at the name fails the regular-file check instead of waiting for a reader. + let flags = if write { OFlags::WRONLY | OFlags::NONBLOCK } else { OFlags::RDONLY }; + let file = File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?); + if write { + protected_regular(&dir, &file)?; + } + Ok(file) }; let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { @@ -265,6 +271,31 @@ pub fn write_atomic_checked( } } +/// The target [`write_atomic_checked`] opened without `O_CREAT`, checked as Linux's strictest +/// `fs.protected_regular` checks an `O_CREAT` open of an existing file: anything but a regular +/// file is refused, and so is a file in a sticky folder that others or the group can write to +/// when neither this process nor the folder's owner owns it. +#[cfg(unix)] +fn protected_regular(dir: &std::os::fd::OwnedFd, file: &File) -> io::Result<()> { + let (folder, opened) = (rustix::fs::fstat(dir)?, rustix::fs::fstat(file)?); + if rustix::fs::FileType::from_raw_mode(opened.st_mode) != rustix::fs::FileType::RegularFile { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); + } + if refused_in_sticky_folder(rustix::fs::Mode::from_raw_mode(folder.st_mode), folder.st_uid, opened.st_uid, rustix::process::geteuid().as_raw()) { + return Err(io::ErrorKind::PermissionDenied.into()); + } + Ok(()) +} + +/// Whether a file owned by `owner` in a folder with mode `folder_mode` owned by `folder_owner` is +/// refused to the user `me`: the folder is sticky, others or the group can write to it, and +/// neither `me` nor `folder_owner` owns the file. +#[cfg(unix)] +fn refused_in_sticky_folder(folder_mode: rustix::fs::Mode, folder_owner: u32, owner: u32, me: u32) -> bool { + use rustix::fs::Mode; + folder_mode.contains(Mode::SVTX) && folder_mode.intersects(Mode::WGRP | Mode::WOTH) && owner != me && owner != folder_owner +} + /// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is /// filled, right before it is put in place; a refusal then removes the temporary file and leaves /// `path` unchanged. @@ -784,6 +815,9 @@ thread_local! { /// Tests: [`write_atomic_checked`]'s folder refuses the rename. #[cfg(unix)] static RENAME_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: run once right before [`write_atomic_checked`] opens its target for writing. + #[cfg(unix)] + static BEFORE_TARGET_OPEN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// A symbolic link keeps pointing at its file: write the file it names. @@ -1282,6 +1316,81 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A target removed after the write starts is not created again before the last check: when its + /// folder has moved outside by then, nothing is left there. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_no_target_removed_while_it_is_opened() { + let (d, root, outside) = checked_folders("checked-removed-target"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + let (inside, moved) = (root.join("inside"), outside.join("inside")); + let (from, to) = (inside.clone(), moved.clone()); + BEFORE_TARGET_OPEN.with(|h| { + *h.borrow_mut() = Some(Box::new(move || { + std::fs::remove_file(from.join("doc.txt")).unwrap(); + std::fs::rename(&from, &to).unwrap(); + })) + }); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()); + assert!(r.is_err(), "{r:?}"); + assert!(!moved.join("doc.txt").exists(), "the removed target was created again"); + assert!(!inside.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// An existing regular file this process owns passes the check. + #[cfg(unix)] + #[test] + fn protected_regular_allows_a_file_this_process_owns() { + let d = std::fs::canonicalize(dir("protected-regular")).unwrap(); + std::fs::write(d.join("doc.txt"), b"old").unwrap(); + let folder: std::os::fd::OwnedFd = File::open(&d).unwrap().into(); + let file = OpenOptions::new().write(true).open(d.join("doc.txt")).unwrap(); + protected_regular(&folder, &file).unwrap(); + let _ = std::fs::remove_dir_all(d); + } + + /// A FIFO at the name is not written into when the rename is refused: without a reader the + /// write fails at once instead of waiting for one (without `O_NONBLOCK` this test does not + /// return), and with a reader nothing reaches it. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_does_not_write_into_a_fifo_at_its_name() { + use rustix::fs::{Mode, OFlags}; + use std::io::Read as _; + let (d, root, _) = checked_folders("checked-fifo"); + let path = root.join("inside/doc.txt"); + rustix::fs::mknodat(rustix::fs::CWD, &path, rustix::fs::FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + RENAME_REFUSED.with(|c| c.set(true)); + let alone = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + let reader = File::from(rustix::fs::open(&path, OFlags::RDONLY | OFlags::NONBLOCK, Mode::empty()).unwrap()); + let read = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + assert!(alone.is_err() && read.is_err(), "{alone:?} {read:?}"); + let mut got = [0u8; 8]; + assert!((&reader).read(&mut got).map_or(true, |n| n == 0), "nothing is written into the FIFO"); + let _ = std::fs::remove_dir_all(d); + } + + /// A file in a sticky folder that others or the group can write to is refused when neither this + /// user nor the folder's owner owns it. + #[cfg(unix)] + #[test] + fn a_file_owned_by_someone_else_in_a_shared_sticky_folder_is_refused() { + let (me, folder_owner, other) = (1000, 0, 2000); + let mode = rustix::fs::Mode::from_raw_mode; + assert!(refused_in_sticky_folder(mode(0o1777), folder_owner, other, me)); + assert!(refused_in_sticky_folder(mode(0o1770), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1755), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o0777), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, me, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, folder_owner, me)); + } + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. #[cfg(unix)] #[test] diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index c7157df94d..9ecba0c7ca 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -275,6 +275,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { d.halftone_radii_to_points(); d.store_legacy_twist_angles(); } + // Older apps don't know live stars: they get the outline a star draws as a plain path. + if version < VERSION { + d.live_stars_to_paths(); + } let v1 = if version == 1 { let mut v = serde_json::to_value(&d).map_err(encode_err)?; legacy::anchors_to_v1(&mut v); diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index afc3bea9d2..0305246868 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -19,6 +19,20 @@ fn json_of(bytes: &[u8]) -> Value { serde_json::from_slice(bytes).unwrap() } +/// `v` (a document's JSON) with every live star's `live` taken off its path. +fn without_live_stars(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") { + o.remove("live"); + } + o.values_mut().for_each(without_live_stars); + } + Value::Array(a) => a.iter_mut().for_each(without_live_stars), + _ => {} + } +} + fn gzip(bytes: &[u8]) -> Vec { let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); gz.write_all(bytes).unwrap(); @@ -274,7 +288,9 @@ fn version_1_files_load() { fn saves_down_to_older_versions() { let mut d = rich_doc(); d.color_profiles = ColorProfiles { rgb: None, cmyk: Some("Coated".into()) }; - let current = doc_json(&load(&save(&d, false)).unwrap()); + let mut current = doc_json(&load(&save(&d, false)).unwrap()); + // Older versions get live stars as plain paths. + without_live_stars(&mut current); for version in [1, 2] { let bytes = save_with(&d, &opts(version, false)).unwrap(); let v = json_of(&bytes); @@ -299,6 +315,47 @@ fn saves_down_to_older_versions() { assert!(matches!(save_with(&d, &opts(2, true)), Err(FormatError::CompressedTooOld(2)))); } +/// Versions before [`VERSION`] don't know live stars: a save for them writes the star's outline as +/// a plain path, which those versions read; the current version keeps the star live. +#[test] +fn older_versions_get_a_live_star_as_its_path() { + let mut d = Document::new(100.0, 100.0); + let star = vectorcraft_doc::LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 5, + xf: Affine::translate((50.0, 50.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }; + let id = d.alloc_id(); + let mut node = Node::path(id, star.to_path(), Default::default()); + if let NodeKind::Path { live, .. } = &mut node.kind { + *live = Some(Box::new(star.clone())); + } + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, node).unwrap(); + for version in 1..VERSION { + let bytes = save_with(&d, &opts(version, false)).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(!text.contains("\"star\""), "v{version} writes no live star"); + let back = load(&bytes).unwrap(); + let mut anchors = None; + back.walk(|n| { + if let NodeKind::Path { path, live, .. } = &n.kind { + assert!(live.is_none(), "v{version}"); + anchors = Some(path.anchor_count()); + } + }); + assert_eq!(anchors, Some(10), "v{version} keeps the star's outline"); + } + let back = load(&save(&d, false)).unwrap(); + let mut live = None; + back.walk(|n| live = live.clone().or(n.live_shape().cloned())); + assert_eq!(live, Some(star)); +} + #[test] fn preview_is_embedded_and_read_back() { let d = Document::new(10.0, 10.0); diff --git a/crates/format/tests/prop_format.rs b/crates/format/tests/prop_format.rs index faecc37a8c..26d91ccf97 100644 --- a/crates/format/tests/prop_format.rs +++ b/crates/format/tests/prop_format.rs @@ -11,6 +11,20 @@ use vectorcraft_testkit::fixtures; use vectorcraft_testkit::invariants::{check_document, check_native_roundtrip, check_native_roundtrip_exact, doc_json, json_approx_eq}; use vectorcraft_testkit::strategies::arb_ops; +/// `v` (a document's JSON) with every live star's `live` taken off its path. +fn without_live_stars(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") { + o.remove("live"); + } + o.values_mut().for_each(without_live_stars); + } + Value::Array(a) => a.iter_mut().for_each(without_live_stars), + _ => {} + } +} + fn rich_doc() -> Document { (*fixtures::rich_session().doc().unwrap().doc).clone() } @@ -117,9 +131,13 @@ proptest! { } let d = s.doc().unwrap().doc.clone(); let want = doc_json(&load(&save(&d, false)).unwrap()); + // Older versions get live stars as plain paths. + let mut older = want.clone(); + without_live_stars(&mut older); for o in [SaveOptions { compress: true, ..SaveOptions::default() }, SaveOptions { version: 2, ..SaveOptions::default() }, SaveOptions { version: 1, pretty: true, ..SaveOptions::default() }] { let back = load(&save_with(&d, &o).unwrap()).unwrap(); - prop_assert!(json_approx_eq(&doc_json(&back), &want, 1e-12), "{:?} differs", o); + let want = if o.version < vectorcraft_format::VERSION { &older } else { &want }; + prop_assert!(json_approx_eq(&doc_json(&back), want, 1e-12), "{:?} differs", o); } } diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index ac6f721b85..74c4737c9f 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -236,6 +236,16 @@ pub struct CombTooth { /// The most teeth a curvature comb draws in all. pub const MAX_COMB_TEETH: usize = 20_000; +/// Does the direction `next` head back against the direction `previous`? A right angle +/// whose dot product rounds a little below zero does not count. +fn turns_back(previous: Vec2, next: Vec2) -> bool { + let unit = |v: Vec2| { + let v = v / v.x.abs().max(v.y.abs()); + v / v.hypot() + }; + unit(previous).dot(unit(next)) < -1e-9 +} + /// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t` /// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment /// gives teeth of no length, its ends included. A point of a curved segment where it has no @@ -243,6 +253,8 @@ pub const MAX_COMB_TEETH: usize = 20_000; /// with no length, a segment whose points are not finite, or a `scale` that is not finite. When /// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when /// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath. +/// The line through the tips starts again wherever the path turns back on itself, at a straight +/// segment as at a curve. pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec { let n = sp.segment_count(); if n == 0 || !scale.is_finite() || max_teeth < 2 { @@ -279,8 +291,10 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize if line { // A line stored with its handles on its anchors has no speed at its ends, but a // direction and no curvature all along. + // A line that turns back on the segment before it is a cusp at their anchor. let at = c.eval(t); - previous_direction = None; + start |= previous_direction.is_some_and(|previous| turns_back(previous, chord)); + previous_direction = Some(chord); if !at.is_finite() { start = true; continue; @@ -298,7 +312,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize } let k = v.cross(a) / (speed * speed * speed); let direction = v / speed; - start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0); + start |= previous_direction.is_some_and(|previous| turns_back(previous, direction)); previous_direction = Some(direction); let normal = Vec2::new(-direction.y, direction.x); let at = c.eval(t); @@ -333,8 +347,15 @@ pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { if !(last.segment + 1..n).chain(0..first.segment).all(no_length) { return false; } - match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { - (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, + match ((0..n).rev().find(|&i| !no_length(i)), (0..n).find(|&i| !no_length(i))) { + (Some(into), Some(out)) => { + let (a, b) = (sp.segment(into), sp.segment(out)); + // A straight segment's chord, as `curvature_comb` uses it, when the chord has a length. + let chord = |i: usize, c: CubicBez| Some(c.p3 - c.p0).filter(|v| sp.segment_is_line(i) && v.hypot() > 0.0); + let a = chord(into, a).unwrap_or_else(|| end_direction(a)); + let b = chord(out, b).unwrap_or_else(|| start_direction(b)); + !turns_back(a, b) + } _ => false, } } @@ -415,6 +436,22 @@ mod tests { assert!(!comb_closes(&sp, &teeth), "an open subpath does not close"); } + /// A curve that ends heading down, a straight segment back up from its end, and a curve that + /// starts heading down again: both anchors are cusps, so the line through the tips starts again + /// at each of them. + #[test] + fn the_comb_breaks_where_a_straight_segment_turns_back() { + let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_out: Point::new(100.0, -50.0), ..Anchor::corner(Point::new(100.0, -100.0)) }; + let a3 = Anchor { h_in: Point::new(200.0, -50.0), ..Anchor::corner(Point::new(200.0, -100.0)) }; + let sp = SubPath::new(vec![a0, a1, a2, a3], false); + assert!(sp.segment_is_line(1)); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 9); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false, true, false, false]); + } + /// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a /// cusp elsewhere, and stays open when the first anchor is the cusp. #[test] @@ -436,6 +473,52 @@ mod tests { assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH))); } + /// A straight segment uses its chord at the seam even when a tiny handle points the other way. + #[test] + fn the_comb_stays_open_where_a_straight_segment_turns_back_at_the_seam() { + let a0 = Anchor { h_in: Point::new(-1e-12, 0.0), h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::ORIGIN) }; + let a1 = Anchor { h_in: Point::new(100.0, 50.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let mut sp = SubPath::new(vec![a0, a1], true); + for line in [1, 0] { + assert!(sp.segment_is_line(line)); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + assert!(teeth[0].at.distance(teeth[5].at) < 1e-9, "the teeth meet at the seam"); + assert!(!comb_closes(&sp, &teeth), "the chord reverses direction at the seam: {line}"); + sp.reverse(); + sp.anchors.rotate_right(1); + } + } + + /// A segment whose anchors sit on one point and whose handle is too short to count still has + /// a direction at the seam, so a reversal there keeps the comb open. + #[test] + fn the_comb_stays_open_at_a_seam_segment_with_coincident_anchors() { + let a0 = Anchor::corner(Point::ORIGIN); + let a1 = Anchor::corner(Point::new(100.0, 0.0)); + let a2 = Anchor { h_out: Point::new(1e-12, 0.0), ..Anchor::corner(Point::ORIGIN) }; + let sp = SubPath::new(vec![a0, a1, a2], true); + assert!(sp.segment_is_line(2)); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + let (first, last) = (teeth.first().map(|t| t.at), teeth.last().map(|t| t.at)); + assert!(first.zip(last).is_some_and(|(f, l)| f.distance(l) < 1e-9), "the teeth meet at the seam: {teeth:?}"); + assert!(!comb_closes(&sp, &teeth), "the closing segment heads back against the first one"); + } + + /// Large finite line directions still break the comb at a reversal inside the path and at its seam. + #[test] + fn the_comb_breaks_where_large_straight_segments_turn_back() { + let sp = SubPath::polyline(&[Point::ORIGIN, Point::new(1e155, 0.0), Point::ORIGIN], false); + let teeth = curvature_comb(&sp, 2, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, true, false]); + let closed = SubPath::polyline(&[Point::ORIGIN, Point::new(1e155, 0.0)], true); + let teeth = curvature_comb(&closed, 2, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4); + assert!(!comb_closes(&closed, &teeth), "the closing chord reverses direction at the first anchor"); + } + /// A segment with no length and a handle drawn back onto its anchor do not panic and give no /// tooth where the curve has no direction; a scale that is not finite gives no comb. #[test] diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 3a3cc606c5..8550807893 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -455,9 +455,9 @@ pub fn polygon_configured(center: Point, radius: f64, sides: u32, rotation_deg: contour_with_rounding(&pts, rounded) } -/// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, first tip up. +/// Star with `points` tips (2–1000), outer radius `r1`, inner radius `r2`, first tip up. pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData { - let n = points.max(2) * 2; + let n = points.clamp(2, 1000) * 2; let rot = rotation_deg.to_radians(); let pts: Vec = (0..n) .map(|i| { @@ -1485,6 +1485,12 @@ mod tests { assert!((d[0] - 10.0).abs() < 1e-9 && (d[1] - 5.0).abs() < 1e-9); } + #[test] + fn star_keeps_to_a_thousand_points() { + assert_eq!(star(Point::ZERO, 10.0, 5.0, 5000, 0.0).anchor_count(), 2000); + assert_eq!(star(Point::ZERO, 10.0, 5.0, 1, 0.0).anchor_count(), 4); + } + #[test] fn straight_star_five_points() { let r2 = straight_star_inner_radius(100.0, 5); diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index f13677ca52..488823940a 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -33,6 +33,13 @@ use pattern::Mode; /// enough for a 1 MiB stack. pub(crate) const MAX_DEPTH: u32 = 600; +#[cfg(test)] +thread_local! { + /// Tests: the top-level function names that deciding the variables of block functions has + /// gathered or looked up. + pub(crate) static FUN_DECL_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Why code could not be compiled. #[derive(Debug)] pub(crate) enum CompileFail { @@ -409,6 +416,7 @@ impl<'a> FnCompiler<'a> { | Stmt::DefaultXmlNamespace(_) => {} } } + let mut top_names: Option> = None; for (k, scope, id) in annex { let mut cur = Some(scope); let mut clash = params.contains(&k) || *k == *key_of("arguments"); @@ -422,7 +430,18 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + if seen.contains(&k) { + continue; + } + // The top-level function names, gathered the first time a block function needs them. + let top = top_names.get_or_insert_with(|| { + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + out.fun_decls.len() as u64)); + out.fun_decls.iter().map(|(name, _)| name).collect::>() + }); + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + 1)); + if !top.contains(&k) && annex_seen.insert(k.clone()) { out.annex_vars.push(k); } } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index ec43bfe327..ebefd33e66 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,19 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn block_function_variables_look_up_each_top_level_function_name_once() { + // 1,000 top-level functions and 1,000 block functions: each block function's variable is + // decided with one lookup in the names gathered once, not by comparing it with every + // top-level function. + let top = (0..1_000).map(|i| format!("function t{i}() {{ return {i}; }}")).collect::(); + let blocks = (0..1_000).map(|i| format!("{{ function b{i}() {{ return {i}; }} }}")).collect::(); + crate::compiler::FUN_DECL_CHECKS.with(|c| c.set(0)); + assert_eq!(run(&format!("{top}{blocks}t999() + b999()")), JsValue::Number(1_998.0)); + let checks = crate::compiler::FUN_DECL_CHECKS.with(std::cell::Cell::get); + assert_eq!(checks, 2_000, "top-level function names gathered and looked up for 1,000 block functions"); +} + #[test] fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() { // A parameter between the eval code and its variable environment has the name, so the block diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 63289f693c..d5dcaf370f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -607,7 +607,8 @@ fn install_checked( let v = i.write_hosted(d)?; undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?; } - Ok(()) + // The prototypes, constructors and members are made without a reservation of their own. + i.reserve_heap(0) } /// Adds the global properties `globals`, each read with its getter and assigned with its setter as diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 7b0578c984..c08168e44f 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -861,6 +861,31 @@ fn with_thing(r: &mut Realm, make: Option) { r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } +#[test] +fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() { + let mut r = realm(1_000_000); + let interp = r.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes; + let class = HostClass { name: "Empty".into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: None }; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); +} + +/// A new object of a host class adds its handle to the heap's total as well as itself, so objects +/// made one after another count each other's handles before a collection does. +#[test] +fn an_object_of_a_host_class_counts_its_handle_toward_the_heap() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + let interp = r.interp(); + let handle: Vec = (0..64).map(f64::from).collect(); + let before = interp.heap.bytes; + interp.write_host_ref(&host_ref("Thing", &handle)).unwrap(); + let added = interp.heap.bytes - before; + assert!(added >= crate::heap::OBJECT_BYTES + crate::host_classes::handle_bytes(handle.len()), "{added}"); +} + #[test] fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { let mut r = realm(1_000_000); 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/agents.rs b/crates/mcp/src/agents.rs index 8f7a8bc8b4..d167ed9135 100644 --- a/crates/mcp/src/agents.rs +++ b/crates/mcp/src/agents.rs @@ -18,6 +18,7 @@ use std::io::{BufRead, BufReader, ErrorKind, Read, Write}; use std::net::{SocketAddr, TcpStream}; use std::path::{Path, PathBuf}; use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant}; @@ -284,7 +285,15 @@ impl LiveBackend { pub fn new(cfg: LiveConfig) -> Self { let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } = cfg; - let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir)); + // The router's own decision on the last lookup (it asks for consent, then makes the + // headless session, under one lock), so the session's file access follows that decision. + let agents_in = Arc::new(AtomicBool::new(false)); + let decided = Arc::clone(&agents_in); + let consent = move |dir: &Path| { + let consent = Consent::new(allowed(), read_settings(dir)); + decided.store(consent.allowed && consent.settings.allow_agent_control, Ordering::SeqCst); + consent + }; let connect = |w: &shared::Window| -> Result { let mut window = Window::new(w.port, w.token.clone()); window.connect()?; @@ -292,7 +301,9 @@ impl LiveBackend { }; let make_headless = move |wanted: &HeadlessFolders| -> Result { let roots = if wanted.read.is_empty() && wanted.write.is_none() { - None + // Agents the person let in are confined to the agent folders: when none can be + // used (the default one can't be made), the session gets no file access. + if agents_in.load(Ordering::SeqCst) { Some(AutomationRoots::none()) } else { None } } else { let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect(); let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect(); @@ -329,6 +340,10 @@ impl Backend for LiveBackend { matches!(self.live.resolve(), Ok(Route::Window(_))) } + fn ui(&self) -> Result { + Ok(matches!(self.live.resolve()?, Route::Window(_))) + } + fn describe(&self) -> String { "the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window" .into() diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 5bbb455854..768c6e8283 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -13,6 +13,11 @@ pub trait Backend { fn call(&mut self, method: &str, params: Value) -> Result; /// True when a real UI is attached (`ui.*` methods like `ui.key` / `ui.inspect` work). fn has_ui(&self) -> bool; + /// Whether a real UI is attached, as [`Self::has_ui`], or why the backend could not reach the + /// window (a launch that timed out, a failed handshake). + fn ui(&self) -> Result { + Ok(self.has_ui()) + } /// Short human description ("headless", "remote 127.0.0.1:7979"). fn describe(&self) -> String; } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 60b27bacbf..d8eaa4fd4d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -229,10 +229,12 @@ fn initialize_negotiates_version() { #[test] fn tool_schemas_are_valid() { let tools = tool_definitions(); + assert!(!tools.is_empty(), "no tools defined"); let mut names = std::collections::HashSet::new(); for t in &tools { let name = t["name"].as_str().expect("name"); - assert!(!name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'), "{name}"); + assert!(!name.is_empty(), "empty tool name"); + assert!(name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'), "{name}"); assert!(names.insert(name), "duplicate tool {name}"); assert!(t["description"].as_str().is_some_and(|d| d.len() > 10), "{name} description"); let schema = &t["inputSchema"]; @@ -1957,10 +1959,11 @@ fn selection_preferences_apply_to_pointer_gestures() { assert_eq!(click(&mut s, 7, 250.0, json!({})), json!([front]), "the path does"); } -/// A Selection tool click inside a closed shape with no fill selects it (#9175), and with Object -/// Selection by Path Only on it selects nothing. +/// A Selection tool click inside a closed shape with no fill selects nothing by default; with +/// Select Inside Unfilled Shapes on it selects the shape (#9175), unless Object Selection by Path +/// Only is on too. #[test] -fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() { +fn a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference() { let mut s = server(); let r = call( &mut s, @@ -1977,10 +1980,13 @@ fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() { assert_eq!(r["isError"], false, "{r}"); serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() }; - assert_eq!(click(&mut s, 2), json!([id])); - let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); + assert_eq!(click(&mut s, 2), json!([]), "off by default"); + let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "selectInsideUnfilledShapes", "value": true}})); assert_eq!(r["isError"], false, "{r}"); - assert_eq!(click(&mut s, 5), json!([]), "path only"); + assert_eq!(click(&mut s, 5), json!([id])); + let r = call(&mut s, 7, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(click(&mut s, 8), json!([]), "path only"); } #[test] diff --git a/crates/mcp/src/tests/agents.rs b/crates/mcp/src/tests/agents.rs index 4be7aa0e05..3beb1838b3 100644 --- a/crates/mcp/src/tests/agents.rs +++ b/crates/mcp/src/tests/agents.rs @@ -132,6 +132,21 @@ fn a_window_that_cannot_prove_the_token_gets_nothing() { assert_eq!(served.load(Ordering::SeqCst), 0); } +// A tool that needs the window reports why the window could not be reached, not that it is closed. +#[test] +fn a_ui_tool_reports_why_the_window_could_not_be_reached() { + let dir = TempFolder::new("agents-ui-bad-token"); + let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); + publish(&dir, port); + let mut b = live(&dir, || true, settings_headless, dir.file("Agents")); + let r = crate::tools::call_tool(&mut b, "inspect_ui", &json!({})); + assert!(r.is_error); + let text = r.content[0]["text"].as_str().unwrap_or_default(); + assert!(text.contains("could not prove"), "{text}"); + assert!(!text.contains(crate::agents::NEEDS_WINDOW), "{text}"); + assert_eq!(served.load(Ordering::SeqCst), 0); +} + #[test] fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() { let dir = TempFolder::new("agents-stale"); @@ -151,6 +166,35 @@ fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() { assert!(e.contains("outside the read root"), "{e}"); } +// The agent folder can't be made (its parent is a file): the headless session the person chose for +// a closed app gets no file access, rather than access to everything. +#[test] +fn a_headless_agent_session_without_usable_folders_reads_and_writes_nothing() { + let dir = TempFolder::new("agents-no-folder"); + std::fs::write(dir.file("blocker"), b"").unwrap(); + let mut b = live(&dir, || true, settings_headless, dir.file("blocker").join("Agents")); + assert!(!b.has_ui()); + let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); + assert_ne!(folders["unrestricted"], true, "{folders}"); + let outside = dir.file("outside.svg"); + std::fs::write(&outside, r#""#).unwrap(); + let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err(); + assert!(e.contains("read authority is absent"), "{e}"); + let saved = dir.file("saved.svg"); + let e = b.call("app.save", json!({"path": saved.to_string_lossy()})).unwrap_err(); + assert!(e.contains("write authority is absent"), "{e}"); + assert!(!saved.exists(), "the refused save must not write the file"); + + // With Allow Agent Control off, the session is the ordinary headless fallback, as before. + fn control_off(dir: &Path) -> AgentSettings { + let mut s = settings_headless(dir); + s.allow_agent_control = false; + s + } + let mut b = live(&dir, || true, control_off, dir.file("blocker").join("Agents")); + assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true); +} + /// A canonical path as the automation roots show it: without Windows' `\\?\` prefix. fn shown(p: PathBuf) -> String { let s = p.to_string_lossy().into_owned(); diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 22cb308a72..66d3eede82 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -25,7 +25,8 @@ pub(super) fn exec(b: &mut dyn Backend, cmd: &str, params: Value) -> Result Result<(), String> { - if b.has_ui() { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) } + // A window that could not be reached says why, rather than that it isn't open. + if b.ui()? { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) } } /// Paint argument → `paint.setFill` / `paint.setStroke` params. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 823d8d88ae..c0dc28dc90 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -223,7 +223,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.shortcutImportDialog", "Import Shortcut Set…", "", - "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", + "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded. The review opens inside Edit › Keyboard Shortcuts, which ui.inspect does not list in `dialogs` and ui.dialog.set does not reach; with a file the reply is {entries, unread}. Without the window, shortcutSet.read reads a file and matches its entries, and importMatches.set stores matches. Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", ), ("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"), ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), @@ -271,7 +271,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.curvatureComb", "Show Curvature Comb", "", - "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color that starts again where the path turns back on itself at a cusp, a straight segment included; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", ), ( "type.hiddenCharacters", @@ -1030,7 +1030,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (listed last in ui.inspect's `dialogs`, with key null), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action (it also lists tab, more, goToKind, goToTarget and the read-only message), which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", @@ -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", @@ -1216,7 +1216,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept, except that preferences saved by an earlier version read it as swatches once), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens (a missing or null tool is an error, and so is one that is not a string). For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept, except that preferences saved by an earlier version read it as swatches once), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1555,7 +1555,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1738,13 +1738,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.cancelOpen", "Cancel Opening", "", - "{} stop opening every file being read in the background (its progress window's Cancel): the files don't open → {cancelled: n}", + "{} stop opening every file being read in the background and every DWG drawing being converted (its progress window's Cancel): the files don't open and the drawings don't open or place → {cancelled: n}", ), ( "file.openInBackground", "Continue in Background", "", - "{} close the progress window of the files being opened; they go on being read, shown in the status bar → {hidden: n}", + "{} close the progress window of the files being opened and the DWG drawings being converted; they go on, shown in the status bar → {hidden: n}", ), ( "file.cancelPlace", @@ -2003,7 +2003,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", + "{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", @@ -2022,7 +2022,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.printPresetDialog", "Print Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (listed last in ui.inspect's `dialogs`, with key null; fields: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", ), ( "plugin.dialog", @@ -2106,7 +2106,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.checkScript", "Check Script…", "", - "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", + "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (listed last in ui.inspect's `dialogs`, with key null; fields `lines`, `notes` and `groups`); with a file the reply is script.check's result, and the report's Copy button copies the report as text; without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", ), ( "ui.perspectiveGridDialog", @@ -2234,6 +2234,11 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move", ), - ("ui.findAndReplace", "Find and Replace…", "", "{} open the Find and Replace dialog (Edit › Find and Replace…; dialog `findReplace`)"), + ( + "ui.findAndReplace", + "Find and Replace…", + "", + "{} open the Find and Replace dialog (Edit › Find and Replace…; listed last in ui.inspect's `dialogs`, with key null; fields and buttons as ui.paramDialog with edit.findReplace)", + ), ("ui.retype", "Retype", "", "{} open the Retype panel (Window › Retype) or start Retype"), ]; diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 9a4c095650..eb47f2a218 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -18,6 +18,8 @@ vectorcraft-brush = { workspace = true } vello_cpu = { workspace = true } # Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2. vello_common = { version = "0.2", default-features = false } +# Hands a rendered pixmap's buffer over as bytes (`group::into_bytes`). +bytemuck = { version = "1", features = ["extern_crate_alloc"] } image = { workspace = true } craft-gif = { workspace = true } craft-image-codecs = { workspace = true } diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 90a35458cc..49e252d206 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -157,8 +157,9 @@ pub struct FrameStats { /// their object moved, or made over such rasters ([`RenderOptions::interacting`]), and those it /// drew at a drag's lower resolution ([`Self::previewed`]). pub moved: usize, - /// The filtered contents, shadows and glows the frame drew at a drag's lower resolution - /// ([`RenderOptions::dragging`]). [`Self::moved`] counts them too. + /// The filtered contents, shadows and glows the frame filtered at a drag's lower resolution + /// ([`RenderOptions::dragging`]). [`Self::moved`] counts them too, and counts alone a raster a + /// drag's earlier frame kept that this frame draws again. pub previewed: usize, /// What the frame drew in a way that depends on the frame's size: effect rasters and filter /// layers cropped to it or made at a lower resolution, blending groups drawn as layers past its diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2eece1125f..28b7966ea4 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -804,7 +804,7 @@ fn three_d_bounds(symbols: &SymbolBoxes, n: &Node) -> Option> { return None; } let doc = Some(symbols.document()); - let art = effects::revolve_art_in(doc, n).or_else(|| effects::solid_art_in(doc, n))?; + let art = effects::three_d_bounds_art_in(doc, n)?; Some(three_d_art_bounds(symbols, &art)) } diff --git a/crates/render/src/fx/entries.rs b/crates/render/src/fx/entries.rs index 24fcf0e38d..64c1cf5ad9 100644 --- a/crates/render/src/fx/entries.rs +++ b/crates/render/src/fx/entries.rs @@ -344,6 +344,7 @@ pub(crate) struct DocInputs { /// may name (`crate::live`). pub(crate) names: u64, pub(crate) cms: usize, + pub(crate) raster_ppi: u64, /// Whether an object in a pattern's or a symbol's art, or in an opacity mask there, has a /// visible plug-in effect. pub(super) plugins: bool, diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index ceead2a01e..d57c34a315 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -33,6 +33,33 @@ pub(crate) fn paint_names(doc: &Document) -> u64 { h.finish() } +/// Whether a raster of content filtered by `chain` can move with its object +/// ([`Renderer::move_pixel_content`]): not under De-Interlace, nor under a Rasterize first in the +/// chain. +fn movable(chain: &[&RasterFx]) -> bool { + !chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }))) && !matches!(chain.first(), Some(RasterFx::Rasterize(_))) +} + +/// The device pixels a frame onto `screen` shows of content reaching `full`, against the device +/// position `at` of the content's anchor. Each side where `screen` cuts the content includes one +/// device pixel for placement rounding and, for raster scale `k` below 1, `ceil(1 / k)` more for +/// bilinear sampling, up to the content's edges. Uncut sides stay at the content's edges. +fn shown(full: Rect, screen: Rect, at: vectorcraft_geom::Point, k: f64) -> Rect { + let s = full.intersect(screen); + let margin = if k < 1.0 { 1.0 + (1.0 / k).ceil() } else { 1.0 }; + let cut = |c: bool| if c { margin } else { 0.0 }; + Rect::new(s.x0 - cut(screen.x0 > full.x0), s.y0 - cut(screen.y0 > full.y0), s.x1 + cut(screen.x1 < full.x1), s.y1 + cut(screen.y1 < full.y1)) + .intersect(full) + - at.to_vec2() +} + +/// Whether `outer` holds all of `inner`, to a millionth of a pixel: the edges of moved content, +/// against its anchor, can differ by rounding. +fn holds(outer: Rect, inner: Rect) -> bool { + let e = 1e-6; + outer.x0 <= inner.x0 + e && outer.y0 <= inner.y0 + e && outer.x1 + e >= inner.x1 && outer.y1 + e >= inner.y1 +} + impl Renderer { /// Paint `content` through the content-changing effects of `rfx` (Gaussian Blur, Feather, the /// Photoshop-style filters and Rasterize) in stack order on its pixels: rendered offscreen over @@ -51,7 +78,9 @@ impl Renderer { /// a drag and for content without a [`Kept`] image, the view with [`pan_margin`] around it. A /// lower-resolution one is kept resampled to the view's pixels ([`Self::resampled`]). /// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`] - /// pixels and is not cached. + /// pixels and is not cached, except content cropped to the view whose raster can move: its + /// raster covers the view with [`pan_margin`] around it, and the drag's later frames move it with + /// the object while what they show of it lies within ([`PixelEntry::valid`]). pub(super) fn pixel_content( &mut self, ctx: &mut RenderContext, @@ -101,11 +130,23 @@ impl Renderer { let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink)); // Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a // margin around the view too, so that later pans within the margin draw it. - let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear) + let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear && e.valid.is_none()) && content.kept.is_none_or(|k| k.shared) && !f.opts.dragging; - let room = match margin { - Some(m) if !fits && again => { + // A drag's raster of content cropped to the view covers a margin around the view too, of + // twice the view's area with the reach around it, and is kept: the drag's later frames move + // it with the object while what they show of it lies within. + let drag_margin = margin + .filter(|_| f.opts.dragging && f.opts.interacting && !fits && key.is_some() && content.kept.is_none() && movable(&chain)) + .map(|m| { + let (w, h) = (screen.width(), screen.height()); + pan_margin((w, h), m, 2.0 * (w + 2.0 * m) * (h + 2.0 * m), f64::from(crate::MAX_RASTER_SIDE)) + }) + .filter(|e| *e > 0.0); + let drag_keep = drag_margin.is_some(); + let room = match (margin, drag_margin) { + (_, Some(e)) => screen.inflate(e, e), + (Some(m), None) if !fits && again => { let e = pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, f64::from(crate::MAX_RASTER_SIDE)); screen.inflate(e, e) } @@ -121,6 +162,17 @@ impl Renderer { let side = f64::from(crate::MAX_RASTER_SIDE); let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0); let (w, h) = ((rw * k).ceil().clamp(1.0, side), (rh * k).ceil().clamp(1.0, side)); + // The scale of a drag's kept raster: 1 when the frame's region fits the drag's budget at full + // resolution, else the scale at which the view, its margin and the reach around them fit + // it, the same for each frame of the drag whatever part of the object the frame shows. + let keep_k = drag_keep.then(|| { + if rw * rh <= DRAG_PIXEL_BUDGET { + return 1.0; + } + let around = room.inflate(margin.unwrap_or(0.0), margin.unwrap_or(0.0)); + let (aw, ah) = (around.width().ceil() + 1.0, around.height().ceil() + 1.0); + (DRAG_PIXEL_BUDGET / (aw * ah)).sqrt().min(side / aw).min(side / ah).min(1.0) + }); // The cached raster: of the whole content at full size at this zoom, else of this view (and // the margin around it). let whole = fits && k >= 1.0; @@ -146,18 +198,27 @@ impl Renderer { let interacting = f.opts.interacting; let in_place = |e: &PixelEntry| match e.view { None => whole, - Some(v) => !whole && v.serves(f.view, screen), + Some(v) => !whole && (e.valid.is_some() || v.serves(f.view, screen)), }; + // A raster a drag kept draws during a drag, while what the frame shows of the content lies + // where its pixels are right ([`PixelEntry::valid`]). let exact = |e: &PixelEntry| { - e.linear == linear && in_place(e) && e.node.is(content.node) && Some(&e.inputs) == inputs.as_ref() && (interacting || !e.moved) + e.linear == linear + && in_place(e) + && e.valid.is_none_or(|v| f.opts.dragging && holds(v, shown(full, screen, f.view * e.anchor, e.k))) + && e.node.is(content.node) + && Some(&e.inputs) == inputs.as_ref() + && (interacting || !e.moved) }; + // During a drag, what the frame shows of the content, against the content's anchor. + let crop = keep_k.map(|d| (d, shown(full, screen, f.view * content.reach.origin(), d))); if interacting - && whole + && (whole || crop.is_some()) && let Some(key) = key && let Some(inputs) = &inputs && !self.pixel_fx.get(&key).is_some_and(exact) { - self.move_pixel_content(f, content, key, &chain, channels, inputs, paint); + self.move_pixel_content(f, content, key, &chain, channels, inputs, crop, paint); } if let Some(e) = key.and_then(|key| self.pixel_fx.get_mut(&key)).filter(|e| exact(e)) { e.stamp = stamp; @@ -171,15 +232,20 @@ impl Renderer { draw_scaled(ctx, image, at, k); return; } - // During a drag, content without a raster to draw renders within the drag's budget and keeps - // no raster (#2558). - let (k, w, h, key) = match drag_scale(f.opts.dragging, (rw, rh), k) { - Some(d) => { + // During a drag, content without a raster to draw renders within the drag's budget (#2558). + // Its raster is kept, marked moved, only when it is cropped to the view and can move. + let (k, w, h, key) = match (keep_k, drag_scale(f.opts.dragging, (rw, rh), k)) { + (Some(d), _) => { + self.stats.moved += 1; + self.stats.previewed += usize::from(d < 1.0); + (d, (rw * d).ceil().clamp(1.0, side), (rh * d).ceil().clamp(1.0, side), key) + } + (None, Some(d)) => { self.stats.moved += 1; self.stats.previewed += 1; (d, (rw * d).ceil().clamp(1.0, side), (rh * d).ceil().clamp(1.0, side), None) } - None => (k, w, h, key), + (None, None) => (k, w, h, key), }; let (wu, hu) = (w as u16, h as u16); let view = Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view; @@ -237,12 +303,12 @@ impl Renderer { let failed = crate::paint::decode_failures() - decoded; let image_left_out = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out; self.image_left_out = outer_image_left_out.map(|outer| outer || image_left_out); - // Content drawn over moved rasters makes a moved raster. - let moved = self.stats.moved > before; - // What the raster is made from, for its object once it moves (`move_pixel_content`): a - // cropped or coarser raster never moves. + // Content drawn over moved rasters makes a moved raster, as does a drag. + let moved = drag_keep || self.stats.moved > before; + // What the raster is made from, for its object once it moves (`move_pixel_content`): of + // the rasters cropped to the view or made coarser, only a drag's moves. let made = key.map(|_| Made { - pixels: if whole { pm.data_as_u8_slice().to_vec() } else { Vec::new() }, + pixels: if whole || drag_keep { pm.data_as_u8_slice().to_vec() } else { Vec::new() }, fx: chain.iter().map(|fx| (*fx).clone()).collect(), size: content.reach.size(), channels: Some(channels), @@ -297,7 +363,7 @@ impl Renderer { // A raster kept for this view alone at a lower resolution than the view's is resampled to the // view's pixels once: each frame that draws it then copies it pixel for pixel, where sampling // it again across the whole view cost several times as much as a plain fill. - let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none_or(|k| k.shared); + let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none_or(|k| k.shared) && !drag_keep; let (image, x0, y0, k) = match view_raster.then(|| self.resampled(f, image.clone(), (x0, y0), k, screen)).flatten() { Some((image, x, y)) => (image, x, y, 1.0), None => (image, x0, y0, k), @@ -311,8 +377,24 @@ impl Renderer { let rel = (x0 - p.x, y0 - p.y); let owner = content.owner.cloned().or_else(|| self.fx_owner.clone().filter(|o| std::ptr::eq(&**o, content.node))); let node = Drawn::of(content.node, owner.as_ref()); - let entry = - PixelEntry { node, linear, anchor, rel, k, image: image.clone(), view: in_view, made, inputs, moved, failed, image_left_out, stamp }; + // The effects saw all they look at for the pixels of the view and its margin. + let valid = drag_keep.then(|| full.intersect(room) - p.to_vec2()); + let entry = PixelEntry { + node, + linear, + anchor, + rel, + k, + image: image.clone(), + view: in_view, + valid, + made, + inputs, + moved, + failed, + image_left_out, + stamp, + }; self.pixel_fx.insert(key, entry); self.trim_fx_rasters(FX_RASTER_BUDGET); } @@ -362,7 +444,13 @@ impl Renderer { /// (and the same Feather outline against its anchor), and whose pixels are the pixels of /// `content` drawn into a raster placed as that one was against its anchor. The raster is kept /// as `content`'s, marked moved, and is drawn at the nearest whole pixel. Content under - /// De-Interlace, or under a Rasterize first in the chain, takes none. + /// De-Interlace, or under a Rasterize first in the chain, takes none ([`movable`]). + /// + /// With `crop` (a drag's frame of content cropped to the view: the scale its raster is made at, + /// and the device pixels the frame shows of the content against its anchor), the raster is + /// instead one a drag's earlier frame kept at that scale or at full resolution + /// ([`PixelEntry::valid`]), whose pixels the effects decided with all they look at over the + /// part the frame shows. #[allow(clippy::too_many_arguments)] fn move_pixel_content( &mut self, @@ -372,10 +460,10 @@ impl Renderer { chain: &[&RasterFx], channels: Channels, inputs: &Inputs, + crop: Option<(f64, Rect)>, paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame), ) { - if chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }))) || matches!(chain.first(), Some(RasterFx::Rasterize(_))) - { + if !movable(chain) { return; } let (linear, stamp, anchor) = (linear_key(f.view), self.stamp, content.reach.origin()); @@ -384,23 +472,29 @@ impl Renderer { (k.1, k.2) == (key.1, key.2) && e.stamp < stamp && e.linear == linear - && e.k >= 1.0 - && e.view.is_none() + && match crop { + None => e.k >= 1.0 && e.view.is_none(), + Some((scale, need)) => { + (e.k.to_bits() == scale.to_bits() || e.k == 1.0) && e.view.is_some() && e.valid.is_some_and(|v| holds(v, need)) + } + } && e.node.id() == content.node.id && e.inputs == *inputs && e.made.fits(chain, content.reach.size(), Some(channels), outline.as_ref()) }; - let Some((old, rel, w, h)) = self.pixel_fx.iter().find(|(k, e)| fits(k, e)).map(|(k, e)| (*k, e.rel, e.image.width(), e.image.height())) + let Some((old, rel, k, w, h)) = + self.pixel_fx.iter().find(|(k, e)| fits(k, e)).map(|(k, e)| (*k, e.rel, e.k, e.image.width(), e.image.height())) else { return; }; // The content drawn where the old content lies in its raster. let p = f.view * anchor; - let view = Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view; + let view = Affine::scale(k) * Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view; let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h))); - let frame = Frame { mt: false, view, visible, ..*f }; + let px = f.px / k; + let frame = Frame { mt: false, view, visible, px, ..*f }; let mut off = f.offscreen_context(w, h); - if hard_edged(chain, f.px) { + if hard_edged(chain, px) { off.set_aliasing_threshold(crate::AntiAlias::None.threshold()); } self.inside_layer(|r| paint(r, &mut off, &frame)); @@ -469,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); @@ -501,15 +596,25 @@ impl Renderer { } }); let names = paint_names(doc); - let found = (patterns, symbols, images, names, Arc::as_ptr(&cms) as usize); + let raster_ppi = doc.raster_ppi().to_bits(); + let found = (patterns, symbols, images, names, Arc::as_ptr(&cms) as usize, raster_ppi); let d = match &self.doc_inputs { - Some((_, d)) if (d.patterns, d.symbols, d.images, d.names, d.cms) == found => d.clone(), + Some((_, d)) if (d.patterns, d.symbols, d.images, d.names, d.cms, d.raster_ppi) == found => d.clone(), _ => { let doc_art = || doc.patterns.iter().flat_map(|p| &p.art).chain(doc.symbols.iter().map(|s| &s.art)); let art = doc_art().map(Arc::downgrade).collect(); let pixels = doc.images.values().flat_map(|b| std::iter::once(&b.bytes).chain(&b.proxy)).map(Arc::downgrade).collect(); let plugins = doc_art().any(|a| crate::holds_plugin_effect(a)); - Arc::new(DocInputs { patterns, symbols, images, names, cms: found.4, plugins, _held: (art, pixels, Arc::downgrade(&cms)) }) + Arc::new(DocInputs { + patterns, + symbols, + images, + names, + cms: found.4, + raster_ppi, + plugins, + _held: (art, pixels, Arc::downgrade(&cms)), + }) } }; self.doc_inputs = Some((at, d.clone())); @@ -570,9 +675,13 @@ impl Renderer { let mut off = frame.offscreen_context(w, h); self.inside_layer(|s| paint(s, &mut off, &frame)); off.flush(); - let mut pm = vello_cpu::Pixmap::new(w, h); + let mut pm = crate::group::blank_pixmap(w, h); off.render(&mut pm, &mut self.resources); - let mut pixels = pm.data_as_u8_slice().to_vec(); + #[cfg(test)] + let rendered = pm.data().as_ptr() as usize; + let mut pixels = crate::group::into_bytes(pm); + #[cfg(test)] + crate::group::RASTERIZE_BUFFERS.with(|b| b.set((rendered, pixels.as_ptr() as usize))); r.finish(&mut pixels); Some((pixels, usize::from(w), usize::from(h))) } diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index efbab00da4..02bf918089 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -95,6 +95,11 @@ pub(crate) struct PixelEntry { /// made for: it draws only there, so dragging other art over the object keeps it (a wide blur, /// or any blur zoomed in, reaches past the pixel budget). pub(super) view: Option, + /// For a raster a drag's frame kept of content cropped to the view, the device pixels (against + /// the anchor's view position) whose pixels the effects decided with all they look at: the + /// drag's later frames move the raster with its object while what they show of it lies within + /// ([`Renderer::move_pixel_content`]). `None` for other rasters. + pub(super) valid: Option, pub(super) made: Made, /// What the content read when the raster was made, with the channels the effects ran on and, /// under De-Interlace, the raster resolution. diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 67b80e6b41..c119ef8b64 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -715,7 +715,7 @@ impl Renderer { let art = match effects::crop_marks_art(a) .or_else(|| crate::addons::halftone::art(doc, a)) .or_else(|| { - let art = effects::revolve_art_in(Some(doc), a).or_else(|| effects::solid_art_in(Some(doc), a)); + let art = effects::revolve_art_drawn_in(Some(doc), a).or_else(|| effects::solid_art_drawn_in(Some(doc), a)); self.stats.three_d_built += usize::from(art.is_some()); three_d |= art.is_some(); art diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index f843ce01f7..be44374572 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -9,6 +9,47 @@ use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, f use crate::tests_fontchange::{fonts_steady, with_fonts_unchanged}; use crate::{RenderOptions, Rendered, Renderer}; +/// Rasterize and culling include the complete rendered image under lights from opposite sides. +#[test] +fn rendered_three_d_painted_bounds_hold_both_shadows() { + let d = Document::new(400.0, 400.0); + for id in [vectorcraft_effects::EXTRUDE, vectorcraft_effects::REVOLVE] { + let mut n = Node::path( + vectorcraft_doc::NodeId(100), + shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects.push( + vectorcraft_effects::new_effect( + id, + &json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": true, + "lights": [{"rotation": 0, "height": 30, "intensity": 100}, {"rotation": 180, "height": 30, "intensity": 100}], + "render": {"mode": "rendered", "quality": "low"} + }), + ) + .unwrap(), + ); + let rasterize = crate::drawn_bounds(&d, &n).unwrap(); + let culling = crate::painted_bounds(&d, &n).unwrap(); + let art = vectorcraft_effects::revolve_art_drawn_in(Some(&d), &n).or_else(|| vectorcraft_effects::solid_art_drawn_in(Some(&d), &n)).unwrap(); + let mut images = 0; + art.walk(&mut |piece| { + if matches!(piece.kind, vectorcraft_doc::NodeKind::Image(_)) { + images += 1; + let image = piece.visual_bounds().unwrap(); + for bounds in [rasterize, culling] { + assert!( + bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1, + "{id}: {bounds:?} holds {image:?}" + ); + } + } + }); + assert_eq!(images, 1, "{id}: draws the rendered image"); + } +} + /// The hash renderers compare to redraw art linked to swatches changes with a global swatch's /// color and spot flag and with the Spot Colors option. #[test] @@ -1718,7 +1759,7 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { let dragged = r.render(&d, 1600, 1000, view, &drag).pixels; assert_eq!(r.stats.previewed, 2, "the shadow and the filtered content"); assert_eq!(r.stats.moved, 2, "counted as moved: the frame after the drag renders them again"); - assert!(r.pixel_fx.is_empty() && r.shadows.values().all(|e| e.stamp < r.stamp), "no raster kept"); + assert!(r.pixel_fx.values().all(|e| e.moved) && r.shadows.values().all(|e| e.stamp < r.stamp), "only rasters marked moved kept"); assert!(dragged != fresh, "at the drag's lower resolution"); let after = r.render(&d, 1600, 1000, view, &still).pixels; assert_eq!((r.stats.previewed, r.stats.moved), (0, 0)); @@ -1742,6 +1783,112 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag"); } +/// At 6400% a Texturized 200 × 150 pt rectangle covers 12800 × 9600 px, past the pixel budget, +/// so its raster is cropped to the view. A drag filters it once, and the drag's later frames +/// move that raster with the object until the object leaves the raster's slack, also when the +/// view shows an edge of the object, and until a pan shows what the raster does not cover. +#[test] +fn a_zoomed_drag_moves_the_cropped_raster_with_its_object() { + let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("texture.texturizer", json!({}))]); + let id = base.layers[0].children().unwrap()[0].id; + let still = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let drag = RenderOptions { interacting: true, dragging: true, ..still.clone() }; + // The rectangle moved by (`dx`, `dy`) device pixels. + let moved = |dx: f64, dy: f64| { + let mut d = base.clone(); + d.node_mut(id).unwrap().transform(Affine::translate((dx / 64.0, dy / 64.0)), false); + d + }; + // A still frame, then eight drag frames: the filters each ran. + let drag_through = |r: &mut Renderer, view: Affine| { + let _ = r.render(&base, 1600, 1000, view, &still); + (1..=8).fold(0, |n, i| { + let _ = r.render(&moved(20.0 * f64::from(i), 13.0 * f64::from(i)), 1600, 1000, view, &drag); + n + r.stats.previewed + }) + }; + // Centered on (290, 175), the view shows the rectangle's right edge. + let edge = Affine::translate((800.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-290.0, -175.0)); + assert_eq!(drag_through(&mut Renderer::new(), edge), 1, "with the object's edge in view"); + let view = Affine::translate((800.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-200.0, -175.0)); + let mut panned = Renderer::new(); + assert_eq!(drag_through(&mut panned, view), 1, "the first drag frame filters the content, and the next seven move its raster"); + // The raster covers between 250 and 300 px around the view as it was when the drag began, and + // the rectangle moved 160 px to the right of where it was. + let held = moved(160.0, 104.0); + let _ = panned.render(&held, 1600, 1000, view, &drag); + assert_eq!(panned.stats.previewed, 0, "where the drag's last frame left it"); + for dx in [40.0, 10.5] { + let _ = panned.render(&held, 1600, 1000, Affine::translate((dx, 0.0)) * view, &drag); + assert_eq!(panned.stats.previewed, 0, "a pan within the raster's margin draws the kept raster ({dx} px)"); + } + let _ = panned.render(&held, 1600, 1000, Affine::translate((200.0, 0.0)) * view, &drag); + assert_eq!(panned.stats.previewed, 1, "a pan that shows what the moved raster does not cover filters the content again"); + let live = RenderOptions { dragging: false, ..drag.clone() }; + let pixels = panned.render(&held, 1600, 1000, view, &live).pixels; + assert!(pixels == Renderer::new().render(&held, 1600, 1000, view, &live).pixels, "an interaction without a drag"); + let mut r = Renderer::new(); + assert_eq!(drag_through(&mut r, view), 1); + let last = moved(1000.0, 0.0); + let _ = r.render(&last, 1600, 1000, view, &drag); + assert_eq!(r.stats.previewed, 1, "a move past the raster's slack filters the content again"); + let after = r.render(&last, 1600, 1000, view, &still).pixels; + let mut fresh = Renderer::new(); + assert!(after == fresh.render(&last, 1600, 1000, view, &still).pixels, "the frame after the drag"); + let kept = r.pixel_fx.values().find(|e| e.node.is(last.node(id).unwrap()) && e.valid.is_none()).unwrap(); + let fresh = fresh.pixel_fx.values().next().unwrap(); + assert_eq!( + (kept.image.width(), kept.image.height()), + (fresh.image.width(), fresh.image.height()), + "the first still frame keeps the same crop as a fresh renderer" + ); + + // Only a narrow strip at the rectangle's right edge lies in view, so its crop fits the drag budget. + let strip = Affine::translate((300.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-300.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&moved(20.0, 13.0), 1600, 1000, strip, &drag); + assert_eq!(r.stats.previewed, 0, "the narrow crop keeps full resolution"); + assert_eq!(r.pixel_fx.values().filter(|e| e.valid.is_some()).count(), 1, "the drag keeps one cropped raster"); + assert!(r.pixel_fx.values().any(|e| e.valid.is_some() && e.k == 1.0), "the kept raster uses scale 1"); + let image = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap().image.clone(); + for i in 2..=4 { + let _ = r.render(&moved(20.0 * f64::from(i), 13.0 * f64::from(i)), 1600, 1000, strip, &drag); + assert_eq!(r.stats.previewed, 0, "a later frame within the slack keeps full resolution"); + assert_eq!(r.pixel_fx.values().filter(|e| e.valid.is_some()).count(), 1, "the drag keeps one cropped raster"); + let kept = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap(); + assert!(std::sync::Arc::ptr_eq(&image, &kept.image), "a later frame within the slack draws the kept raster"); + } + // The crop grows past the drag budget while the visible content stays within the 255 px slack. + let _ = r.render(&moved(120.0, 13.0), 1600, 1000, strip, &drag); + assert_eq!(r.stats.previewed, 0, "crossing the drag budget draws the full-resolution raster"); + let kept = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap(); + assert!(std::sync::Arc::ptr_eq(&image, &kept.image), "crossing the drag budget draws the kept raster"); +} + +#[test] +fn a_zoomed_drag_keeps_the_sampling_footprint_inside_the_valid_crop() { + let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("texture.texturizer", json!({}))]); + let id = base.layers[0].children().unwrap()[0].id; + let drag = RenderOptions { interacting: true, dragging: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((800.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-200.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&base, 1600, 1000, view, &drag); + let kept = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap(); + assert!(kept.k < 1.0, "the drag raster uses a lower resolution"); + let valid = kept.valid.unwrap(); + let at = view * kept.anchor; + let footprint = 1.0 + (1.0 / kept.k).ceil(); + let gap = (1.0 + footprint) / 2.0; + let dx = -at.x - valid.x0 - gap; + let left = -(at.x + dx); + assert!(left - 1.0 > valid.x0, "the visible edge and placement rounding stay inside the valid crop"); + assert!(left - footprint < valid.x0, "the sampling footprint reaches past the valid crop"); + let mut moved = base.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((dx / 64.0, 0.0)), false); + let _ = r.render(&moved, 1600, 1000, view, &drag); + assert_eq!(r.stats.previewed, 1, "the sampling footprint outside the valid crop filters the content again"); +} + #[test] fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { let doc = doc_with( @@ -2233,3 +2380,36 @@ fn geometry_effects_work_from_bounds_that_hold_lone_anchors() { } } } + +#[test] +fn rendered_art_follows_document_raster_resolution() { + let mut d = Document::new(200.0, 200.0); + d.raster_effects_ppi = 36.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(50.0, 50.0, 100.0, 100.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects.push(crate::effects::new_effect("threeD.extrude", &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + let n = Arc::new(n); + let mut renderer = Renderer::new(); + // The width of the art's image, counted only when the image carries its pixels. + let image_width = |art: &Node| { + let mut width = 0; + art.walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(image) = &n.kind { + assert!(image.pixels.is_some(), "the rendered image has no pixels"); + width = image.width; + } + }); + width + }; + let before = renderer.fx_art(&d.symbol_boxes(), &n, true); + d.raster_effects_ppi = 144.0; + renderer.stamp += 1; + let measured = renderer.measured_fx_art(&d.symbol_boxes(), &n); + let after = renderer.fx_art(&d.symbol_boxes(), &n, true); + assert!(image_width(&before) > 0); + assert!(image_width(&after) > image_width(&before)); + assert!(Arc::ptr_eq(&measured, &after)); +} diff --git a/crates/render/src/group.rs b/crates/render/src/group.rs index 12490eb308..82f774631c 100644 --- a/crates/render/src/group.rs +++ b/crates/render/src/group.rs @@ -209,13 +209,17 @@ impl Renderer { pub(crate) fn finish(&mut self, ctx: &mut RenderContext, settings: vello_cpu::RasterizerSettings) -> Pixmap { ctx.flush(); let Some(below) = self.picture.take() else { - let mut pm = Pixmap::new(ctx.width(), ctx.height()); + let mut pm = blank_pixmap(ctx.width(), ctx.height()); ctx.render_with(&mut pm, &mut self.resources, settings); + #[cfg(test)] + FINISHED.with(|p| p.set(pm.data().as_ptr() as usize)); return pm; }; let mut pm = Arc::unwrap_or_clone(below); let over = vello_cpu::RasterizerSettings { composite_mode: vello_cpu::CompositeMode::SrcOver, ..settings }; ctx.render_with(&mut pm, &mut self.resources, over); + #[cfg(test)] + FINISHED.with(|p| p.set(pm.data().as_ptr() as usize)); pm } @@ -345,10 +349,31 @@ pub(crate) fn draw_pixmap(ctx: &mut RenderContext, pm: Arc, at: (f64, f6 ctx.set_transform(Affine::IDENTITY); } +/// A transparent `w`×`h` pixmap in zeroed memory, which the allocator can hand out without +/// writing every byte as [`Pixmap::new`] does. +pub(crate) fn blank_pixmap(w: u16, h: u16) -> Pixmap { + Pixmap::from_parts(bytemuck::zeroed_vec(usize::from(w) * usize::from(h)), w, h) +} + +/// `pm`'s premultiplied RGBA pixels as bytes, in the buffer `pm` held. +pub(crate) fn into_bytes(pm: Pixmap) -> Vec { + bytes_of(pm.take()) +} + +/// `pixels` as bytes: the same allocation when `T` is aligned like a byte, else a copy. +pub(crate) fn bytes_of(pixels: Vec) -> Vec { + bytemuck::allocation::try_cast_vec(pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec()) +} + #[cfg(test)] thread_local! { /// The pixels [`draw_pixmap`] has drawn on this thread. pub(crate) static PIXELS_DRAWN: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The address of the pixel buffer [`Renderer::finish`] last returned on this thread. + pub(crate) static FINISHED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The addresses of the pixmap the last Effect › Rasterize image on this thread was rendered + /// into and of the bytes it was returned in. + pub(crate) static RASTERIZE_BUFFERS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; } /// The offscreen pixels that groups drawn offscreen may keep alive at once, in frames: deeper diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 2884e9c4d8..602a32e4d0 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -119,7 +119,7 @@ fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u6 let mut shown = Shown::default(); hash_resources(symbols, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; - (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) + (walked.key(cms, names, symbols.document().raster_ppi().to_bits()), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } /// What [`hash_resources`] found in a node: the hash of what it walked, whether it found type or @@ -135,10 +135,10 @@ impl Walked { /// The [`resources_key`] of the node walked: the walk's hash, the layout inputs (fonts and /// hyphenation exceptions, [`vectorcraft_text::layout_inputs`]) when it found type or a placed /// file, the plug-in revision and the hash of the document's swatch and pattern - /// names (`names`) when it found a plug-in effect, and the color settings `cms`. Whether a - /// plug-in paints its pieces depends on the plug-ins installed, so the names count for every - /// plug-in effect. - fn key(self, cms: usize, names: u64) -> u64 { + /// names (`names`) when it found a plug-in effect, the color settings `cms` and the document's + /// raster resolution `raster_ppi`. Whether a plug-in paints its pieces depends on the plug-ins + /// installed, so the names count for every plug-in effect. + fn key(self, cms: usize, names: u64, raster_ppi: u64) -> u64 { let mut h = DefaultHasher::new(); self.hash.hash(&mut h); if self.text { @@ -149,6 +149,7 @@ impl Walked { names.hash(&mut h); } cms.hash(&mut h); + raster_ppi.hash(&mut h); h.finish() } } @@ -484,7 +485,7 @@ impl Renderer { && std::ptr::eq(node.as_ptr(), Arc::as_ptr(n)) && read.same_art(&inputs) { - return (walked.key(inputs.cms, inputs.names), inputs, vec![]); + return (walked.key(inputs.cms, inputs.names, inputs.raster_ppi), inputs, vec![]); } #[cfg(test)] { 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 5f4b5d71df..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,8 +339,8 @@ 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 fdf7847412..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 = pm.data_as_u8_slice().to_vec(); + 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. @@ -504,7 +541,7 @@ impl Renderer { let pm = self.finish(&mut ctx, self.raster); self.end_frame(); self.raster = raster; - pm.data_as_u8_slice().to_vec() + group::into_bytes(pm) } /// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into @@ -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 9ee678965c..afa49188c2 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -18,6 +18,7 @@ mod container; mod curvedstrokeedges; mod dither; pub(super) mod fontchange; +mod framebuffer; mod freeform; mod fxzoom; mod isolation; @@ -40,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/framebuffer.rs b/crates/render/src/tests/framebuffer.rs new file mode 100644 index 0000000000..5931449617 --- /dev/null +++ b/crates/render/src/tests/framebuffer.rs @@ -0,0 +1,136 @@ +//! The pixels a render returns are the buffer it rendered into, handed over without a copy: a +//! page, a node, a pattern swatch and the image of Effect › Rasterize. + +use std::cell::Cell; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::pattern::pattern_paint; +use vectorcraft_doc::{Appearance, Effect, Node, PatternDef}; +use vectorcraft_geom::shapes; + +use crate::group::{FINISHED, RASTERIZE_BUFFERS, blank_pixmap, bytes_of, into_bytes}; +use crate::*; + +/// A red square over 10..30 pt with the effects `fx` (id, params). +fn red_square(fx: &[(&str, serde_json::Value)]) -> Document { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.appearance.effects = fx.iter().map(|(id, params)| Effect { id: (*id).into(), params: params.clone(), visible: true }).collect(); + d.insert(Some(l), 0, n).unwrap(); + d +} + +fn finished() -> usize { + FINISHED.with(Cell::get) +} + +/// A pixmap with the red square drawn into it, over transparency. +fn drawn(w: u16, h: u16) -> Pixmap { + let mut ctx = crate::threads::single_threaded_context(w, h); + ctx.set_paint(peniko::Color::from_rgba8(255, 0, 0, 255)); + ctx.fill_rect(&Rect::new(10.0, 10.0, 30.0, 30.0)); + ctx.flush(); + let mut pm = Pixmap::new(w, h); + ctx.render(&mut pm, &mut Resources::new()); + pm +} + +#[test] +fn a_pixmap_is_handed_over_in_its_own_buffer_with_the_same_bytes() { + let pm = drawn(40, 30); + let (bytes, at) = (pm.data_as_u8_slice().to_vec(), pm.data().as_ptr() as usize); + let out = into_bytes(pm); + assert_eq!(out.as_ptr() as usize, at, "the buffer is handed over, not copied"); + assert!(out == bytes, "the same bytes"); + assert_eq!(&out[(20 * 40 + 20) * 4..][..4], &[255, 0, 0, 255]); +} + +#[test] +fn pixels_aligned_wider_than_a_byte_are_copied_with_the_same_bytes() { + let words: Vec = (0..1000u32).map(|i| i.wrapping_mul(0x9e37_79b9)).collect(); + let bytes: Vec = words.iter().flat_map(|w| w.to_ne_bytes()).collect(); + let out = bytes_of(words); + assert!(out == bytes, "a buffer the cast cannot take is copied byte for byte"); + assert!(bytes_of(Vec::::new()).is_empty()); + assert!(bytes_of(Vec::::new()).is_empty()); +} + +#[test] +fn a_blank_pixmap_is_transparent_and_renders_as_a_new_one_does() { + for (w, h) in [(1, 1), (40, 30), (257, 3)] { + let blank = blank_pixmap(w, h); + assert_eq!((blank.width(), blank.height()), (w, h)); + assert!(blank.data_as_u8_slice() == Pixmap::new(w, h).data_as_u8_slice()); + } + let mut ctx = crate::threads::single_threaded_context(40, 30); + ctx.set_paint(peniko::Color::from_rgba8(0, 0, 255, 128)); + ctx.fill_rect(&Rect::new(5.0, 5.0, 25.0, 15.0)); + ctx.flush(); + let mut on_blank = blank_pixmap(40, 30); + ctx.render(&mut on_blank, &mut Resources::new()); + assert!(on_blank.data_as_u8_slice() == drawn_with(&ctx).data_as_u8_slice()); +} + +/// What `ctx` renders into a new pixmap of its size. +fn drawn_with(ctx: &RenderContext) -> Pixmap { + let mut pm = Pixmap::new(ctx.width(), ctx.height()); + ctx.render(&mut pm, &mut Resources::new()); + pm +} + +#[test] +fn a_page_render_returns_the_buffer_it_rendered_into() { + let d = red_square(&[]); + let mut r = Renderer::new(); + for background in [None, Some([255, 255, 255, 255])] { + let opts = RenderOptions { background, ..Default::default() }; + let out = r.render(&d, 64, 48, Affine::IDENTITY, &opts); + assert_eq!(out.pixels.len(), 64 * 48 * 4); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "background {background:?}: the page's pixels are returned without a copy"); + } +} + +#[test] +fn a_node_render_returns_the_buffer_it_rendered_into() { + let d = red_square(&[]); + let n = d.layers[0].children().unwrap()[0].clone(); + let out = Renderer::new().render_node(&d, &n, 40, 40, Affine::IDENTITY).unwrap(); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "the node's pixels are returned without a copy"); + assert_eq!(&out.pixels[(20 * 40 + 20) * 4..][..4], &[255, 0, 0, 255]); +} + +#[test] +fn a_pattern_swatch_returns_the_buffer_it_rendered_into() { + let mut d = Document::new(100.0, 100.0); + let red = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + let mut def = PatternDef::new("Checks", vec![Arc::new(red)]); + def.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + d.patterns.push(def); + let l = d.layers[0].id; + let filled = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0)); + d.insert(Some(l), 0, filled).unwrap(); + let out = render_pattern_swatch(&d, "Checks", 20).unwrap(); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "the swatch's pixels are returned without a copy"); +} + +#[test] +fn the_rasterize_effect_keeps_the_buffer_it_rendered_its_image_into() { + RASTERIZE_BUFFERS.with(|b| b.set((0, 0))); + let d = red_square(&[("rasterize", json!({}))]); + let opts = RenderOptions { background: None, artboards: false, ..Default::default() }; + Renderer::new().render(&d, 100, 100, Affine::scale(2.0), &opts); + let (rendered, bytes) = RASTERIZE_BUFFERS.with(Cell::get); + assert_ne!(rendered, 0, "the effect made its image"); + assert_eq!(bytes, rendered, "the image's pixels are taken from its pixmap without a copy"); +} 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/svg/src/css.rs b/crates/svg/src/css.rs index d37715f9b9..fca1b86de3 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -805,7 +805,12 @@ fn corners(path: &PathData, live: Option<&LiveShape>) -> Option { (sweep < 1e-6 || (sweep - 360.0).abs() < 1e-6).then_some(Corners::Ellipse) } Some( - LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Line { .. } | LiveShape::Path { .. }, + LiveShape::Rectangle { .. } + | LiveShape::Ellipse { .. } + | LiveShape::Polygon { .. } + | LiveShape::Star { .. } + | LiveShape::Line { .. } + | LiveShape::Path { .. }, ) => None, None => is_upright_rectangle(path).then_some(Corners::Square), } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 37768ea651..1b19a847b2 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -27,7 +27,8 @@ pub use material::{Highlight, Material}; mod caps; mod mesh; pub use mesh::{ - Mesh, MeshPart, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface, + Mesh, MeshPart, MeshProjection, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, plane_meshed, + revolve_mesh, revolve_mesh_projection, revolve_mesh_surface, }; mod shadow; pub use shadow::{ @@ -314,6 +315,23 @@ impl Revolve { [ch * cr, -ch * sr, if o.light_behind { -sh } else { sh }] } + /// The directional lights the surface is shaded with: its [`Revolve::lights`], or the one light + /// its single-light settings describe. + pub fn active_lights(self) -> Vec { + let o = self.sanitized(); + match o.lights { + Some(lights) => lights.iter().copied().collect(), + None => vec![Light { + rotation: o.light_rotation, + height: o.light_height, + behind: o.light_behind, + color: o.light_color, + intensity: o.light_intensity, + softness: o.light_softness, + }], + } + } + /// Light-direction orbits as (centre, cosine basis, sine basis), in view space. /// The first changes the Rotation at the current Height: a circle on the page. The second /// changes the Height at the current Rotation; its parameter runs 0..90 degrees. diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 77c6371e49..bd15fd33e8 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -128,7 +128,39 @@ pub fn extrude_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Extr /// Rotate's plane ([`crate::plane`]) as a mesh. pub fn plane_mesh(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result { - plane_faces(path, rule, bounds, view, Keep::Faces).and_then(|(_, faces, _)| mesh(&faces?)) + plane_meshed(path, rule, bounds, view).map(|(mesh, _)| mesh) +} + +/// [`plane_mesh`] with the projection its faces are drawn with ([`MeshProjection`]). +pub fn plane_meshed(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result<(Mesh, Option), String> { + let (_, faces, projection) = plane_faces(path, rule, bounds, view, Keep::Faces)?; + Ok((mesh(&faces?)?, projection.map(MeshProjection::of))) +} + +/// Where the points of a mesh land on the page, as the effect projects the faces it draws: the +/// page point the mesh's origin draws at, and the eye's distance in front of it (`None` without +/// perspective). A point `z` in front of the origin is scaled by `eye / (eye − z)`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshProjection { + pub origin: Point, + pub eye: Option, +} + +impl MeshProjection { + pub(crate) fn of(p: crate::shadow::Projection) -> Self { + Self { origin: p.origin, eye: p.eye } + } + + /// The page point mesh point `p` (x right, y up, z toward the viewer) draws at. + pub fn project(&self, p: [f64; 3]) -> Point { + let f = crate::perspective_scale(self.eye, p[2]); + Point::new(self.origin.x + p[0] * f, self.origin.y - p[1] * f) + } +} + +/// The projection Revolve's mesh ([`revolve_mesh`]) of a profile with bounds `bounds` is drawn with. +pub fn revolve_mesh_projection(bounds: Rect, options: Revolve) -> MeshProjection { + MeshProjection::of(crate::revolve_projection(bounds, options.sanitized())) } /// Inflate's solids for several shapes of one object ([`crate::inflate_together`]) as meshes, one @@ -150,12 +182,13 @@ pub struct MeshedSolid { pub facets: Vec, /// The faces before projection, or the error the mesh alone gives when there are too many. faces: Result, String>, + projection: Option, } /// A solid with no facets and an empty mesh. impl Default for MeshedSolid { fn default() -> Self { - Self { facets: vec![], faces: Ok(vec![]) } + Self { facets: vec![], faces: Ok(vec![]), projection: None } } } @@ -164,12 +197,22 @@ impl MeshedSolid { pub fn mesh(&self) -> Result { mesh(self.faces.as_ref().map_err(String::clone)?) } + + /// The projection the solid's facets are drawn with, which takes its mesh's points to the page; + /// `None` for a solid with no faces. + pub fn projection(&self) -> Option { + self.projection + } } /// Extrude & Bevel's solid ([`crate::extrude`]) and its mesh ([`extrude_mesh`]) from one build. An /// error where [`crate::extrude`] gives one. pub fn extrude_meshed(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result { - extrude_faces(path, rule, bounds, options, view, Keep::Both).map(|(facets, faces, _)| MeshedSolid { facets, faces }) + extrude_faces(path, rule, bounds, options, view, Keep::Both).map(|(facets, faces, projection)| MeshedSolid { + facets, + faces, + projection: projection.map(MeshProjection::of), + }) } /// Inflate's solids for several shapes of one object ([`crate::inflate_each`]) and their meshes @@ -181,7 +224,8 @@ pub fn inflate_meshed( options: Inflate, view: View, ) -> impl Iterator> + use<> { - inflate_faces(shapes, bounds, options, view, Keep::Both).map(|r| r.map(|(facets, faces, _)| MeshedSolid { facets, faces })) + inflate_faces(shapes, bounds, options, view, Keep::Both) + .map(|r| r.map(|(facets, faces, projection)| MeshedSolid { facets, faces, projection: projection.map(MeshProjection::of) })) } /// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 8a89f5e3cc..137c0c4996 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -61,6 +61,13 @@ impl Default for Shadow { } impl Shadow { + /// The blur radius in points for a solid whose largest size is `size`. + fn blur(self, size: f64) -> f64 { + let s = self.sanitized(); + let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR); + if blur.is_finite() { blur } else { 0.0 } + } + fn sanitized(self) -> Self { Self { distance: finite(self.distance, 0.0, 0.0, 1.0), @@ -149,6 +156,20 @@ impl ShadowPlane { } } +/// Where a shadow's plane lies ([`ShadowCaster::placement`]): its unit normal toward the object and +/// two unit axes along it, its level along the normal, the foot of the object's center on it, half +/// the side of the square it ends at, and the object's largest size. +#[derive(Clone, Copy, Debug)] +struct Placement { + n: V3, + u: V3, + w: V3, + level: f64, + foot: V3, + half: f64, + size: f64, +} + /// The faces of one object's solids, gathered to cast one shadow. The solids of one object share /// their bounds and view, so they share a projection: the first solid's is kept. Each solid added /// returns the range of its faces, so that the shadow of some of them can be drawn on the plane @@ -261,6 +282,19 @@ impl ShadowCaster { let p = self.projection?; let light = p.light()?; let s = shadow.sanitized(); + let Placement { n, u, w, level, foot, half, size } = self.placement(s, faces)?; + let reach = n.dot(light); + if !reach.is_finite() || reach < MIN_LIGHT { + return None; + } + let blur = s.blur(size); + Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half, blur }) + } + + /// Where the plane of sanitized settings `s` lies for the faces in the ranges `faces`, whatever + /// lights it: `None` when there are none. + fn placement(&self, s: Shadow, faces: &[Range]) -> Option { + let p = self.projection?; let corners = || self.within(faces).flat_map(|face| face.contours.iter().flatten()); let first = *corners().next()?; let (lo, hi) = corners() @@ -274,17 +308,55 @@ impl ShadowCaster { (r(V3(0.0, -1.0, 0.0)), r(V3(1.0, 0.0, 0.0)), r(V3(0.0, 0.0, 1.0))) } }; - let reach = n.dot(light); - if !reach.is_finite() || reach < MIN_LIGHT { - return None; - } // The plane: every corner at least `distance` × size in front of it. let level = corners().map(|v| n.dot(*v)).fold(f64::INFINITY, f64::min) - s.distance * size; let centre = V3((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0, (lo.2 + hi.2) / 2.0); let foot = add(centre, scale(n, level - n.dot(centre))); - let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR); - let blur = if blur.is_finite() { blur } else { 0.0 }; - Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size, blur }) + Some(Placement { n, u, w, level, foot, half: 2.0 * s.bounds * size, size }) + } + + /// The blur radius in points for `shadow` and the faces in the ranges `faces`, regardless of + /// the light direction; `None` when there are no faces. + pub fn shadow_blur(&self, shadow: Shadow, faces: &[Range]) -> Option { + Some(shadow.blur(self.placement(shadow.sanitized(), faces)?.size)) + } + + /// The rectangle of the plane `shadow` falls on that holds the shadows the faces in the ranges + /// `faces` cast toward each of the lights in `toward` (directions toward a light, in view space, + /// with y down), widened on each side by the blur radius plus `margin` times the faces' largest + /// size and cut where the plane ends: its four corners in view space, in order round it. Every light counts, not only the + /// first. `None` when there are no faces, when no light reaches the plane, or when no shadow falls + /// within it. + pub fn receiver(&self, shadow: Shadow, faces: &[Range], toward: &[[f64; 3]], margin: f64) -> Option<[[f64; 3]; 4]> { + let Placement { n, u, w, level, foot, half, size } = self.placement(shadow.sanitized(), faces)?; + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for t in toward { + let light = V3(t[0], t[1], t[2]).unit(); + let reach = n.dot(light); + if !reach.is_finite() || reach < MIN_LIGHT { + continue; + } + for v in self.within(faces).flat_map(|face| face.contours.iter().flatten()) { + let d = add(*v, scale(light, -(n.dot(*v) - level) / reach)).sub(foot); + let q = [u.dot(d), w.dot(d)]; + for k in 0..2 { + lo[k] = lo[k].min(q[k]); + hi[k] = hi[k].max(q[k]); + } + } + } + let m = shadow.blur(size) + if margin.is_finite() { margin.max(0.0) * size } else { 0.0 }; + let [a0, b0] = [0, 1].map(|k| (lo[k] - m).clamp(-half, half)); + let [a1, b1] = [0, 1].map(|k| (hi[k] + m).clamp(-half, half)); + if !(a1 > a0 && b1 > b0) { + return None; + } + let at = |a: f64, b: f64| { + let p = add(foot, add(scale(u, a), scale(w, b))); + [p.0, p.1, p.2] + }; + let corners = [at(a0, b0), at(a1, b0), at(a1, b1), at(a0, b1)]; + corners.iter().flatten().all(|v| v.is_finite()).then_some(corners) } /// The shadow the faces in the ranges `faces` cast on `plane`, on the page, filled with the diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index deeaab4dde..1d5c442254 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -93,6 +93,11 @@ impl View { view.lights.map_or(view.light_color != [1.0; 3], |lights| lights.iter().any(|light| light.color != [1.0; 3])) } + /// The directional lights the view shades with ([`Revolve::active_lights`]). + pub fn active_lights(self) -> Vec { + self.revolve().active_lights() + } + /// Whether the view shades with a material other than [`crate::Material::DEFAULT`], which also /// needs RGB shading: its highlight ([`Facet::highlight`]) and a metal's tint. pub fn shades_material(self) -> bool { diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index e4f4b272c5..0fbc4c5522 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -24,8 +24,9 @@ pub const ID: &str = "box3d"; /// The `vc-` prefix marks it as internal so SVG export omits it from `data-*` attributes. pub const KEY: &str = "vc-shape-tools"; -/// Maximum stored JSON length read back from a file. -const MAX_STORED: usize = 4096; +/// Maximum stored JSON length read back from a file: room for a 1000-point star's 2000 corner +/// radii and kinds. +const MAX_STORED: usize = 128 * 1024; fn whole_mode() -> EllipseMode { EllipseMode::Whole @@ -35,6 +36,11 @@ fn default_pie() -> (f64, f64) { (0.0, 360.0) } +/// A polygon's sides or a star's points read from a file, clamped as the tools clamp them. +fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + /// Parse an [`EllipseMode`] from a command or tool option string (`"slice"`/`"pie"`, `"arc"`/`"open"`, /// `"chord"`, `"whole"`/`"full"`/`"closed"`). pub fn parse_arc_mode(s: &str) -> Option { @@ -86,6 +92,9 @@ pub enum CustomShape { }, Polygon { radius: f64, + /// Sides, or a star's points: 2–1000, as the Polygon and Star tools give them; a file's + /// count is clamped when read. + #[serde(deserialize_with = "de_sides")] sides: u32, xf: Affine, #[serde(default)] @@ -144,7 +153,8 @@ impl CustomShape { CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode } => { let raw = match spoke_ratio { Some(ratio) => { - let r2 = (*radius * ratio.clamp(0.01, 1.0)).max(0.01); + // Any ratio a live star takes (0 to 1) draws as it is. + let r2 = *radius * if ratio.is_finite() { ratio.clamp(0.0, 1.0) } else { 0.01 }; shapes::star_configured(Point::ZERO, *radius, r2, *sides, 0.0, *rounded, *randomized) } None => shapes::polygon_configured(Point::ZERO, *radius, *sides, 0.0, *rounded, *randomized), @@ -184,7 +194,20 @@ impl CustomShape { { Some(LiveShape::Polygon { radius: *radius, - sides: *sides, + sides: (*sides).clamp(3, 1000), + xf: *xf, + radii: radii.clone(), + kinds: kinds.clone(), + radii_relative: *radii_relative, + }) + } + CustomShape::Polygon { + radius, sides, xf, radii, kinds, radii_relative, spoke_ratio: Some(ratio), rounded, randomized, arc_mode, .. + } if (0.0..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole => { + Some(LiveShape::Star { + r1: *radius, + r2: *radius * ratio, + points: (*sides).clamp(2, 1000), xf: *xf, radii: radii.clone(), kinds: kinds.clone(), @@ -197,7 +220,13 @@ impl CustomShape { /// Whether this shape uses extended add-on parameters beyond what `LiveShape` stores on its own. pub fn needs_extra_storage(&self) -> bool { - self.to_live_shape().is_none() + // A whole shape's `LiveShape` keeps no angles, so angles set for a later arc mode are + // stored with it. + let angles = match self { + CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. } => *pie != (0.0, 360.0), + _ => false, + }; + self.to_live_shape().is_none() || angles } /// Write this shape's regenerated path, `LiveShape` (if standard) and `vc-shape-tools` attribute @@ -279,9 +308,14 @@ impl CustomShape { LiveShape::Ellipse { w, h, pie, xf } => { let span = (pie.1 - pie.0).rem_euclid(360.0); let default_mode = if span < 1e-9 || 360.0 - span < 1e-9 { EllipseMode::Whole } else { EllipseMode::Slice }; - let arc_mode = match stored { - Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => arc_mode, - _ => default_mode, + let (pie, arc_mode) = match stored { + // A whole ellipse's `LiveShape` draws the full turn; its stored angles wait + // for another arc mode. + Some(CustomShape::Ellipse { arc_mode: EllipseMode::Whole, pie: angles, .. }) if default_mode != EllipseMode::Slice => { + (angles, EllipseMode::Whole) + } + Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => (pie, arc_mode), + _ => (pie, default_mode), }; Some(CustomShape::Ellipse { w, h, pie, arc_mode, xf }) } @@ -294,6 +328,26 @@ impl CustomShape { }; Some(CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode }) } + LiveShape::Star { r1, r2, points, xf, radii, kinds, radii_relative } => { + let (rounded, randomized, pie, arc_mode) = match stored { + Some(CustomShape::Polygon { rounded, randomized, pie, arc_mode, .. }) => (rounded, randomized, pie, arc_mode), + _ => (0.0, 0.0, (0.0, 360.0), EllipseMode::Whole), + }; + let spoke_ratio = Some(if r1 > 0.0 { r2 / r1 } else { 0.0 }); + Some(CustomShape::Polygon { + radius: r1, + sides: points, + xf, + radii, + kinds, + radii_relative, + spoke_ratio, + rounded, + randomized, + pie, + arc_mode, + }) + } LiveShape::Line { .. } | LiveShape::Path { .. } => stored, } } @@ -759,3 +813,100 @@ impl Tool for Box3dTool { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn read_back(spoke_ratio: Option, sides: u64) -> CustomShape { + let shape = CustomShape::Polygon { + radius: 10.0, + sides: 5, + xf: Affine::IDENTITY, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio, + rounded: 0.0, + randomized: 0.0, + pie: (0.0, 360.0), + arc_mode: EllipseMode::Whole, + }; + let mut v = serde_json::to_value(&shape).unwrap_or_default(); + v["sides"] = json!(sides); + serde_json::from_value(v).unwrap_or_else(|e| panic!("{e}")) + } + + #[test] + fn a_file_point_count_is_clamped_as_the_tools_clamp_it() { + let star = read_back(Some(0.5), u64::from(u32::MAX)); + let CustomShape::Polygon { sides, .. } = &star else { panic!("a polygon") }; + assert_eq!(*sides, 1000); + let CustomShape::Polygon { sides, .. } = read_back(None, 0) else { panic!("a polygon") }; + assert_eq!(sides, 2); + let Some(LiveShape::Star { points, .. }) = star.to_live_shape() else { panic!("a live star") }; + assert_eq!(points, 1000); + assert_eq!(star.to_path().anchor_count(), 2000); + let polygon = read_back(None, u64::from(u32::MAX)); + let Some(LiveShape::Polygon { sides, .. }) = polygon.to_live_shape() else { panic!("a live polygon") }; + assert_eq!(sides, 1000); + let Some(LiveShape::Polygon { sides, .. }) = read_back(None, 0).to_live_shape() else { panic!("a live polygon") }; + assert_eq!(sides, 3); + let Some(LiveShape::Star { points, .. }) = read_back(Some(0.5), 0).to_live_shape() else { panic!("a live star") }; + assert_eq!(points, 2); + } + + /// A whole star draws every point whatever its pie angles hold, so it stays live. + #[test] + fn a_whole_star_with_other_pie_angles_is_live() { + let mut star = read_back(Some(0.5), 5); + let CustomShape::Polygon { pie, .. } = &mut star else { panic!("a polygon") }; + *pie = (0.0, 90.0); + assert!(matches!(star.to_live_shape(), Some(LiveShape::Star { points: 5, .. })), "{star:?}"); + } + + /// A 1000-point star with a radius on each of its 2000 corners, written and read back. + fn round_trip(arc_mode: EllipseMode) -> CustomShape { + let mut star = read_back(Some(0.5), 1000); + let CustomShape::Polygon { radii, kinds, pie, arc_mode: mode, .. } = &mut star else { panic!("a polygon") }; + *radii = vec![12.0; 2000]; + *kinds = vec![CornerKind::Round; 2000]; + *pie = (0.0, 90.0); + *mode = arc_mode; + let mut node = Node::path(vectorcraft_doc::NodeId(1), PathData::default(), vectorcraft_doc::Appearance::default_art()); + star.write_to_node(&mut node); + CustomShape::read(&node).unwrap_or_else(|| panic!("a shape")) + } + + /// A live star's stored entry holds a long corner list, and its pie angles still read back. + #[test] + fn a_live_star_with_many_corners_keeps_its_pie_angles() { + let back = round_trip(EllipseMode::Whole); + let CustomShape::Polygon { pie, radii, kinds, .. } = &back else { panic!("a polygon") }; + assert_eq!(*pie, (0.0, 90.0)); + assert_eq!(radii.len(), 2000); + assert_eq!(kinds.len(), 2000); + } + + /// A sliced star has no `LiveShape`, so its stored entry holds every corner and still reads back. + #[test] + fn a_sliced_star_with_many_corners_reads_back() { + let back = round_trip(EllipseMode::Slice); + let CustomShape::Polygon { pie, radii, arc_mode, .. } = &back else { panic!("a polygon") }; + assert_eq!(*pie, (0.0, 90.0)); + assert_eq!(*arc_mode, EllipseMode::Slice); + assert_eq!(radii.len(), 2000); + } + + /// The longest corner values a 1000-point star can hold still fit in the stored entry. + #[test] + fn the_longest_star_entry_fits_the_read_limit() { + let mut star = read_back(Some(0.5), 1000); + let CustomShape::Polygon { radius, radii, kinds, .. } = &mut star else { panic!("a polygon") }; + *radius = -f64::MAX; + *radii = vec![-1.2345678901234567e-300; 2000]; + *kinds = vec![CornerKind::InvertedRound; 2000]; + let len = serde_json::to_string(&star).map(|s| s.len()).unwrap_or(usize::MAX); + assert!(len <= MAX_STORED, "{len}"); + } +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 79e69f77f6..2ac3c90086 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -288,6 +288,10 @@ pub struct ToolContext<'a> { /// Selection & Anchor Display → Object Selection by Path Only: a click inside a filled path /// doesn't pick it, only one on its path does. pub path_only: bool, + /// Selection & Anchor Display → Select Inside Unfilled Shapes (off by default): a selection + /// tool click inside a closed path with no fill picks it where nothing else is hit, instead of + /// starting a marquee. + pub unfilled_interiors: bool, /// Type → Type Object Selection by Path Only: type is picked on its type path only (point /// type's baseline, area type's frame, type on a path's path), not anywhere in its bounds. pub type_path_only: bool, @@ -476,15 +480,16 @@ impl ToolContext<'_> { /// [`Self::hit_options`] for the selection tools (Selection, Direct Selection, Group /// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]), and - /// where nothing else is hit, an unfilled closed path is hit inside unless Object Selection by - /// Path Only is on ([`HitOptions::unfilled_interiors`]). + /// with Select Inside Unfilled Shapes on ([`Self::unfilled_interiors`]), an unfilled closed path + /// is hit inside where nothing else is hit, unless Object Selection by Path Only is on + /// ([`HitOptions::unfilled_interiors`]). /// Only for what a press or a hover selects: a double-click, loaded text or a guide's release /// acts on what is drawn and takes [`Self::hit_options`]. /// /// [`HitOptions::clip_outlines`]: vectorcraft_doc::hit::HitOptions::clip_outlines /// [`HitOptions::unfilled_interiors`]: vectorcraft_doc::hit::HitOptions::unfilled_interiors pub fn selection_hit_options(&self) -> vectorcraft_doc::hit::HitOptions { - vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..self.hit_options() } + vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: self.unfilled_interiors, ..self.hit_options() } } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 3707d4ee88..aa7fb8cc30 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1869,9 +1869,10 @@ fn the_centre_point_selects_and_moves_the_object_whole() { assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0)); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_)))); - // Without it, a press inside the unfilled square selects it (#9175). + // Without it and with Select Inside Unfilled Shapes on, a press inside the unfilled square + // selects it (#9175). let mut t = DirectSelectionTool::new(false); - let c = cx(&d, &none, &p); + let c = ToolContext { unfilled_interiors: true, ..cx(&d, &none, &p) }; assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index bee869a8e8..4c53d294bf 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -692,6 +692,7 @@ pub(crate) mod testutil { selection_tolerance: 3.0, anchor_size: 3, path_only: false, + unfilled_interiors: false, type_path_only: false, double_click_isolate: true, double_click_adds_anchor: false, diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1d7bd558e0..fe23341fb6 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -538,6 +538,7 @@ struct BehindKey { scope: Option, outline: bool, path_only: bool, + unfilled_interiors: bool, type_path_only: bool, skip_guides: bool, handles_multiple: bool, @@ -556,6 +557,7 @@ impl BehindKey { scope: cx.isolation, outline: opt.outline, path_only: opt.path_only, + unfilled_interiors: opt.unfilled_interiors, type_path_only: opt.type_path_only, skip_guides: opt.skip_guides, handles_multiple: cx.handles_multiple, diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 0ebda2c719..63f7e5c25f 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -3026,6 +3026,30 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() { assert!(matches!(t.overlays(&c).first(), Some(Overlay::SelectionMarquee { .. })), "a marquee"); } +/// A drag inside an unselected unfilled shape, away from its path, makes a marquee and leaves the +/// shape where it is by default; with Select Inside Unfilled Shapes on, the press selects the shape +/// and the drag moves it (#9175). +#[test] +fn a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked() { + let (d, id) = doc_with_live_rect(); + let none = Selection::default(); + let p = paint(); + let inside = Point::new(130.0, 130.0); + let c = cx(&d, &none, &p); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, inside.x, inside.y)).is_empty(), "nothing is selected"); + let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0)); + assert!(a.is_empty(), "nothing moves: {a:?}"); + assert!(matches!(t.overlays(&c).first(), Some(Overlay::SelectionMarquee { .. })), "a marquee"); + let c = ToolContext { unfilled_interiors: true, ..cx(&d, &none, &p) }; + let mut t = SelectionTool::default(); + let a = t.pointer(&c, &ev(PointerKind::Down, inside.x, inside.y)); + assert_eq!(a, vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0)); + assert!(a.iter().any(|a| *a == Action::Begin("Move".into())), "the shape moves: {a:?}"); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::SelectionMarquee { .. })), "no marquee"); +} + /// A Shift-press on a selected object's centre point moves the selection too, held to 45° steps, /// and a Shift-click there (no drag) takes the object out of the selection, as a Shift-press on /// the object itself does. diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs index 361430dcf5..82668516c7 100644 --- a/crates/tools/src/sidewidget.rs +++ b/crates/tools/src/sidewidget.rs @@ -6,6 +6,10 @@ //! `object.setLiveShape`'s `sides` in one undo step, and none when the count ends where it began. //! The Selection tool and the shape tools that show the box hit the widget, and the canvas draws it //! from the same geometry. +//! +//! A live star shows the same widget +//! (): +//! its drag sends `points`, from 3 to 20, with the same rule for a count past either end. use serde_json::json; use vectorcraft_doc::{Document, LiveShape, NodeId, NodeKind, OrientedBox, Selection}; @@ -27,35 +31,45 @@ pub const STEP_PX: f64 = 12.0; pub const MIN_SIDES: u32 = 3; /// The most sides a drag gives. pub const MAX_SIDES: u32 = 11; +/// The fewest points a drag gives a star. +pub const MIN_POINTS: u32 = 3; +/// The most points a drag gives a star. +pub const MAX_POINTS: u32 = 20; -/// The side widget of a selection that is exactly one editable live polygon. +/// The side widget of a selection that is exactly one editable live polygon or star. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SideWidget { pub id: NodeId, /// Center in document coordinates. pub at: Point, - /// The polygon's side count. + /// The polygon's side count, or the star's point count. pub sides: u32, + /// The shape is a star: the drag sets its points (3 to 20) instead of a polygon's sides. + pub star: bool, } impl SideWidget { /// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document - /// point). None unless the selection is one whole editable live polygon, with no anchors or - /// segments of it selected. + /// point). None unless the selection is one whole editable live polygon or star, with no + /// anchors or segments of it selected. pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { let [id] = selection.objects[..] else { return None }; if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !zoom.is_finite() || zoom <= 0.0 { return None; } let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None }; - let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None }; + let (sides, star) = match live.as_deref() { + Some(LiveShape::Polygon { sides, .. }) => (*sides, false), + Some(LiveShape::Star { points, .. }) => (*points, true), + _ => return None, + }; // After the kind: on a locked artboard it measures the art of the layer object holding `id`. if !doc.is_editable(id) { return None; } let r = bx.rect; let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y); - (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) + (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides, star }) } /// The widget the tool can drag (its bounding box and the shape widgets showing). @@ -82,15 +96,35 @@ pub fn over_widget(cx: &ToolContext, p: Point) -> bool { /// The side count a drag of `steps` (down positive) gives a polygon of `from` sides: within 3 to 11, /// and `from` itself while a polygon of more than 11 sides has not been dragged up. pub fn sides_after(from: u32, steps: i64) -> u32 { - let (min, max) = (i64::from(MIN_SIDES), i64::from(MAX_SIDES)); - let to = if from <= MAX_SIDES { - i64::from(from).saturating_add(steps) - } else if steps >= 0 { - return from; + count_after(from, steps, MIN_SIDES, MAX_SIDES) +} + +/// The point count a drag of `steps` (down positive) gives a star of `from` points: within 3 to 20, +/// and `from` itself while a star of more than 20 points has not been dragged up, or a star of +/// fewer than 3 has not been dragged down. +pub fn points_after(from: u32, steps: i64) -> u32 { + count_after(from, steps, MIN_POINTS, MAX_POINTS) +} + +/// A count a drag of `steps` gives from `from`, within `min` to `max`. A count past `max` stays +/// until the drag goes up a step, which gives `max`; one below `min` stays until it goes down a +/// step, which gives `min`. +fn count_after(from: u32, steps: i64, min: u32, max: u32) -> u32 { + let (lo, hi) = (i64::from(min), i64::from(max)); + let to = if from > max { + if steps >= 0 { + return from; + } + (hi + 1).saturating_add(steps) + } else if from < min { + if steps <= 0 { + return from; + } + (lo - 1).saturating_add(steps) } else { - (max + 1).saturating_add(steps) + i64::from(from).saturating_add(steps) }; - to.clamp(min, max) as u32 + to.clamp(lo, hi) as u32 } /// Dragging the side widget. @@ -139,7 +173,7 @@ impl SideDrag { return vec![]; } // The cast saturates: an infinite count of steps becomes i64::MAX or i64::MIN. - let sides = sides_after(self.widget.sides, steps as i64); + let sides = if self.widget.star { points_after(self.widget.sides, steps as i64) } else { sides_after(self.widget.sides, steps as i64) }; if sides == self.sides { return vec![]; } @@ -149,7 +183,8 @@ impl SideDrag { out.push(Action::Begin("Live Shape".into())); } self.sides = sides; - out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, "sides": sides }))); + let key = if self.widget.star { "points" } else { "sides" }; + out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, key: sides }))); out } @@ -172,7 +207,8 @@ impl SideDrag { if !self.moved || !cx.measurement_labels { return vec![]; } - vec![Overlay::Measure { p: self.at, text: format!("Sides: {}", self.sides) }] + let label = if self.widget.star { "Points" } else { "Sides" }; + vec![Overlay::Measure { p: self.at, text: format!("{label}: {}", self.sides) }] } } @@ -188,7 +224,17 @@ mod tests { /// A document holding a live polygon of `sides` sides and radius 100 placed by `xf`, and a /// selection of it. fn polygon_doc(sides: u32, xf: Affine) -> (Document, NodeId, Selection) { - let live = LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + shape_doc(LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }) + } + + /// A document holding a live star of `points` points, radii 100 and 50, placed by `xf`, and a + /// selection of it. + fn star_doc(points: u32, xf: Affine) -> (Document, NodeId, Selection) { + shape_doc(LiveShape::Star { r1: 100.0, r2: 50.0, points, xf, radii: vec![], kinds: vec![], radii_relative: false }) + } + + /// A document holding the live shape `live`, and a selection of it. + fn shape_doc(live: LiveShape) -> (Document, NodeId, Selection) { let mut d = Document::new(800.0, 800.0); let l = d.layers[0].id; let id = d.alloc_id(); @@ -226,6 +272,42 @@ mod tests { assert_eq!(sides_after(1000, -100), 3); } + #[test] + fn a_star_s_counts_stay_within_three_and_twenty() { + assert_eq!(points_after(5, 1), 6); + assert_eq!(points_after(5, 100), 20); + assert_eq!(points_after(5, -100), 3); + assert_eq!(points_after(20, i64::MAX), 20); + // Over 20: unchanged until the drag goes up, which gives 20. + assert_eq!(points_after(40, 3), 40); + assert_eq!(points_after(40, -1), 20); + // Under 3 (a two-point star): unchanged until the drag goes down, which gives 3. + assert_eq!(points_after(2, 0), 2); + assert_eq!(points_after(2, -4), 2); + assert_eq!(points_after(2, 1), 3); + assert_eq!(points_after(2, 2), 4); + assert_eq!(points_after(2, i64::MIN), 2); + } + + /// A live star shows the widget, and dragging it down a step gives the star a point, in one + /// undo step, with the count beside the pointer. + #[test] + fn dragging_a_star_s_widget_down_adds_a_point() { + let (d, id, s) = star_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).expect("a widget on a live star"); + assert_eq!((w.id, w.sides, w.star), (id, 5, true)); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let to = w.at + vectorcraft_geom::Vec2::new(0.0, STEP_PX + 1.0); + let out = t.pointer(&c, &ev(PointerKind::Drag, to)); + assert_eq!(out[0], Action::Begin("Live Shape".into())); + assert!(matches!(&out[1], Action::Preview(cmd, v) if cmd == "object.setLiveShape" && *v == json!({ "id": id.0, "points": 6 })), "{out:?}"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Points: 6"))); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, to)), vec![Action::Commit]); + } + #[test] fn the_longest_drags_stay_within_three_and_eleven() { assert_eq!(sides_after(5, i64::MAX), 11); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9197a3be31..fe411e7c59 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -97,6 +97,8 @@ web-time = "1" rustix = { workspace = true, features = ["std", "process"] } [dev-dependencies] +# DWG files for the DXF Import Options tests, written from DXF by craft-dwg. +craft-dwg = { workspace = true } # `Fixture` and the stories sit behind craft-ui's `testing` feature. craft = { workspace = true, features = ["ui-testing"] } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index ea78593400..df763b4425 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,7 +1,8 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of //! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, Randomize -//! Opacity, Sort Objects and Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command -//! on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. +//! Opacity, Sort Objects, Add Artboard Guides and Mark Bounds of Each, which preview on the canvas and run their +//! `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active +//! view to the selection. use std::borrow::Cow; @@ -29,9 +30,10 @@ const MATCH: &str = "addon.arrange.match"; const ROWS: &str = "addon.arrange.groupRows"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const GUIDES: &str = "addon.arrange.artboardGuides"; const MARKS: &str = "addon.arrange.markBounds"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 9] = [ +const DIALOGS: [(&str, &str); 10] = [ (GRID, "Arrange in Grid"), (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), @@ -40,8 +42,11 @@ const DIALOGS: [(&str, &str); 9] = [ (ROWS, "Group by Row"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (GUIDES, "Add Artboard Guides"), (MARKS, "Mark Bounds of Each"), ]; +/// The artboards Add Artboard Guides puts guides around: `all` false or true. +const SCOPES: [(&str, &str); 2] = [("active", "Active Artboard"), ("all", "All Artboards")]; /// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights. const MARK_LENGTHS: std::ops::RangeInclusive = 0.001..=1e6; const WEIGHTS: std::ops::RangeInclusive = 0.01..=1000.0; @@ -77,6 +82,7 @@ pub fn menu() -> Vec { c("Group by Row…", ROWS), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Add Artboard Guides…", GUIDES), c("Mark Bounds of Each…", MARKS), Sep, cp("Zoom to Selection", ZOOM, json!({})), @@ -91,6 +97,7 @@ static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: No static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None }; static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. @@ -201,6 +208,11 @@ fn sort_rows() -> Vec { ] } +fn guides_rows(lengths: LengthUnits) -> Vec { + // More than 0 outside the artboard, less than 0 inside it. + vec![length("offset", "Offset:", 0.0, GAPS, lengths), choice("scope", "Artboards:", &SCOPES, "active")] +} + fn marks_rows(lengths: LengthUnits) -> Vec { let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")]; let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")]; @@ -258,10 +270,39 @@ fn sort_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&sort_rows(), fields)) } +/// Add Artboard Guides' offset, and `all` for All Artboards, else the artboard active when the dialog opened. +fn guides_params(fields: &DialogFields) -> Value { + let mut params = form::json_of(&guides_rows(POINTS), fields); + let all = fields.text("scope") == Some("all"); + params.remove("scope"); + if all { + params.remove("artboardId"); + } + params.insert("all".into(), json!(all)); + Value::Object(params) +} + +pub(super) fn resolve_guides_artboard(app: &VectorcraftApp, params: &mut Value) -> Result<(), String> { + if params["all"] == true { + return Ok(()); + } + let id = params["artboardId"].as_u64(); + let index = app.session.active().and_then(|st| st.doc.artboards.iter().position(|a| Some(u64::from(a.id)) == id)); + let Some(index) = index else { return Err("The artboard no longer exists.".into()) }; + if let Some(params) = params.as_object_mut() { + params.remove("artboardId"); + params.insert("artboard".into(), json!(index)); + } + Ok(()) +} + /// Opens the dialog of command `id` on the active document; `None` for another command and without a document. pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; let st = app.session.active()?; + if command == GUIDES && st.doc.artboards.is_empty() { + return Some(Err("the document has no artboards".into())); + } let strokes = app.session.prefs.scale_strokes; let key = st.selection.key.is_some(); let lengths = general_lengths(app); @@ -295,6 +336,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option ( + guides_rows(lengths), + json!({ + "offset": 0, "scope": "active", + "artboardId": st.doc.artboards.get(crate::panels::artboards::selected(app, st.doc.artboards.len())).map(|a| a.id), + }), + ), MARKS => (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { @@ -328,6 +376,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), + GUIDES => super::dialogs::open(app, &GUIDES_SPEC, fields, move |fields| dialog(GUIDES, guides_rows(lengths)).values(Bind::bound(fields))), MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 6c68fa385b..2e9beac838 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -164,6 +164,182 @@ fn real_opacity_edits_drive_validation_confirmation_and_cancel() { assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); } +/// The bounds of the guide paths on the top-level layer Artboard Guides, from the back. +fn artboard_guides(app: &VectorcraftApp) -> Vec { + let d = &app.session.doc().unwrap().doc; + let layer = d.layers.iter().find(|l| l.name.as_deref() == Some("Artboard Guides")); + let guides = layer.and_then(|l| l.children()).into_iter().flatten(); + guides.filter(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: true, .. })).map(|n| n.geometric_bounds().unwrap()).collect() +} + +#[test] +fn real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step() { + for cancel in [true, false] { + let (app, _, _) = app(); + let board = app.session.doc().unwrap().doc.artboards[0].rect; + let (original, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Add Artboard Guides…"); + panel.frame(); + type_number(&mut panel, "Offset", "-12"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("offset")), Some(-12.0)); + assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)], "the preview insets the active artboard"); + panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX); + panel.frame(); + assert!(artboard_guides(&panel.app()).is_empty(), "no guide with Preview off"); + panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX); + panel.frame(); + assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)]); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo, "a preview makes no step"); + panel.click(if cancel { "Cancel" } else { "OK" }); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + let state = app.session.doc().unwrap(); + if cancel { + assert!(*state.doc == *original, "Cancel leaves the document as it was"); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(artboard_guides(&app), vec![board.inflate(-12.0, -12.0)]); + assert_eq!(state.history.undo.len(), undo + 1, "OK adds the guide as one undo step"); + } + } +} + +#[test] +fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + let boards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| (f.number("offset"), f.text("scope").map(str::to_owned))), (Some(0.0), Some("active".to_owned()))); + host::set(&app, id, "offset", json!(18)); + host::set(&app, id, "scope", json!("all")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), boards.iter().map(|b| b.inflate(18.0, 18.0)).collect::>()); + // The second artboard is 100 pt tall: an inset of 50 leaves it nothing, so OK adds nothing. + let (before, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len()); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "offset", json!(-50)); + host::set(&app, id, "scope", json!("all")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(*app.session.doc().unwrap().doc == *before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn add_artboard_guides_does_not_open_without_artboards() { + let (mut app, _, _) = app(); + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).artboards.clear(); + let opened = crate::addons::dialogs::open_from_menu(&mut app, "addon.arrange.artboardGuides"); + assert!(matches!(opened, Some(Err(_))), "{opened:?}"); + assert!(!app.any_dialog_open()); +} + +#[test] +fn add_artboard_guides_keeps_the_opening_artboard_after_reordering() { + for preview in [false, true] { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + let board = app.session.doc().unwrap().doc.artboards[0].rect; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(preview)); + if preview { + host::frame(&mut app); + app.session.cancel_interaction().unwrap(); + } + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + let n = steps(&app); + if preview { + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![board]); + assert_eq!(steps(&app), n); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![board]); + assert_eq!(steps(&app), n + 1); + } +} + +#[test] +fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() { + for preview in [false, true] { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(preview)); + if preview { + host::frame(&mut app); + app.session.cancel_interaction().unwrap(); + } + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let (before, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + if preview { + host::frame(&mut app); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(steps(&app), n); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(steps(&app), n); + assert_eq!(app.ui.status, "The artboard no longer exists."); + } +} + +#[test] +fn artboard_guides_menu_dialog_is_available_without_a_selection() { + let (mut app, _, _) = app(); + app.run("select.none", json!({})).unwrap(); + assert!(menus::enabled(&app, "ui.menuDialog")); + let guides = json!({"command": "addon.arrange.artboardGuides"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &guides).map(|s| s.0), Some(true)); + let transform = json!({"command": "object.move"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(false)); + let grid = json!({"command": "addon.arrange.grid"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(false)); + app.run("select.all", json!({})).unwrap(); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(true)); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(true)); + app.run("select.none", json!({})).unwrap(); + app.run("ui.menuDialog", guides).unwrap(); + let id = host::dialog_id(&app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![app.session.doc().unwrap().doc.artboards[0].rect]); +} + +#[test] +fn add_artboard_guides_uses_the_artboard_the_view_shows() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + let second = app.session.doc().unwrap().doc.artboards[1].rect; + // The view moves to the second artboard without a command that tells the document, which + // still names the first. + app.view_mut().unwrap().artboard = 1; + let first = app.session.doc().unwrap().doc.artboards[0].id; + app.session.active_mut().unwrap().active_artboard = Some(first); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "offset", json!(6)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "the preview"); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "OK"); +} + /// The objects of the first layer, from the back. fn stacking(panel: &Harness) -> Vec { panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index ecbcf6856d..02f9745b5d 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -29,6 +29,16 @@ pub(crate) struct Spec { pub found: Option, } +impl Spec { + fn params(&self, app: &VectorcraftApp, fields: &DialogFields) -> Result { + let mut params = (self.params)(fields); + if self.command == "addon.arrange.artboardGuides" { + super::arrange::resolve_guides_artboard(app, &mut params)?; + } + Ok(params) + } +} + /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. #[derive(Default)] pub(crate) struct AddonDialogs { @@ -141,11 +151,19 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.preview = LivePreview::default(); app.addon_dialogs.preview_error = None; } - let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); + let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), spec.params(app, d.fields())))); if on_document && let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); - let answer = preview.run(app, *previewing, label, spec.command, params); + let answer = match params { + Ok(params) => preview.run(app, *previewing, label, spec.command, params), + Err(error) => { + preview.cancel(app); + preview = LivePreview::default(); + app.status(error.clone()); + Some(Err(error.clone())) + } + }; app.addon_dialogs.preview = preview; if spec.command == super::select::points_only::COMMAND { match &answer { @@ -172,11 +190,13 @@ fn pump_commit(app: &mut VectorcraftApp) { } else if !on_document { app.status("The add-on settings apply only to the drawing where the dialog opened."); } else { - let params = (spec.params)(&result.fields); - let answer = if spec.command == super::select::points_only::COMMAND { - preview.commit_selection(app, spec.command, params) - } else { - preview.commit(app, spec.command, params) + let answer = match spec.params(app, &result.fields) { + Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params), + Ok(params) => preview.commit(app, spec.command, params), + Err(error) => { + preview.cancel(app); + Err(error) + } }; if let Err(error) = answer { app.status(error); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d4c7c410ed..3a9142ba89 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -180,6 +180,8 @@ impl VectorcraftApp { multi_color: None, global_edit_count: None, shape_angle: None, + radius_corners: None, + selected_rectangles: None, trace_presets: None, trace_target: None, attributes_info: None, @@ -640,6 +642,7 @@ impl VectorcraftApp { crate::addons::select::link_status::refresh(self, now); if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() + || !self.opening.converting.is_empty() || plugin_runs::any_pending(self) || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() @@ -862,6 +865,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/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 818863408d..f7fb6b2ba1 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -124,10 +124,11 @@ impl VectorcraftApp { } } - /// Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align, - /// Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols - /// panel act on the active artboard, the view's, which the app adds to command `id`'s `params` as - /// `artboard`. A batch passes it on to those steps. While the Artboard tool has several artboards + /// Add Artboard Guides (Object › Plug-ins › Arrange Tools), Paste in place, in front and in + /// back (#693), Select › All on Active Artboard (#1006), and Align, Distribute Objects and + /// Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols panel act on the + /// active artboard, the view's, which the app adds to command `id`'s `params` as `artboard`. A + /// batch passes it on to those steps. While the Artboard tool has several artboards /// selected, the paste commands get those as `artboards` instead, and paste a copy on each; in a /// document without artboards they get neither. fn add_active_artboard(&self, id: &str, params: &mut Value) { diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index d2809d5846..d7d333402a 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -160,6 +160,12 @@ pub struct CanvasCache { pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>, /// The selected live shape's angle, for (document uid, revision, kind of shape). pub shape_angle: Option, + /// The corners a live shape's Corner Radius field sets, as one hash, for (document uid, + /// File › Revert count, revision). + pub(crate) radius_corners: Option<((u64, u64, u64), u64)>, + /// The selected live rectangles the per-corner fields set, as one hash, for (document uid, + /// File › Revert count, revision). + pub(crate) selected_rectangles: Option<((u64, u64, u64), u64)>, /// The Image Trace presets, for the session's preset revision. pub(crate) trace_presets: Option<(u64, Arc)>, /// What the Image Trace panel traces, for (document uid, revision). @@ -308,6 +314,13 @@ pub struct SymbolInstances { /// One of them has a scale, rotation or shear that Reset Transformation would change; measured /// on the first read. pub transformed: Option, + /// The names of the symbols they are instances of, each once and sorted; found on the first + /// read. + pub names: Option>, + /// The symbol the selected objects share when every one is a symbol instance, blank when they + /// are instances of different symbols, and `None` inside when nothing is selected or one is not + /// an instance; found on the first read. + pub shared: Option>, } /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 0d70e1a78a..11a80a1449 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -218,12 +218,14 @@ pub(super) fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option Option { + let unfilled_interiors = app.session.prefs.select_inside_unfilled_shapes; hit_with(app, p, zoom, |doc, p, opt| { - vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..opt }) + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors, ..opt }) }) } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 56ecf1b24c..ef40ffefe4 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -32,7 +32,7 @@ const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0); /// on the canvas of `space`. The extras lie under the tool's own marks. pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, overlays: &[Overlay], extra: &[Overlay]) { let rect = space.view.rect; - let options = super::selection::path_options(&app.session.prefs); + let options = super::selection::path_options(&app.session.prefs, app.session.tool_id()); let quiet = tool_adapter::in_gesture(app, ui.ctx()) || tool_adapter::view_tool_held(app); let lists = [extra, overlays]; // Only the overlays that are controls get a child `Ui`: a list of 10,000 path marks makes none. 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/selection.rs b/crates/ui-egui/src/canvas/selection.rs index c2d53fcf97..861eda0790 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -30,8 +30,11 @@ use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). -/// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points. +/// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points, under a tool that edits +/// anchors ([`vectorcraft_tools::catalog::edits_anchors`]). const ANCHOR_AT_DEFAULT_SIZE: f32 = 5.0; +/// How many points smaller the anchor squares are under a tool that does not edit anchors, such as the Selection tool. +const SELECTING_ANCHOR_SHRINK: f32 = 1.0; /// The default of Selection & Anchor Display › Size. const DEFAULT_SIZE: u32 = 3; /// How many points bigger than the other selected anchors the key anchor's square is drawn. @@ -129,12 +132,14 @@ pub(super) fn outline_revision(paths: &[BezPath], key: Option<&BezPath>, extra: hasher.finish() } -/// The Path Options the anchors layer draws with: Selection & Anchor Display › Size (1–7, one point per step) and -/// Handles. One builder, so every overlay reads the preference the same way. +/// The Path Options the anchors layer draws with under `tool`: Selection & Anchor Display › Size (1–7, one point per +/// step) and Handles. Anchors are [`SELECTING_ANCHOR_SHRINK`] smaller under a tool that does not edit anchors. One +/// builder, so every overlay reads the preference the same way. #[allow(clippy::field_reassign_with_default)] // `PathOptionsSettings` is non-exhaustive: no struct literal outside its crate -pub(super) fn path_options(prefs: &Prefs) -> PathOptionsSettings { +pub(super) fn path_options(prefs: &Prefs, tool: &str) -> PathOptionsSettings { let mut options = PathOptionsSettings::default(); - options.anchor_size = Some(ANCHOR_AT_DEFAULT_SIZE + grow(prefs)); + let shrink = if vectorcraft_tools::catalog::edits_anchors(tool) { 0.0 } else { SELECTING_ANCHOR_SHRINK }; + options.anchor_size = Some(ANCHOR_AT_DEFAULT_SIZE - shrink + grow(prefs)); options.handles = match prefs.handle_style.as_str() { "hollow" => HandleStyle::Hollow, "large" => HandleStyle::Large, @@ -282,7 +287,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin shown: if curvature { AnchorsShown::Curvature } else { AnchorsShown::All }, handles: if prefs.show_handles_multiple_anchors { HandlesShown::Selected } else { HandlesShown::OneAnchor }, segment_mark: SegmentMark::Line, - options: path_options(prefs), + options: path_options(prefs, tool), }; if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 42adf76890..65ca87aff3 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -119,10 +119,11 @@ fn no_stale_marks_after_a_change(tool: &str) { // The display preferences. app.session.active_mut().unwrap().selection.segments.clear(); + let at_default = marks(&app).options.anchor_size.unwrap(); app.session.prefs.anchor_size = 6; app.session.prefs.handle_style = "hollow".into(); let options = marks(&app).options; - assert_eq!((options.anchor_size, options.handles), (Some(8.0), HandleStyle::Hollow)); + assert_eq!((options.anchor_size, options.handles), (Some(at_default + 3.0), HandleStyle::Hollow), "Size 6 is three points up"); app.session.prefs.show_handles_multiple_anchors = false; assert_eq!(marks(&app).handles, HandlesShown::OneAnchor); app.session.prefs.show_handles_multiple_anchors = true; @@ -875,7 +876,8 @@ fn curvature_marks_existing_paths_as_circles_and_leaves_a_drafts_points_to_the_t #[test] fn anchor_size_scales_anchors_and_handles() { - let options = |size: u32, style: &str| path_options(&Prefs { anchor_size: size, handle_style: style.into(), ..Default::default() }); + let options = + |size: u32, style: &str| path_options(&Prefs { anchor_size: size, handle_style: style.into(), ..Default::default() }, "directSelection"); assert_eq!(options(3, "solid").anchor_size, Some(ANCHOR_AT_DEFAULT_SIZE)); let large = options(7, "large"); assert_eq!((large.anchor_size, large.handles), (Some(ANCHOR_AT_DEFAULT_SIZE + 4.0), HandleStyle::Large)); @@ -883,6 +885,25 @@ fn anchor_size_scales_anchors_and_handles() { assert_eq!(options(3, "solid").handles, HandleStyle::Solid); } +/// Anchors are a point smaller under the selection tools that move objects than under the tools that edit anchors, +/// at every Size. +#[test] +fn anchors_are_smaller_under_the_selection_tool_than_under_the_tools_that_edit_them() { + let (mut app, _) = scene(); + let mut size_under = |tool: &str| { + app.select_tool(tool); + assert!(!shown_paths(&marks(&app)).is_empty(), "{tool} shows the selection's anchors"); + marks(&app).options.anchor_size.unwrap() + }; + let (selection, group, direct, pen) = (size_under("selection"), size_under("groupSelection"), size_under("directSelection"), size_under("pen")); + assert_eq!(direct, ANCHOR_AT_DEFAULT_SIZE); + assert_eq!(pen, direct, "the Pen tool draws anchors as Direct Selection does"); + assert_eq!(selection, direct - SELECTING_ANCHOR_SHRINK); + assert_eq!(group, selection, "Group Selection moves objects as the Selection tool does"); + let largest = |tool: &str| path_options(&Prefs { anchor_size: 7, ..Default::default() }, tool).anchor_size.unwrap(); + assert_eq!(largest("directSelection") - largest("selection"), SELECTING_ANCHOR_SHRINK, "Size grows both alike"); +} + /// The revision is of the drawn outline: the same paths and colour give one value, other paths or another colour do not. #[test] fn the_outline_revision_follows_what_is_drawn() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e7fec25534..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]); @@ -2086,8 +2087,9 @@ fn dragging_with_raster_effects() { } /// A tool's drag on the canvas renders with `dragging` (#2558). At 3200% a rectangle with -/// Texturizer covers more than the raster budget, so no raster is kept for it, and each frame -/// of a Selection tool drag draws its filtered content at the drag's lower resolution. The +/// Texturizer covers more than the raster budget, so its raster is cropped to the view: the first +/// frame of a Selection tool drag filters its content at the drag's lower resolution, and the +/// next moves that raster with the rectangle. The /// frame after the drag draws what a fresh renderer draws. A dialog's preview, an interaction /// without a drag, renders without `dragging` and draws the same. #[test] @@ -2139,7 +2141,9 @@ fn a_drag_at_a_lower_resolution(fits_frame: bool) { for step in [1.0, 2.0] { let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}"); - assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}"); + // Cropped to the view, the first frame's raster moves with the rectangle on the second. + let filtered = usize::from(fits_frame || step == 1.0); + assert_eq!(app.canvas.renderer.stats.previewed, filtered, "the filtered content, step {step}"); if fits_frame { assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster"); assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch"); @@ -2545,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 }) @@ -2687,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 }) @@ -2735,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 }) @@ -3171,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. @@ -5958,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, @@ -5982,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, @@ -6005,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, @@ -6028,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, @@ -6098,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(), @@ -6164,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"); } @@ -6428,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}"); } } } @@ -6491,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"); @@ -6962,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/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 985646a065..0c02c32828 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -127,10 +127,11 @@ fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(picked) = crate::panels::picked_corners(app) else { return }; let label = tl!("Corner Radius:"); let lengths = crate::canvas::general_lengths(app); + let target = crate::panels::corner_target(app, &picked.corners); let mut typed = None; group(ui, rank::GROUP, |ui| { crate::panels::corners_link(app, ui); - let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui); + let number = NumberField::length(label, Bind::given(picked.radius), lengths).edit_target(target).show(ui); typed = number.edit.events.committed().copied().flatten().or(typed); }); if let Some(radius) = typed { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index fb3032d235..b7d7f0b4dd 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3194,6 +3194,64 @@ fn the_control_bar_opacity_drops_an_unfinished_value_when_the_selection_changes( assert_eq!((opacity(&bar, &a), opacity(&bar, &b)), (0.5, 0.01), "the typing gives the other object 1%, not 20+1"); } +/// File › Revert drops an unfinished Opacity expression in the Control bar, though the reverted document has the same +/// object, with the same opacity, selected again before the next frame. +#[test] +fn the_control_bar_opacity_drops_an_unfinished_value_on_file_revert() { + use egui::{Key, Modifiers}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 20, "y": 50, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("transparency.set", json!({"ids": [a], "opacity": 50})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("control-bar-opacity-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("Opacity.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the rectangle as saved. + app.run("shape.rectangle", json!({"x": 200, "y": 50, "width": 40, "height": 40})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 300.0)).frame(); + bar.click_role("Opacity:", Role::SPIN_BUTTON); + bar.key(Key::A, Modifiers::COMMAND); + bar.type_text("20+"); + bar.app().run("file.revert", json!({"confirmed": true})).unwrap(); + bar.app().run("select.set", json!({"ids": [a]})).unwrap(); + bar.type_text("1"); + bar.key(Key::Enter, Modifiers::NONE); + let opacity = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a.as_u64().unwrap())).unwrap().opacity; + assert_eq!(opacity, 0.01, "Revert drops the unfinished value: 1%, not 20+1"); +} + +/// A radius typed into the Control bar's Corner Radius field and not yet entered is dropped when +/// another corner with the same radius is Direct-Selected: Enter sets only what was typed after. +#[test] +fn the_control_bar_corner_radius_drops_an_unfinished_value_when_the_corners_change() { + use egui::{Key, Modifiers}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 400.0)).frame(); + bar.click_role("Corner Radius:", Role::SPIN_BUTTON); + bar.key(Key::A, Modifiers::COMMAND); + bar.type_text("3+"); + bar.app().run("select.anchors", json!({"id": id, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + bar.frame(); + assert_eq!(bar.value_role("Corner Radius:", Role::SPIN_BUTTON).as_deref(), Some("0 pt"), "the field shows the new corner's radius"); + bar.type_text("1"); + bar.key(Key::Enter, Modifiers::NONE); + let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + assert_eq!((0..4).map(|k| lc.radius(k)).collect::>(), [0.0, 1.0, 0.0, 0.0], "the second corner takes 1 pt, not 3+1"); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A 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/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6be16732f6..f385161dda 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -1188,4 +1188,89 @@ mod tests { assert!(lengths("select.object.hairlineSlivers").contains(&"width")); assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE)); } + + /// The dialogs `ui.inspect` lists, by id and key. + fn inspected_kinds(app: &VectorcraftApp) -> Vec { + let dialogs = app.dialogs().unwrap().with(|host| craft::automation::dialogs::inspect(host)); + dialogs.as_array().unwrap().iter().map(|d| json!([d["id"], d["key"]])).collect() + } + + /// `ui.paramDialog` without a command it can open, or with a label or params of the wrong type, is an error that + /// opens no dialog and leaves the dialog already open in place. + #[test] + fn param_dialog_refuses_a_missing_empty_or_unknown_command() { + let mut app = windowed(); + let refused = [ + (json!({}), "missing `command`"), + (json!({"command": null, "params": {}}), "missing `command`"), + (json!({"command": "", "params": {}}), "`command` must name a command"), + (json!({"command": 5, "params": {}}), "`command` must be a string"), + (json!({"command": "no.such", "params": {}}), "unknown command `no.such`"), + (json!({"command": "gradient.presets.save", "label": 7, "params": {"name": "a"}}), "`label` must be a string"), + (json!({"command": "gradient.presets.save", "params": ["a"]}), "`params` must be an object"), + (json!({"command": "edit.findReplace", "params": "a"}), "`params` must be an object"), + ]; + for (params, want) in &refused { + let e = app.run("ui.paramDialog", params.clone()).unwrap_err(); + assert!(e.contains(want), "{params}: {e}"); + assert!(app.command_dialog.open.is_none(), "{params}: no dialog opens"); + assert_eq!(inspected_kinds(&app), Vec::::new(), "{params}: ui.inspect lists no dialog"); + } + app.run("ui.paramDialog", json!({"command": "gradient.presets.save", "label": "Gradient Preset", "params": {"name": "a"}})).unwrap(); + pump(&mut app); + let (id, kinds) = (id_of(&app), inspected_kinds(&app)); + // Which opening of the dialog shows: the host numbers every open, so a dialog opened again has a new number. + let shown_serial = |app: &VectorcraftApp, id: DialogId| app.dialogs().unwrap().with(|host| host.open_serial(id)); + let serial = shown_serial(&app, id); + assert_eq!(kinds.len(), 1, "{kinds:?}"); + assert!(serial.is_some()); + for (params, want) in &refused { + let e = app.run("ui.paramDialog", params.clone()).unwrap_err(); + assert!(e.contains(want), "{params}: {e}"); + assert_eq!(id_of(&app), id, "{params}: the open dialog stays"); + assert_eq!(shown_serial(&app, id), serial, "{params}: the same opening of the dialog stays"); + assert_eq!(inspected_kinds(&app), kinds, "{params}: ui.inspect lists the same dialog"); + } + } + + /// `ui.paramDialog` on the command of a plug-in still loading in the background waits for the plug-in to install and + /// opens its dialog, as running the command waits for it. + #[test] + fn param_dialog_waits_for_a_plug_in_still_loading() { + use vectorcraft_plugins::wat as tpl; + let id = "test.ui.paramdialogloading"; + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-param-dialog-loading-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","commands":[{{"id":"look","label":"Look"}}]}}"#); + std::fs::write(dir.join(format!("{id}.wasm")), wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let mut app = windowed(); + app.session.load_plugins_in_background(true); + app.session.attach_plugin_store(dir.clone()); + let command = format!("plugin.{id}.look"); + let loading = app.session.plugins_loading(); + let before = vectorcraft_engine::find_command(&command).is_some(); + let opened = app.run("ui.paramDialog", json!({"command": command, "params": {}})); + let (after, shown) = (vectorcraft_engine::find_command(&command).is_some(), app.command_dialog.open.is_some()); + vectorcraft_plugins::registry::remove(id); + let _ = std::fs::remove_dir_all(&dir); + assert!(loading, "the store loads in the background"); + assert!(!before, "the plug-in's command is not registered while it loads"); + opened.unwrap(); + assert!(after, "the plug-in installed before the dialog opened"); + assert!(shown, "the plug-in's dialog opens"); + } + + /// `tool.options` without a tool, or with one that is not a string, is an error that names the parameter. + #[test] + fn tool_options_refuses_a_missing_or_wrongly_typed_tool() { + let mut app = windowed(); + for (params, want) in + [(json!({}), "missing `tool`"), (json!({"tool": null}), "missing `tool`"), (json!({"tool": 3}), "`tool` must be a string")] + { + let e = app.run("tool.options", params.clone()).unwrap_err(); + assert!(e.contains(want), "{params}: {e}"); + assert_eq!(inspected_kinds(&app), Vec::::new(), "{params}: ui.inspect lists no dialog"); + } + } } 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/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 29b5962d3e..f3a6bc366a 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -311,7 +311,7 @@ mod tests { set(&app, "radius", json!(5)); confirm(&mut app); let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone(); - assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(&**l, LiveShape::Star { radii, .. } if !radii.is_empty()))); assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0)); } diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 59d5dddca0..a01076a838 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -1,4 +1,4 @@ -//! DXF Import Options: opening or placing a DXF drawing asks which layout to import (model space +//! DXF Import Options: opening or placing a DXF or DWG drawing asks which layout to import (model space //! or a paper layout, previewed), its scale (fitted to the artboard, or 1 unit of the art = N //! drawing units: by default the drawing at 1:1 in its own unit), whether lineweights scale with //! it, whether it is centred, and whether its layers merge into one. @@ -77,6 +77,18 @@ struct Source { name: String, path: Option, file: Arc, + /// What a DWG drawing converted off the UI thread brings. + converted: Option, +} + +/// A DWG drawing converted off the UI thread ([`converted`]). +pub(crate) struct Converted { + /// Its conversion, kept while the dialog is open, and for a place until the place's read is + /// done ([`crate::placing::Placing::keep_next`]), so that its previews, its OK and that read + /// read the drawing without converting it again. + held: vectorcraft_cad::dwg::Held, + /// Where it is placed, taken when Place started; `None` when it opens. + placement: Option, } /// The DXF Import Options dialog: the layout preview and what the drawing declares on the left, the @@ -320,13 +332,97 @@ impl HoldsOk for DxfImportDialog { } } +/// Is `ext` the extension of a drawing this dialog opens (DXF, or DWG converted to DXF)? +pub(crate) fn is_drawing_ext(ext: &str) -> bool { + matches!(ext, "dxf" | "dwg") +} + /// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they -/// are a DXF drawing; false when they aren't (or can't be read: the loader then says why). +/// are a DXF or DWG drawing; false when they aren't (or can't be read: the loader then says why). pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { - if fileio::detect(name, bytes).is_none_or(|f| f.id != "dxf") { + if fileio::detect(name, bytes).is_none_or(|f| !is_drawing_ext(f.id)) { return false; } let Ok(info) = vectorcraft_cad::info(bytes) else { return false }; + show(app, name, bytes, path, place, &info, None) +} + +/// [`offer`] for a file the user opens or places where files are read off the UI thread: a DWG +/// drawing is converted on a job of its own ([`crate::opening::convert_drawing`]) and its dialog +/// opens once that is done ([`converted`]) → true; false when `bytes` aren't a DWG drawing. +pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { + if !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| f.id != "dwg") { + return false; + } + crate::opening::convert_drawing(app, name, bytes.to_vec(), path, place.cloned()); + true +} + +/// [`offer_place`] for a file the user places where files are read off the UI thread: a DWG +/// drawing is converted first ([`convert_in_background`]) → true; false when `p` names no DWG +/// drawing. Place's checks run first, as for other files read for Place: a bad param, or a +/// selection that `replace` can't swap, is reported in the status bar at once and nothing is +/// converted (true). +pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool { + let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); + if p.get("dxf").is_some() || named.as_deref() != Some("dwg") { + return false; + } + let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dwg") else { return false }; + if !vectorcraft_cad::is_dwg(&bytes) { + return false; + } + if p.get("replace").and_then(Value::as_bool) == Some(true) { + // The edit the tool computes on another thread comes first: the object Replace swaps is the + // one selected after it. + let r = app.session.finish_tool_edit(); + crate::canvas::apply_requests(app, r); + } + if let Err(e) = app.session.prepare_place(p) { + app.status(e.to_string()); + return true; + } + convert_in_background(app, &name, &bytes, path, Some(p)) +} + +/// A DWG drawing converted off the UI thread ([`convert_in_background`]): its dialog opens, to +/// place it with the `file.place` params `place` where `placement` says, or else to open it (it +/// then goes on the recent files); a drawing that can't be read is reported. +pub(crate) fn converted( + app: &mut VectorcraftApp, + name: &str, + conversion: crate::opening::Conversion, + path: Option, + place: Option<&Value>, + placement: Option, +) { + let (bytes, info) = conversion; + match info { + Ok((info, held)) => { + let opens = place.is_none(); + if show(app, name, &bytes, path.clone(), place, &info, Some(Converted { held, placement })) + && opens + && let Some(path) = &path + { + io::note_recent(app, path); + } + } + Err(e) if place.is_some() => app.status(e), + Err(e) => io::report_open_error(app, &fileio::file_name(name), &e), + } +} + +/// Open the dialog for `bytes`, the drawing `info` describes (see [`offer`]), with what its +/// conversion off the UI thread brings, if it was converted there. +fn show( + app: &mut VectorcraftApp, + name: &str, + bytes: &[u8], + path: Option, + place: Option<&Value>, + info: &vectorcraft_cad::DxfInfo, + converted: Option, +) -> bool { let mut choices = DxfChoices { layout: info.layouts.first().cloned().unwrap_or_else(|| "Model".into()), unit: info.unit, @@ -342,28 +438,28 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option bool { let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); - if p.get("dxf").is_some() || named.as_deref() != Some("dxf") { + if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) { return false; } - let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dxf") else { return false }; + let Some((name, bytes, path)) = place_source(app, p, is_drawing_ext) else { return false }; offer(app, &name, &bytes, path, Some(p)) } /// The `dxf` options a drawing `file.place` params `p` name is placed with when Show Import Options /// is off: the choices confirmed last (fit, lineweights, centring, layers), the drawing at 1:1 in -/// its own unit. `None` when `p` names no `.dxf` drawing or already gives `dxf` options. +/// its own unit. `None` when `p` names no `.dxf` or `.dwg` drawing or already gives `dxf` options. pub fn last_options(app: &VectorcraftApp, p: &Value) -> Option { let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); - if p.get("dxf").is_some() || named.as_deref() != Some("dxf") { + if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) { return None; } Some(remembered(app)) @@ -395,14 +491,50 @@ fn options(c: &DxfChoices) -> Value { /// OK: open or place the drawing with the choices; an error keeps the dialog open. fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> Result<(), String> { let dxf = options(choices); - app.ui.dxf_import = Value::Object(REMEMBERED.iter().map(|k| (k.to_string(), dxf[*k].clone())).collect()); + let remembered = Value::Object(REMEMBERED.iter().map(|k| (k.to_string(), dxf[*k].clone())).collect()); match &source.place { Some(place) => { + let placement = source.converted.as_ref().and_then(|c| c.placement.as_ref()); + if let Some(placement) = placement { + placement.check(app)?; + } + app.ui.dxf_import = remembered; let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); p["dxf"] = dxf; - crate::place::run_for_user(app, &p).map(|_| ()) + // Where new art goes now is taken before Replace selects the object it swaps again. + let current = placement.and_then(|_| crate::placing::Insertion::of(app)); + // A drawing converted off the UI thread replaces the object selected when Place + // started, selected again, unless it changed meanwhile. + if let Some((old, node)) = placement.and_then(|pl| pl.replaced.as_ref()) { + let st = app.session.doc().map_err(|e| e.to_string())?; + if st.doc.node(*old) != Some(node) { + return Err("replace: the object to replace was changed or deleted".into()); + } + if st.selection.objects != [*old] || st.selection.symbol_part.is_some() { + app.session.execute("select.set", &json!({ "ids": [old.0] })).map_err(|e| e.to_string())?; + } + } + // It goes where new art went when Place started, and what the user changed since is + // kept, as for other files read for Place. + let restore = placement.and_then(|pl| pl.insertion.clone()).map(|insertion| { + let insertion = insertion.or_now(current.as_ref(), app, false); + insertion.clone().set(app); + insertion + }); + if let Some(converted) = &source.converted { + app.placing.keep_next = Some(Box::new(converted.held.clone())); + } + let r = crate::place::run_for_user(app, &p).map(|_| ()); + app.placing.keep_next = None; + if let (Some(current), Some(insertion)) = (current, restore) { + current.restore_changed(&insertion, app); + } + r + } + None => { + app.ui.dxf_import = remembered; + io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &json!({ "dxf": dxf })).map(|_| ()) } - None => io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &json!({ "dxf": dxf })).map(|_| ()), } } @@ -611,6 +743,312 @@ mod tests { assert_eq!(w, 100.0, "1 pt = 1 unit"); } + /// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_opens_and_places_through_the_dialog() { + vectorcraft_engine::dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); + let mut app = host::app(); + io::open_bytes(&mut app, "plan.dwg", &dwg, None).unwrap(); + let f = host::fields(&app, KIND); + assert_eq!((&f["mode"], &f["layout"], &f["unit"]), (&json!("open"), &json!("Model"), &json!("Millimeters"))); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); + let w = app.session.doc().unwrap().doc.artboards[0].rect.width(); + assert!((w - 100.0 * Unit::Millimeters.points()).abs() < 1e-6, "the model space line at 1:1: {w}"); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run(&mut app, &json!({"name": "plan.dwg", "dataBase64": vectorcraft_format::base64_encode(&dwg)})).unwrap(); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + } + + /// Where files the user opens and places are read off the UI thread, a DWG drawing is converted + /// on a job: its dialog opens once the conversion is done, not while File › Open or Place runs. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_is_converted_off_the_ui_thread_before_its_dialog_opens() { + let converted = finish_conversions; + vectorcraft_engine::dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); + let dir = crate::tests_folder::Folder::new("dxf-import-dwg-background"); + let (plan, bad) = (dir.join("plan.dwg"), dir.join("bad.dwg")); + std::fs::write(&plan, &dwg).unwrap(); + std::fs::write(&bad, &dwg[..dwg.len() / 3]).unwrap(); + let (plan, bad) = (plan.to_string_lossy().into_owned(), bad.to_string_lossy().into_owned()); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert!(!host::is_open(&app, KIND), "the dialog waits for the conversion"); + assert_eq!(app.opening.converting.len(), 1); + assert!(crate::opening::long_operation_busy(&app)); + assert_eq!(app.ui.status, "Converting plan.dwg…"); + // Asked for again while it is converted, it is converted once. + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert_eq!(app.opening.converting.len(), 1); + converted(&mut app); + assert!(app.opening.converting.is_empty() && app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(host::fields(&app, KIND)["mode"], "open"); + assert_eq!(app.ui.recent_files.first(), Some(&plan)); + host::confirm(&mut app, KIND).unwrap(); + let w = app.session.doc().unwrap().doc.artboards[0].rect.width(); + assert!((w - 100.0 * Unit::Millimeters.points()).abs() < 1e-6, "the model space line at 1:1: {w}"); + // Placed by the user, it is converted first too. + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + assert!(!host::is_open(&app, KIND)); + converted(&mut app); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + host::cancel(&app, KIND); + // A drawing that can't be converted is reported, and doesn't go on the recent files. + crate::io::open_file(&mut app, &bad, true).unwrap(); + converted(&mut app); + assert!(!host::is_open(&app, KIND)); + assert!(app.ui.status.starts_with("Couldn't open bad.dwg"), "{}", app.ui.status); + assert_ne!(app.ui.recent_files.first(), Some(&bad)); + }); + } + + /// Waits for the DWG conversions under way to finish, then lets [`crate::opening::poll`] hand + /// them on. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + fn finish_conversions(app: &mut VectorcraftApp) { + for c in &mut app.opening.converting { + let (tx, done) = std::sync::mpsc::channel(); + if let Ok(r) = c.done.recv() { + let _ = tx.send(r); + } + c.done = done; + } + crate::opening::poll(app); + } + + /// `plan.dwg`, the [`drawing`] as a DWG file in a folder of `test`'s own → its path. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + fn dwg_file(test: &str) -> (crate::tests_folder::Folder, String) { + let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); + let dir = crate::tests_folder::Folder::new(test); + let plan = dir.join("plan.dwg"); + std::fs::write(&plan, &dwg).unwrap(); + let plan = plan.to_string_lossy().into_owned(); + (dir, plan) + } + + /// While a DWG drawing is converted the idle window keeps coming back to look, so its dialog + /// opens when the conversion is done without other input. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn the_idle_window_opens_the_dialog_when_the_conversion_is_done() { + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64) -> std::time::Duration { + app.now_override = Some(time); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(time), + ..Default::default() + }; + let out = crate::testing::app_frame(app, ctx, raw); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + } + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-idle"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + let ctx = app.ui_ctx.clone().expect("the test app has a window"); + frame(&mut app, &ctx, 0.0); + crate::io::open_file(&mut app, &plan, true).unwrap(); + // The conversion's result is held back, so the drawing is still being converted in the frames below. + let (tx, done) = std::sync::mpsc::channel(); + let result = std::mem::replace(&mut app.opening.converting[0].done, done).recv().unwrap(); + frame(&mut app, &ctx, 1.0); + let wait = frame(&mut app, &ctx, 2.0); + assert!(wait <= std::time::Duration::from_millis(100), "{wait:?}: {:?}", ctx.repaint_causes()); + tx.send(result).unwrap(); + frame(&mut app, &ctx, 2.0 + wait.as_secs_f64()); + assert!(host::is_open(&app, KIND), "the dialog opens in the next frame"); + }); + } + + /// The progress window shows a DWG drawing being converted: Cancel drops it, so its dialog + /// never opens, and Continue in Background leaves it converting in the status bar only. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_conversion_can_be_cancelled_or_continued_in_the_background() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-cancel"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + assert!(!crate::menus::enabled(&app, "file.cancelOpen")); + crate::io::open_file(&mut app, &plan, true).unwrap(); + let (tx, done) = std::sync::mpsc::channel(); + let result = std::mem::replace(&mut app.opening.converting[0].done, done).recv().unwrap(); + assert!(crate::menus::enabled(&app, "file.cancelOpen") && crate::menus::enabled(&app, "file.openInBackground")); + assert!(crate::opening::shown(&app).is_some_and(|s| s.title.contains("plan.dwg"))); + assert_eq!(app.run("file.cancelOpen", json!({})).unwrap()["cancelled"], 1); + assert!(app.opening.converting.is_empty() && app.ui.status.is_empty(), "{}", app.ui.status); + assert!(!crate::menus::enabled(&app, "file.cancelOpen")); + assert!(tx.send(result).is_err(), "nothing waits for the result"); + crate::opening::poll(&mut app); + assert!(!host::is_open(&app, KIND)); + // Continue in Background. + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert_eq!(app.run("file.openInBackground", json!({})).unwrap()["hidden"], 1); + assert!(crate::opening::shown(&app).is_none() && !crate::menus::enabled(&app, "file.openInBackground")); + assert_eq!(app.ui.status, "Converting plan.dwg…"); + finish_conversions(&mut app); + assert!(host::is_open(&app, KIND)); + }); + } + + /// File › Open of a DWG drawing being converted for Place converts it for opening too. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_being_placed_can_also_be_opened() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-place-open"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert_eq!(app.opening.converting.len(), 2); + finish_conversions(&mut app); + }); + } + + /// A DWG drawing converted off the UI thread and placed keeps its conversion until the place + /// read off the UI thread is done. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_conversion_is_kept_for_the_pending_read() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-pending-hold"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + finish_conversions(&mut app); + host::confirm(&mut app, KIND).unwrap(); + assert!(app.placing.pending.first().is_some_and(crate::placing::Pending::holds_conversion)); + assert!(app.placing.keep_next.is_none()); + while !app.placing.pending.is_empty() { + crate::placing::wait(&mut app); + crate::placing::poll(&mut app); + } + }); + } + + /// A DWG drawing placed while it is converted goes in the document it was placed in, which + /// becomes the active one again, on the layer that was current when Place started and, with + /// `replace`, in place of the object selected then; it is not placed when that document was + /// closed or reverted meanwhile, and the status bar says why. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_placed_while_converted_goes_in_its_own_document() { + fn undo_steps(app: &VectorcraftApp, uid: u64) -> usize { + app.session.documents().iter().find(|st| st.uid == uid).map_or(0, |st| st.history.undo.len()) + } + fn placed(app: &mut VectorcraftApp) { + while !app.placing.pending.is_empty() { + crate::placing::wait(app); + crate::placing::poll(app); + } + } + vectorcraft_engine::dwg::allow_in_process(); + let (dir, plan) = dwg_file("dxf-import-dwg-place-doc"); + let saved = dir.join("saved.vectorcraft").to_string_lossy().into_owned(); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let first = app.session.doc().unwrap().uid; + let bottom = app.session.doc().unwrap().active_layer; + let ink = vectorcraft_doc::NodeId(app.run("layer.new", json!({})).unwrap()["id"].as_u64().unwrap()); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + // The user makes another layer current, then another document. + app.session.doc_mut().unwrap().active_layer = bottom; + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let other = app.session.doc().unwrap().uid; + let (before, other_before) = (undo_steps(&app, first), undo_steps(&app, other)); + finish_conversions(&mut app); + assert_eq!(app.session.doc().unwrap().uid, first, "the document it was placed in is active again"); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + host::confirm(&mut app, KIND).unwrap(); + placed(&mut app); + assert_eq!((undo_steps(&app, first), undo_steps(&app, other)), (before + 1, other_before)); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.parent_of(st.selection.objects[0]), Some(ink), "on the layer current when Place started"); + assert_eq!(st.active_layer, bottom, "the layer the user made current stays current"); + // Replace: the object selected when Place started is replaced, not the one selected since. + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + app.session.doc().unwrap().selection.objects[0] + }; + let replaced = rect(&mut app, 10.0); + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + // Meanwhile the user draws on another layer, which stays current. + app.session.doc_mut().unwrap().active_layer = Some(ink); + let selected_since = rect(&mut app, 50.0); + finish_conversions(&mut app); + host::confirm(&mut app, KIND).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert!(st.doc.node(replaced).is_none() && st.doc.node(selected_since).is_some(), "{}", app.ui.status); + assert_eq!(st.active_layer, Some(ink), "the layer the user made current stays current"); + // A selection Replace can't swap is refused at once, and nothing is converted. + app.run("select.all", json!({})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + assert!(app.opening.converting.is_empty()); + assert!(app.ui.status.contains("select the one object to replace"), "{}", app.ui.status); + // Closed meanwhile. + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + app.session.execute("file.close", &json!({})).unwrap(); + let other_before = undo_steps(&app, other); + finish_conversions(&mut app); + assert!(!host::is_open(&app, KIND)); + assert_eq!(app.ui.status, "Couldn't place plan.dwg: the document it was placed in was closed"); + assert_eq!(undo_steps(&app, other), other_before); + // Reverted meanwhile. + app.run("file.saveAs", json!({ "path": saved })).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = undo_steps(&app, other); + finish_conversions(&mut app); + assert!(!host::is_open(&app, KIND)); + assert_eq!(app.ui.status, "Couldn't place plan.dwg: the document it was placed in was reverted"); + assert_eq!(undo_steps(&app, other), reverted); + }); + } + + /// Switching documents while the import dialog is open leaves both documents unchanged. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_cannot_be_placed_after_switching_documents_in_its_dialog() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-place-dialog-switch"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let first = app.session.doc().unwrap().uid; + let before = app.session.doc().unwrap().history.undo.len(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + finish_conversions(&mut app); + assert!(host::is_open(&app, KIND)); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let other_before = app.session.doc().unwrap().history.undo.len(); + let error = host::confirm(&mut app, KIND).unwrap_err(); + assert!(error.contains("not the active document"), "{error}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), other_before); + let first = app.session.documents().iter().find(|st| st.uid == first).unwrap(); + assert_eq!(first.history.undo.len(), before); + }); + } + #[test] fn placing_a_drawing_asks_then_places_one_group() { let mut app = host::app(); diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 949382c23e..e98d212976 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -29,7 +29,7 @@ pub(super) const KIND: &str = "exportAs"; /// The built-in formats Export As writes (the native format and `.ai` are Save As's). static BUILT_IN: LazyLock> = LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect()); -/// Formats listed after them that can't be written (`fileio::unsupported` ids), greyed out. +/// Formats listed after them that can't be written (`fileio::write_hint` ids), greyed out. const UNAVAILABLE: [(&str, &str); 1] = [("dwg", "DWG (use DXF)")]; /// The formats Export As writes: the built-in ones, then those of the installed exporter plug-ins. @@ -46,7 +46,7 @@ fn from_plugin(f: &Format) -> bool { fn unavailable(fields: &DialogFields) -> Option<(&'static str, &'static str)> { let id = fields.text("format")?; let (_, label) = UNAVAILABLE.iter().find(|u| u.0 == id)?; - Some((label, fileio::unsupported(id)?.hint)) + Some((label, fileio::write_hint(id)?)) } /// The chosen format (PNG when the field names none Export As writes). diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index dd1dc255e7..04b12a8d50 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -650,3 +650,25 @@ fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected() assert_eq!(selected(&p), vec![first]); assert_eq!(undo_steps(&p), before); } + +/// `ui.findAndReplace` and `ui.paramDialog` with edit.findReplace open the dialog that `ui.inspect` lists with key null +/// and the fields the params text names, as both params texts say. +#[test] +fn params_texts_match_what_ui_inspect_lists() { + let expected = ["find", "replace", "matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers", "action"]; + let doc = |command: &str| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; + for (command, params) in [("ui.findAndReplace", json!({})), ("ui.paramDialog", json!({"command": super::COMMAND, "params": {}}))] { + let mut app = crate::testing::windowed(app_with(&["alpha"]).0); + app.run(command, params).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog"); + assert_eq!(entry.get("key"), Some(&Value::Null), "{command}: {entry}"); + assert!(doc(command).contains("with key null"), "{command} opens a dialog with key null, which its params text does not say"); + let missing: Vec<&str> = expected.iter().copied().filter(|f| entry["fields"].get(*f).is_none()).collect(); + assert!(missing.is_empty(), "{command}: ui.inspect does not list {missing:?}"); + } + let named = doc("ui.paramDialog"); + let unnamed: Vec<&str> = expected.iter().copied().filter(|f| !named.contains(*f)).collect(); + assert!(unnamed.is_empty(), "the params text of ui.paramDialog does not name {unnamed:?}"); +} 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/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index bbc16218e2..1475d2ca14 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -111,6 +111,10 @@ impl StackDialog for JavaScriptFiles { dialog_id(KEY) } + fn key(&self) -> Option<&str> { + Some(KEY) + } + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let Self { open, files, form } = self; let shown = Dialog::new(tl!("JavaScript Files")) @@ -418,4 +422,19 @@ mod tests { fixture.click(&add); assert_eq!(form.borrow().pending, Some(Pending::Add)); } + + /// `ui.javascriptFilesDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.javascriptFilesDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index bad3e0044c..aa2b84fc80 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -21,10 +21,14 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI}; -use craft::behavior::{ColumnWidth, IconId}; +use craft::behavior::{ColumnWidth, CursorIcon, IconId, Input, Metrics, PartKey, Sense}; +use craft::theme::Srgba; use craft::ui::buttons::Button; -use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked}; +use craft::ui::choice::{Checkbox, Segmented, SwatchMetrics}; +use craft::ui::contract::{ + Access, Bind, Common, Component, Cx, Entry, FieldLayout, Gap, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _, ShowContainer as _, + SideLabel, Sizing, clicked, +}; use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; use craft::ui::layout::CellAlign; @@ -35,10 +39,12 @@ use craft::ui::patterns::form_dialogs::{ use craft::ui::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary}; use craft::ui::pickers::Select; use craft::ui::popover::Popover; +use craft::ui::primitives::{PaintShape, StrokeWidth}; use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind, WordRows}; use craft::ui::sections::Section; -use craft::ui::style::TypeRole; +use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx, TypeRole}; use craft::ui::text::{LinkMode, LinkedWords, NumberField, follow_equal, link_toggle}; +use egui::{Color32, Rect, Response, Vec2}; use super::host::open_held; use crate::VectorcraftApp; @@ -356,12 +362,16 @@ impl DocumentSettings for VcNewDocument { let bleed = text(tl!("Bleed")); Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths, compact)); + // The list with a chip after it: white, or No Color's slash for transparent. Field::new(background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| { - let entries: Vec> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect(); - let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth); - if let Some(b) = select.show(ui).events.committed().copied() { - s.background = b; - } + Row::new().show(ui, |ui, _| { + let entries: Vec> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect(); + let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth); + if let Some(b) = select.show(ui).events.committed().copied() { + s.background = b; + } + background_chip(ui, s.background); + }); }); Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); @@ -420,6 +430,127 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti DocumentCard::new(text(preset_name(&preset.name)), line, value, CardSource::preset(None)) } +/// The chip after Background Contents: the paper white, or No Color for transparent. It shows the choice and opens +/// nothing. It is display-only: it is not a Tab stop, offers no click and draws in full color. +fn background_chip(ui: &mut egui::Ui, background: Background) { + let name = crate::i18n::fmt(tl!("{row} swatch"), &[("row", tl!("Background Contents"))]); + BackgroundChip::new(name, background).show(ui); +} + +// TEMPORARY: craft-libs on the pinned rev has no display-only PaintChip, so this chip draws the swatch-size well +// itself. Replace it with `PaintChip::chip_size(PaintChipSize::Swatch).display_only()` once storytold/craft-libs#4953 +// merges and the pin moves past it. + +/// The No Color diagonal stops this many well heights short of the chip's edges, as PaintChip's does. +const NO_COLOR_INSET: f32 = 0.15; +/// A one-column rail's cell holds this many swatch chips to a row, as PaintChip's swatch size does. +const SWATCHES_PER_RAIL_BUTTON: f32 = 3.0; +/// The chip's well, which keeps the arrow cursor: the chip opens nothing. +const BACKGROUND_WELL: PartKey = PartKey::new("well"); + +/// The style of a [`BackgroundChip`]. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +pub(crate) struct BackgroundChipStyle { + #[style(metrics)] + metrics: Metrics, + /// The well's side. + side: f32, + /// The well's corners. + radius: egui::CornerRadius, + /// The ring on the well's outline. + edge: StyleColor, + /// The fill of No Color. + none_fill: StyleColor, + /// The No Color diagonal. + none_mark: StyleColor, +} + +/// A swatch-size color well that shows the Background Contents choice: white, or No Color for transparent. +/// +/// - Pointer and keys: none; it is not a Tab stop and draws as an enabled chip. +/// - AccessKit: a color well named by the label, its value the hex or "No Color". +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(sample = background_chip_sample)] +pub(crate) struct BackgroundChip { + #[common] + common: Common, + background: Background, +} + +impl BackgroundChip { + /// A chip named `label` that shows `background`. + fn new(label: impl Into