diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 53a9be4e4a..94e08ef762 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,7 +67,8 @@ jobs: # The warm build runs as one `cache warm /6` leg per shard, in parallel (each builds what # its shard builds), and `cache warm` puts their files into the one entry it saves. warm-split: true - # The dependency cache also keeps the compiled workspace crates and test executables, so a + # The dependency cache also keeps the compiled workspace crates and their library and binary + # test executables (not the integration tests' executables), so a # pull request's shards rebuild only the crates its changes reach. Each main run's `cache # warm` leg saves a rolling entry of its own, every leg restores the newest one, and # cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores diff --git a/Cargo.lock b/Cargo.lock index 9ec37d145d..b878d75456 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,8 @@ version = 4 [[package]] name = "acadrust" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8923c99ea1f151cb7fc17ce2fc14f8b1e330fa22611e535602d985c0cc3c89a2" +version = "0.6.9" +source = "git+https://github.com/storytold/acadrust.git?rev=468b9d8e317755209020d5d3f2f1c8a76210c47f#468b9d8e317755209020d5d3f2f1c8a76210c47f" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -16,6 +15,7 @@ dependencies = [ "foldhash 0.2.0", "indexmap", "itoa", + "memchr", "memmap2", "nom 7.1.3", "oem_cp", @@ -24,6 +24,7 @@ dependencies = [ "ryu", "thiserror 2.0.21", "web-time", + "whichever", ] [[package]] @@ -1255,7 +1256,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-automation", "craft-behavior", @@ -1297,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "crc32fast", "flate2", @@ -1318,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1330,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "rustix 1.1.6", ] @@ -1338,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1363,11 +1364,12 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "accesskit", "bitflags 2.13.2", "craft-host", + "craft-i18n", "craft-keymap", "craft-theme", "craft-tracked", @@ -1381,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-docpath", @@ -1399,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "crc32fast", "flate2", @@ -1408,7 +1410,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "egui", ] @@ -1416,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "md-5", "rayon", @@ -1425,12 +1427,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-cms", @@ -1450,7 +1452,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1466,7 +1468,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1476,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "rayon", ] @@ -1484,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1510,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "blake3", "craft-ecproj-format", @@ -1526,7 +1528,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "serde", ] @@ -1534,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1553,16 +1555,17 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "acadrust", + "craft-dxf", "log", ] [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-codepage", "encoding_rs", @@ -1574,7 +1577,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "serde", "serde_json", @@ -1584,12 +1587,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-atomic", "dirs", @@ -1599,7 +1602,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1614,7 +1617,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1633,7 +1636,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1642,7 +1645,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "cap-primitives", "craft-atomic", @@ -1665,12 +1668,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "gif", ] @@ -1678,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "flate2", ] @@ -1686,7 +1689,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1699,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1729,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-dds", "craft-jpeg", @@ -1756,7 +1759,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1774,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "thiserror 2.0.21", ] @@ -1782,7 +1785,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1793,7 +1796,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-host", "craft-i18n", @@ -1808,7 +1811,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-i18n", @@ -1822,7 +1825,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-host", @@ -1840,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1852,7 +1855,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "encoding_rs", "image", @@ -1863,7 +1866,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "chrono", "craft-codepage", @@ -1873,7 +1876,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "uds_windows", "winsafe", @@ -1882,7 +1885,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-keymap", @@ -1898,7 +1901,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1907,7 +1910,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "flate2", "serde", @@ -1918,7 +1921,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1930,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "async-channel", "async-io", @@ -1963,7 +1966,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1972,7 +1975,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-host", @@ -1996,7 +1999,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2007,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-eps", "flate2", @@ -2021,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "encoding_rs", "flate2", @@ -2032,7 +2035,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "dispatch2", "egui", @@ -2045,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2054,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2073,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-atomic", "craft-host", @@ -2090,7 +2093,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "fax", "hayro-ccitt", @@ -2101,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2122,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-keymap", @@ -2134,7 +2137,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2159,7 +2162,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "thiserror 2.0.21", ] @@ -2167,7 +2170,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2182,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-atomic", "craft-behavior", @@ -2197,7 +2200,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "serde", "thiserror 2.0.21", @@ -2207,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "serde", "thiserror 2.0.21", @@ -2216,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-keymap", @@ -2231,12 +2234,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2250,7 +2253,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2267,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "accesskit", "craft-behavior", @@ -2305,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2316,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-host", @@ -2334,7 +2337,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-host", @@ -2355,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-host", @@ -2376,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-behavior", "craft-host", @@ -2395,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "base64 0.22.1", "chrono", @@ -2427,7 +2430,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "flate2", "serde", @@ -2438,7 +2441,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2448,7 +2451,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "js-sys", "serde_json", @@ -2459,7 +2462,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "winsafe", ] @@ -2467,7 +2470,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "craft-appkit", "craft-atomic", @@ -2499,7 +2502,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2844,7 +2847,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "bytemuck", "emath", @@ -2877,7 +2880,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "ahash", "bytemuck", @@ -2912,7 +2915,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "accesskit", "ahash", @@ -2931,7 +2934,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "ahash", "bytemuck", @@ -2950,7 +2953,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "accesskit_winit", "arboard", @@ -2976,7 +2979,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "ahash", "egui", @@ -2990,7 +2993,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "bytemuck", "egui", @@ -3003,7 +3006,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "dify", "eframe", @@ -3029,7 +3032,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "bytemuck", ] @@ -3110,7 +3113,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "ahash", "bytemuck", @@ -3136,7 +3139,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" +source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -3859,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3868,7 +3871,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3886,7 +3889,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3904,12 +3907,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "flate2", "hayro-ccitt", @@ -4892,7 +4895,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5049,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" +source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -7615,8 +7618,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", @@ -9272,6 +9274,8 @@ dependencies = [ name = "vectorcraft-ui-egui" version = "0.25.1" dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", "bytemuck", "chrono", "craft", @@ -9662,19 +9666,6 @@ dependencies = [ "wayland-scanner", ] -[[package]] -name = "wayland-protocols-plasma" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" -dependencies = [ - "bitflags 2.13.2", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "wayland-scanner", -] - [[package]] name = "wayland-protocols-wlr" version = "0.3.12" @@ -9975,6 +9966,26 @@ dependencies = [ "web-sys", ] +[[package]] +name = "whichever" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68887c9512981e597d730f1d95b2eb6abdd53385e4e76c35a95e7121e16232b0" +dependencies = [ + "whichever-macros", +] + +[[package]] +name = "whichever-macros" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb15ad553239d9fdefac12e31e16c7682dc62a2106ba035aec69c5dd15835a7b" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "widestring" version = "1.2.1" @@ -10218,7 +10229,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" +source = "git+https://github.com/storytold/winit.git?rev=3fd7ae64762f82a73b78bd24f453f82c4291067d#3fd7ae64762f82a73b78bd24f453f82c4291067d" dependencies = [ "ahash", "android-activity", @@ -10257,7 +10268,6 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-protocols", - "wayland-protocols-plasma", "web-sys", "web-time", "windows-sys 0.52.0", diff --git a/Cargo.toml b/Cargo.toml index f8fb73b21d..a48e3c1330 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # 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 = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # 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 = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # 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 = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # 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 = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # 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 = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # 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 = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -200,22 +200,25 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } -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" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } -winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). +# It stays at this rev until craft-libs#5222 merges. +skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" } +winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" } diff --git a/ROADMAP.md b/ROADMAP.md index f81353a895..b59eea470a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,7 +124,9 @@ 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-04: Paste from CAD apps: on Windows, Paste reads the enhanced metafile CAD and office apps copy as vector art, and a `.dxf`, `.dwg` or HP-GL plot file copied in a file manager pastes as its drawing through the new command `clipboard.importCad` (#10819). 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-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index d94dcf91cc..4db9a1dac2 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 = "a59264281e498d78ede8f503572b3d5502c44d51", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 0d886789e2..e9737ab251 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -2,8 +2,10 @@ //! (`Services::clipboard`). //! //! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go; -//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that -//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`). +//! Paste reads each of them and EPS, the enhanced metafile that CAD and office apps copy as +//! vector art (`CF_ENHMETAFILE`; the system makes one of a `CF_METAFILEPICT`), a bitmap as PNG, +//! else as the device-independent bitmap that screenshots and most apps copy (`CF_DIBV5`, +//! `CF_DIB`; the system makes them of a `CF_BITMAP`). //! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and //! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste //! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG @@ -19,7 +21,8 @@ //! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at //! once; a paste then waits for that read's answer off the UI thread. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, -//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A +//! a metafile, a DXF or DWG drawing, an HP-GL plot file or a bitmap), before the clipboard's +//! other formats (the files' paths as text). A //! file of more than 64 MiB is skipped before it is read. use std::io::{Cursor, Read}; @@ -303,6 +306,23 @@ fn copy_within(size: Option, limit: usize, copy: impl FnOnce() -> Option< copy().filter(|data| data.len() <= limit) } +/// The records of an enhanced metafile, which the Windows clipboard holds as a handle +/// (`CF_ENHMETAFILE`) whose records `GetEnhMetaFileBits` copies: `bits` called without a buffer +/// gives their size, and with a buffer copies them and gives how many bytes it copied (0 when it +/// failed). Nothing is copied when the size is 0 or more than `limit` bytes ([`copy_within`]). +#[cfg_attr(not(windows), allow(dead_code))] +fn enhmetafile_bits(mut bits: impl FnMut(Option<&mut [u8]>) -> u32, limit: usize) -> Option> { + let size = usize::try_from(bits(None)).ok(); + copy_within(size, limit, || { + let mut data = vec![0; size?]; + let copied = usize::try_from(bits(Some(&mut data))).ok()?; + (copied > 0 && copied <= data.len()).then(|| { + data.truncate(copied); + data + }) + }) +} + /// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at /// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4. #[cfg_attr(not(windows), allow(dead_code))] @@ -428,10 +448,12 @@ mod win { use std::path::PathBuf; + use windows::Win32::Graphics::Gdi::{GetEnhMetaFileBits, HENHMETAFILE}; + use super::{ - BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG, SVG, - TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, png_flavour, read_flavor, read_image_flavor, read_later_flavor, - utf8_most, windows_formats, + BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, EMF, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG, + SVG, TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, enhmetafile_bits, png_flavour, read_flavor, read_image_flavor, + read_later_flavor, utf8_most, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -533,6 +555,7 @@ mod win { || mimes.iter().any(|m| match *m { TEXT => raw::is_format_avail(formats::CF_UNICODETEXT), BITMAP => DIBS.into_iter().chain(formats_of(PNG)).any(raw::is_format_avail), + EMF => raw::is_format_avail(formats::CF_ENHMETAFILE), m => formats_of(m).any(raw::is_format_avail), }) } @@ -571,6 +594,19 @@ mod win { formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty())) } + /// The enhanced metafile the clipboard holds, while it is open, as the bytes of an EMF file; at + /// most [`MAX_BYTES`] of them ([`enhmetafile_bits`]). + #[allow(unsafe_code)] + fn read_enhmetafile() -> Option> { + if !raw::is_format_avail(formats::CF_ENHMETAFILE) { + return None; + } + let emf = HENHMETAFILE(raw::get_clipboard_data(formats::CF_ENHMETAFILE).ok()?.as_ptr()); + // SAFETY: `emf` is the clipboard's metafile handle, which stays valid while the clipboard is + // open; the call writes at most the length of the buffer it is given. + enhmetafile_bits(|buffer| unsafe { GetEnhMetaFileBits(emf, buffer) }, MAX_BYTES) + } + /// A device-independent bitmap as a PNG flavour. fn dib_png(dib: &[u8]) -> Option { png_flavour(&dib_image(dib)?) @@ -607,6 +643,7 @@ mod win { })?; (TEXT, text) } + EMF => (EMF, read_enhmetafile()?), m => (m, read_registered(m)?), }; // Memory blocks can be longer than the data: SVG text ends at its first NUL. @@ -3545,6 +3582,48 @@ mod tests { assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none()); } + /// A DXF drawing or an HP-GL plot file copied in a file manager pastes as vector art. + #[test] + fn a_copied_cad_file_pastes() { + use vectorcraft_engine::cmd::clipboard::{DXF, HPGL}; + let d = dir("cad"); + let (dxf, plot) = (d.path().join("plan.dxf"), d.path().join("part.plt")); + std::fs::write(&dxf, "0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n").unwrap(); + std::fs::write(&plot, "IN;SP1;PA0,0;PD1016,0;PU;").unwrap(); + assert_eq!(copied_file(vec![dxf.clone()], &PASTE_ORDER).map(|f| f.mime), Some(DXF)); + assert_eq!(copied_file(vec![plot.clone()], &PASTE_ORDER).map(|f| f.mime), Some(HPGL)); + assert!(copied_file(vec![dxf, plot], &[BITMAP, TEXT]).is_none()); + } + + /// The enhanced metafile the Windows clipboard holds is copied whole, into a buffer of the size + /// it gives; one of no records or of more than the limit is not copied, and a failed copy gives + /// nothing. + #[test] + fn an_enhanced_metafile_is_copied_within_the_limit() { + let records: Vec = (0..40).collect(); + let read = |records: &[u8], fails: bool, limit: usize| { + let mut copies = 0; + let got = enhmetafile_bits( + |buffer| match buffer { + None => records.len() as u32, + Some(_) if fails => 0, + Some(buffer) => { + copies += 1; + assert_eq!(buffer.len(), records.len()); + buffer.copy_from_slice(records); + records.len() as u32 + } + }, + limit, + ); + (got, copies) + }; + assert_eq!(read(&records, false, 40), (Some(records.clone()), 1)); + assert_eq!(read(&records, false, 39), (None, 0)); + assert_eq!(read(&[], false, 40), (None, 0)); + assert_eq!(read(&records, true, 40), (None, 0)); + } + #[test] fn a_crlf_left_by_the_uri_list_is_ignored() { let d = dir("crlf"); diff --git a/crates/cad/src/blocks_compat.rs b/crates/cad/src/blocks_compat.rs new file mode 100644 index 0000000000..bcc4860314 --- /dev/null +++ b/crates/cad/src/blocks_compat.rs @@ -0,0 +1,115 @@ +//! Block definitions and INSERT entities for the DXF writer. +//! +//! Temporary: `craft_dxf::drawing` at the pinned craft-libs revision writes only the model and +//! paper space blocks. storytold/craft-libs#5381 adds `Block`, `Drawing::blocks` and +//! `Codes::insert`; once it merges and the pin moves past it, this module is removed and +//! `scene.rs` uses those instead. Until then [`write`] adds the user blocks to the file that +//! `Drawing::write` returns, with the same group codes #5381 writes. + +use craft_dxf::drawing::{Codes, Drawing, Handle, fixed}; + +/// A block definition: entities written once, which INSERT entities place ([`insert`]). Its base +/// point is the origin. +#[derive(Clone, Debug)] +pub struct Block { + pub name: String, + /// The handle of its BLOCK_RECORD (from R13), which owns its entities. + pub record: Handle, + /// The handles of its BLOCK and ENDBLK records. + pub begin: Handle, + pub end: Handle, + /// The entities' group codes, written with `record` as their owner. + pub entities: String, +} + +/// The start of an object: its type, and from R13 its handle, owner and first subclass. +fn object(c: &mut Codes, kind: &str, h: Handle, owner: Handle, subclass: &str) { + c.raw(0, kind); + if c.v.handles() { + c.handle(5, h); + c.handle(330, owner); + c.raw(100, subclass); + } +} + +/// An INSERT entity owned by `owner` on `layer` that places block `block` at the origin, unscaled +/// and unrotated. It has no color of its own (ByLayer). +pub fn insert(c: &mut Codes, h: Handle, owner: Handle, layer: &str, block: &str) { + object(c, "INSERT", h, owner, "AcDbEntity"); + c.str(8, layer); + if c.v.handles() { + c.raw(100, "AcDbBlockReference"); + } + c.str(2, block); + c.xyz(10, 0.0, 0.0); +} + +/// The whole file of `d` with `blocks` written after the model and paper space blocks. +pub fn write(d: Drawing, blocks: &[Block]) -> String { + let v = d.version; + let out = d.write(); + if blocks.is_empty() { + return out; + } + let mut defs = Codes::new(v); + for b in blocks { + object(&mut defs, "BLOCK", b.begin, b.record, "AcDbEntity"); + defs.raw(8, "0"); + if v.handles() { + defs.raw(100, "AcDbBlockBegin"); + } + defs.str(2, &b.name); + defs.int(70, 0); + defs.xyz(10, 0.0, 0.0); + defs.str(3, &b.name); + defs.raw(1, ""); + defs.append(&b.entities); + object(&mut defs, "ENDBLK", b.end, b.record, "AcDbEntity"); + defs.raw(8, "0"); + if v.handles() { + defs.raw(100, "AcDbBlockEnd"); + } + } + let defs = defs.into_string(); + if !v.handles() { + // R12 has no model and paper space blocks: its BLOCKS section holds the user blocks only. + let at = " 0\nSECTION\n 2\nENTITIES\n"; + return match out.find(at) { + Some(i) => format!("{} 0\nSECTION\n 2\nBLOCKS\n{defs} 0\nENDSEC\n{}", &out[..i], &out[i..]), + None => out, + }; + } + let mut records = Codes::new(v); + for b in blocks { + object(&mut records, "BLOCK_RECORD", b.record, fixed::BLOCK_RECORD_TABLE, "AcDbSymbolTableRecord"); + records.raw(100, "AcDbBlockTableRecord"); + records.str(2, &b.name); + if v.r2000() { + records.handle(340, Handle(0)); + records.int(70, 0); + records.int(280, 1); + records.int(281, 0); + } + } + let records = records.into_string(); + let (Some(table), Some(blocks_at)) = (out.find(" 0\nTABLE\n 2\nBLOCK_RECORD\n"), out.find(" 0\nSECTION\n 2\nBLOCKS\n")) else { + return out; + }; + let count = " 70\n2\n"; + let (Some(c), Some(t_end), Some(b_end)) = ( + out[table..].find(count).map(|i| table + i), + out[table..].find(" 0\nENDTAB\n").map(|i| table + i), + out[blocks_at..].find(" 0\nENDSEC\n").map(|i| blocks_at + i), + ) else { + return out; + }; + let mut s = String::with_capacity(out.len() + records.len() + defs.len()); + s.push_str(&out[..c]); + s.push_str(&format!(" 70\n{}\n", 2 + blocks.len())); + s.push_str(&out[c + count.len()..t_end]); + s.push_str(&records); + s.push_str(&out[t_end..b_end]); + s.push_str(&defs); + s.push_str(&out[b_end..]); + s +} diff --git a/crates/cad/src/hpgl.rs b/crates/cad/src/hpgl.rs index 9494fbee46..eefca332b0 100644 --- a/crates/cad/src/hpgl.rs +++ b/crates/cad/src/hpgl.rs @@ -76,6 +76,12 @@ pub fn is_hpgl(bytes: &[u8]) -> bool { holds_instructions(bytes, true) } +/// Does `bytes` start like a file named as an HP-GL plot file ([`import`] reads it)? As +/// [`is_hpgl`] checks, but any instruction may come first. +pub fn is_named_hpgl(bytes: &[u8]) -> bool { + holds_instructions(bytes, false) +} + /// Does `bytes` hold HP-GL instructions as [`is_hpgl`] checks? When `strict` is false, any of them /// may come first: a file picked by its extension may start with one a plot file seldom starts /// with (`SI`, `DI`). Either way, at least one of the instructions checked must be one the reader 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/lib.rs b/crates/cad/src/lib.rs index 73e30bd2a9..e4eac1b20c 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -5,7 +5,8 @@ //! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths //! become polylines (straight segments) or cubic splines (curves), fills their outlines and solid //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG -//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per +//! or JPEG files the caller writes next to the drawing; with [`DxfOptions::group_blocks`] groups +//! become blocks placed by INSERT entities. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. //! [`export_drawings`] writes one such drawing for each of several regions, applying the live //! effects once for all of them. @@ -26,6 +27,8 @@ #![doc(test(attr(deny(unsafe_code))))] mod aci; +// Temporary until storytold/craft-libs#5381 merges and the craft-libs pin moves past it. +mod blocks_compat; pub mod dwg; #[cfg(test)] mod expansion_test; @@ -316,6 +319,10 @@ pub struct DxfOptions { pub alter_paths: bool, /// Type is written as glyph outlines (always with [`Preserve::Appearance`]). pub outline_text: bool, + /// Always Export Group as Block Reference: each group is written as a block definition of its + /// contents, placed by an INSERT entity on the group's layer (groups inside it are blocks + /// placed inside that block). Off: a group's contents are written as plain entities. + pub group_blocks: bool, /// The drawing's origin is this region's bottom-left corner (document space). pub region: Rect, /// Leave out objects entirely outside `region` (one drawing per artboard). @@ -336,6 +343,7 @@ impl Default for DxfOptions { preserve: Preserve::default(), alter_paths: false, outline_text: false, + group_blocks: false, region: Rect::ZERO, crop: false, } diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 26025f2544..45d2fcf234 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -2,7 +2,8 @@ //! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with //! hatches left out), placed images are linked image files unless left out, strokes //! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or -//! filled outlines where the look needs them. +//! filled outlines where the look needs them. With [`DxfOptions::group_blocks`] each group is a +//! block, placed by an INSERT. use std::collections::HashMap; @@ -14,6 +15,8 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2}; use crate::aci::nearest_aci; use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat}; +// Block and the INSERT writer come from craft-libs#5381 once it merges; see `blocks_compat`. +use crate::blocks_compat::Block; use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed}; /// Curves are flattened to within this distance (points) where DXF needs straight segments @@ -503,8 +506,13 @@ pub(crate) struct Scene<'a> { to_dxf: Affine, /// Drawing units per point. k: f64, - /// The entities written so far. + /// The entities written so far: those of model space, or of the group block being written. e: Codes, + /// The owner of the entities in `e`: model space, or the group block's record. + owner: Handle, + /// Group blocks written so far ([`DxfOptions::group_blocks`]), each after the blocks it inserts. + blocks: Vec, + block_names: Names, next: u32, layers: Vec, layer_names: Names, @@ -544,6 +552,9 @@ impl<'a> Scene<'a> { to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]), k, e: Codes::new(o.version.into()), + owner: fixed::MODEL_RECORD, + blocks: vec![], + block_names: Names::with(&["*Model_Space", "*Paper_Space"]), next: fixed::FIRST_FREE, layers: vec![], layer_names: Names::with(&["0", "Defpoints"]), @@ -593,7 +604,12 @@ impl<'a> Scene<'a> { metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters), next: self.next, }; - DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes } + DxfOutput { + bytes: crate::blocks_compat::write(drawing, &self.blocks).into_bytes(), + images: self.files, + warnings: self.warnings, + setting_notes: self.setting_notes, + } } /// Note `w`, once, about something of the document that the drawing leaves out or that reaches @@ -660,6 +676,7 @@ impl<'a> Scene<'a> { self.children(children, *clip); (self.layer, self.flags) = outer; } + NodeKind::Group { children, clip } if self.o.group_blocks => self.group_block(n, children, *clip), NodeKind::Group { children, clip } => self.children(children, *clip), NodeKind::Path { path, rule, guide, .. } => { if !*guide { @@ -754,6 +771,27 @@ impl<'a> Scene<'a> { } } + /// Group `n` as a block of its children's entities and an INSERT that places it on the current + /// layer ([`DxfOptions::group_blocks`]). The block's base point is the drawing's origin, so its + /// entities keep their coordinates. A group that writes no entity writes no block. + fn group_block(&mut self, n: &Node, children: &[std::sync::Arc], clip: bool) { + let (record, begin, end, insert) = (self.handle(), self.handle(), self.handle(), self.handle()); + let outer = std::mem::replace(&mut self.e, Codes::new(self.o.version.into())); + let owner = std::mem::replace(&mut self.owner, record); + self.children(children, clip); + let entities = std::mem::replace(&mut self.e, outer).into_string(); + self.owner = owner; + if entities.is_empty() { + return; + } + let long = self.o.version.r2000(); + let base = symbol_name(n.name.as_deref().unwrap_or_default(), long); + let base = if base.is_empty() { symbol_name("Group", long) } else { base }; + let name = self.block_names.unique(&base, if long { 255 } else { 31 }); + crate::blocks_compat::insert(&mut self.e, insert, self.owner, &self.layer, &name); + self.blocks.push(Block { name, record, begin, end, entities }); + } + /// Warn about what DXF can't hold in `n`'s look. fn note_losses(&mut self, n: &Node) { if n.blend != vectorcraft_color::BlendMode::Normal { @@ -959,7 +997,7 @@ impl<'a> Scene<'a> { } let h = self.handle(); let layer = self.layer.clone(); - self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch"); + self.e.entity("HATCH", h, self.owner, &layer, style, "AcDbHatch"); self.e.xyz(10, 0.0, 0.0); self.e.normal(); self.e.raw(2, "SOLID"); @@ -1040,7 +1078,7 @@ impl<'a> Scene<'a> { let (a, b) = (self.pt(a), self.pt(b)); let layer = self.layer.clone(); let h = self.handle(); - self.e.entity("LINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbLine"); + self.e.entity("LINE", h, self.owner, &layer, style, "AcDbLine"); self.e.xyz(10, a.x, a.y); self.e.xyz(11, b.x, b.y); } @@ -1058,7 +1096,7 @@ impl<'a> Scene<'a> { // Bit 128: a linetype runs on through the vertices instead of restarting at each one. let flags = i64::from(closed) | if style.linetype.is_some() { 128 } else { 0 }; if self.o.version.lwpolyline() { - self.e.entity("LWPOLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbPolyline"); + self.e.entity("LWPOLYLINE", h, self.owner, &layer, style, "AcDbPolyline"); self.e.int(90, pts.len() as i64); self.e.int(70, flags); if let Some(w) = width { @@ -1072,7 +1110,7 @@ impl<'a> Scene<'a> { } return; } - self.e.entity("POLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDb2dPolyline"); + self.e.entity("POLYLINE", h, self.owner, &layer, style, "AcDb2dPolyline"); self.e.int(66, 1); self.e.xyz(10, 0.0, 0.0); self.e.int(70, flags); @@ -1134,7 +1172,7 @@ impl<'a> Scene<'a> { let layer = self.layer.clone(); let h = self.handle(); if sub.closed { - self.e.entity("CIRCLE", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle"); + self.e.entity("CIRCLE", h, self.owner, &layer, style, "AcDbCircle"); self.e.xyz(10, centre.x, centre.y); self.e.num(40, radius); self.e.normal(); @@ -1150,7 +1188,7 @@ impl<'a> Scene<'a> { if !on_ccw_arc(a0, a1, am) { std::mem::swap(&mut a0, &mut a1); } - self.e.entity("ARC", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle"); + self.e.entity("ARC", h, self.owner, &layer, style, "AcDbCircle"); self.e.xyz(10, centre.x, centre.y); self.e.num(40, radius); self.e.normal(); @@ -1197,7 +1235,7 @@ impl<'a> Scene<'a> { let layer = self.layer.clone(); let h = self.handle(); - self.e.entity("ELLIPSE", h, fixed::MODEL_RECORD, &layer, style, "AcDbEllipse"); + self.e.entity("ELLIPSE", h, self.owner, &layer, style, "AcDbEllipse"); self.e.xyz(10, centre.x, centre.y); self.e.xyz(11, axis.x, axis.y); self.e.normal(); @@ -1232,7 +1270,7 @@ impl<'a> Scene<'a> { let ctrl: Vec = ctrl.iter().map(|p| self.pt(*p)).collect(); let layer = self.layer.clone(); let h = self.handle(); - self.e.entity("SPLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbSpline"); + self.e.entity("SPLINE", h, self.owner, &layer, style, "AcDbSpline"); self.e.normal(); // Planar (bit 3) and, if the subpath is closed, also closed (bit 0). A geometrically // closed cut needs the closed flag set so CAM/CAM tools (e.g. VCarve) treat it as a @@ -1308,7 +1346,7 @@ impl<'a> Scene<'a> { let p = self.pt(t.xf * origin); let layer = self.layer.clone(); let h = self.handle(); - self.e.entity("TEXT", h, fixed::MODEL_RECORD, &layer, &style, "AcDbText"); + self.e.entity("TEXT", h, self.owner, &layer, &style, "AcDbText"); self.e.xyz(10, p.x, p.y); self.e.num(40, height); let s: String = s.chars().take(MAX_TEXT).collect(); @@ -1368,7 +1406,7 @@ impl<'a> Scene<'a> { let def = def.handle; let layer = self.layer.clone(); let style = EntityStyle { aci: 7, ..EntityStyle::default() }; - self.e.entity("IMAGE", handle, fixed::MODEL_RECORD, &layer, &style, "AcDbRasterImage"); + self.e.entity("IMAGE", handle, self.owner, &layer, &style, "AcDbRasterImage"); self.e.int(90, 0); self.e.xyz(10, at.x, at.y); self.e.xyz(11, u.x, u.y); diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 16f4f97082..216dc1a088 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -8,6 +8,8 @@ use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, Shape, shapes} use crate::*; +mod blocks; + type Pairs = Vec<(i32, String)>; /// The `(code, value)` pairs of a DXF file. diff --git a/crates/cad/src/tests/blocks.rs b/crates/cad/src/tests/blocks.rs new file mode 100644 index 0000000000..b0ac7a9fe4 --- /dev/null +++ b/crates/cad/src/tests/blocks.rs @@ -0,0 +1,125 @@ +//! Always Export Group as Block Reference: groups written as blocks placed by INSERT entities. + +use super::*; + +/// The user blocks of a drawing (not model or paper space): each its name and the entities +/// between its BLOCK and its ENDBLK. +fn blocks(out: &DxfOutput) -> Vec<(String, Vec)> { + let mut found: Vec<(String, Vec)> = vec![]; + let mut open = false; + for o in section(&pairs(&out.bytes), "BLOCKS") { + match kind(&o) { + "BLOCK" => { + found.push((get(&o, 2).unwrap_or_default().to_string(), vec![])); + open = true; + } + "ENDBLK" => open = false, + _ if open => found.last_mut().expect("a block").1.push(o), + _ => {} + } + } + found.retain(|(name, _)| !name.starts_with('*')); + found +} + +/// A filled square outside any group; the group `Frame` holding a stroked rectangle and the group +/// `Ring` holding a circle, on a second layer `Parts`. +fn grouped_doc() -> Document { + let mut d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(150.0, 10.0, 170.0, 30.0)), Paint::solid(Color::BLACK), Paint::None, 0.0)]); + let parts = d.add_layer(Some("Parts")); + let rect = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0); + let circle = path(&mut d, shapes::ellipse(Rect::new(40.0, 20.0, 70.0, 50.0)), Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let mut ring = Node::group(d.alloc_id(), vec![Arc::new(circle)]); + ring.name = Some("Ring".into()); + let mut frame = Node::group(d.alloc_id(), vec![Arc::new(rect), Arc::new(ring)]); + frame.name = Some("Frame".into()); + d.insert(Some(parts), usize::MAX, frame).unwrap(); + d +} + +#[test] +fn groups_are_blocks_placed_by_inserts_in_every_version() { + let d = grouped_doc(); + for v in DxfVersion::ALL { + let out = export(&d, &DxfOptions { version: v, group_blocks: true, ..opts(&d) }).unwrap(); + let top = entities(&out); + let inserts: Vec<&Pairs> = top.iter().filter(|e| kind(e) == "INSERT").collect(); + assert_eq!(inserts.len(), 1, "{v:?}: the outer group alone is placed in model space"); + // Before 2000, names are capitals, letters, digits and $-_ only. + let long = v >= DxfVersion::R2000; + let (frame, ring, parts, first) = if long { ("Frame", "Ring", "Parts", "Layer 1") } else { ("FRAME", "RING", "PARTS", "LAYER_1") }; + assert_eq!((get(inserts[0], 2), get(inserts[0], 8)), (Some(frame), Some(parts)), "{v:?}"); + assert!(top.iter().any(|e| kind(e) != "INSERT" && get(e, 8) == Some(first)), "{v:?}: the loose square stays in model space"); + let found = blocks(&out); + let names: Vec<&str> = found.iter().map(|b| b.0.as_str()).collect(); + assert_eq!(names, [ring, frame], "{v:?}: the inner block comes first"); + let (ring_entities, frame_entities) = (&found[0].1, &found[1].1); + assert!(!ring_entities.is_empty() && ring_entities.iter().all(|e| kind(e) != "INSERT"), "{v:?}: the circle is in its group's block"); + let nested: Vec<&Pairs> = frame_entities.iter().filter(|e| kind(e) == "INSERT").collect(); + assert_eq!(nested.len(), 1, "{v:?}: the inner group is placed inside the outer block"); + assert_eq!(get(nested[0], 2), Some(ring), "{v:?}"); + assert!(frame_entities.iter().any(|e| kind(e) != "INSERT"), "{v:?}: the rectangle is in the outer block"); + if v >= DxfVersion::R13 { + // Each block's entities are owned by its BLOCK_RECORD, and the INSERTs by what holds them. + let records = table(&out, "BLOCK_RECORD"); + let record = |name: &str| records.iter().find(|r| get(r, 2) == Some(name)).and_then(|r| get(r, 5).map(str::to_string)); + for (name, ents) in &found { + let owner = record(name).unwrap_or_else(|| panic!("{v:?}: no BLOCK_RECORD for {name}")); + // A polyline's vertices and its SEQEND are owned by the polyline. + let owned: Vec<&Pairs> = ents.iter().filter(|e| !matches!(kind(e), "VERTEX" | "SEQEND")).collect(); + assert!(!owned.is_empty() && owned.iter().all(|e| get(e, 330) == Some(owner.as_str())), "{v:?}: {name}"); + } + assert_eq!(get(inserts[0], 330).map(str::to_string), record("*Model_Space"), "{v:?}: the outer INSERT is in model space"); + assert_eq!(get(nested[0], 330).map(str::to_string), record(frame), "{v:?}: the inner INSERT is in the outer block"); + } + } +} + +#[test] +fn without_the_option_groups_are_written_as_their_contents() { + let d = grouped_doc(); + let out = export(&d, &opts(&d)).unwrap(); + assert!(blocks(&out).is_empty()); + assert!(!kinds(&out).iter().any(|k| k == "INSERT")); + let with = export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap(); + // The same entities are written, moved into blocks. + let count = |o: &DxfOutput| { + let drawn = |ents: &[Pairs]| ents.iter().filter(|e| kind(e) != "INSERT").count(); + drawn(&entities(o)) + blocks(o).iter().map(|b| drawn(&b.1)).sum::() + }; + assert_eq!(count(&out), count(&with)); + assert_eq!(header(&pairs(&out.bytes), "$EXTMIN"), header(&pairs(&with.bytes), "$EXTMIN")); + assert_eq!(header(&pairs(&out.bytes), "$EXTMAX"), header(&pairs(&with.bytes), "$EXTMAX")); +} + +#[test] +fn blocks_read_back_at_the_place_their_group_was() { + let d = grouped_doc(); + let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }; + let plain = import(&export(&d, &opts(&d)).unwrap().bytes, &o).unwrap().document; + let blocked = import(&export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap().bytes, &o).unwrap().document; + let names: Vec<&str> = blocked.symbols.iter().map(|s| s.name.as_str()).collect(); + assert!(names.contains(&"Frame") && names.contains(&"Ring"), "{names:?}"); + let (a, b) = (plain.art_bounds().unwrap(), blocked.art_bounds().unwrap()); + assert!(close_to(&[a.x0, a.y0, a.x1, a.y1], &[b.x0, b.y0, b.x1, b.y1], 1e-6), "{a:?} against {b:?}"); +} + +#[test] +fn a_group_with_nothing_written_is_no_block_and_names_stay_unique() { + let mut d = Document::new(200.0, 100.0); + let layer = d.layers[0].id; + let mut hidden = path(&mut d, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Paint::solid(Color::BLACK), Paint::None, 0.0); + hidden.visible = false; + let empty = Node::group(d.alloc_id(), vec![Arc::new(hidden)]); + d.insert(Some(layer), usize::MAX, empty).unwrap(); + for name in [Some("Part"), Some("part"), None, Some("*Model_Space")] { + let p = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(p)]); + g.name = name.map(str::to_string); + d.insert(Some(layer), usize::MAX, g).unwrap(); + } + let out = export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap(); + let names: Vec = blocks(&out).into_iter().map(|b| b.0).collect(); + assert_eq!(names, ["Part", "part_2", "Group", "_Model_Space"], "the hidden-only group writes no block"); + assert_eq!(kinds(&out).iter().filter(|k| *k == "INSERT").count(), 4); +} diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index ba12eafabb..56bbb29845 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -28,12 +28,19 @@ pub fn resolve_stored_radii(base: &PathData, stored: &[f64], relative: bool) -> out } +fn dormant_radius_scale(base: &PathData) -> f64 { + base.length().max(1e-12) +} + /// Turn stored absolute radii into fractions of each corner's maximum, or the other way. +/// Anchors without a cuttable corner use the outline's length (at least 1e-12 document units). +/// Their fractions are not capped at 1. +/// When an anchor edit straightens or bends a corner, [`edit_corner_anchors`] converts its +/// radius between these reference lengths, preserving its document length at that edit. pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { if live.radii_relative() == relative { return; } - 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 { .. } | LiveShape::Star { .. } => live.polygon_outline(), @@ -41,22 +48,22 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; let corners = path_corners(&base); + let dormant_scale = dormant_radius_scale(&base); let radii: &mut [f64] = match live { LiveShape::Rectangle { radii, .. } => radii, LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii, LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; - for c in corners { - if let Some(r) = radii.get(c.index) { - let max = c.max_radius(); - radii[c.index] = if relative { - if max > 1e-12 && !was_relative { (*r / max).clamp(0.0, 1.0) } else { *r } - } else if was_relative { - (*r).clamp(0.0, 1.0) * max - } else { - *r - }; + for (index, r) in radii.iter_mut().enumerate() { + let corner = corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &corners[i]); + let max = corner.map_or(dormant_scale, Corner::max_radius); + if relative { + if max > 0.0 { + *r = if corner.is_some() { (*r / max).clamp(0.0, 1.0) } else { (*r / max).max(0.0) }; + } + } else { + *r = if corner.is_some() { (*r).clamp(0.0, 1.0) } else { (*r).max(0.0) } * max; } } match live { @@ -143,7 +150,8 @@ impl<'a> LiveCorners<'a> { } /// The radius corner `index` is stored at: document lengths, or a fraction in 0..1 when - /// [`LiveCorners::radii_relative`]. + /// [`LiveCorners::radii_relative`]. Dormant anchors use the reference length documented in + /// [`convert_radii_relative`], and their fractions can exceed 1. pub fn radius(&self, index: usize) -> f64 { self.radii.get(index).copied().unwrap_or(0.0) } @@ -206,8 +214,8 @@ impl<'a> LiveCorners<'a> { /// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of /// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again. /// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a -/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they -/// are. +/// plain path again once no radius or nondefault corner kind is stored. A straight anchor keeps +/// its stored radius. Ellipses and lines have no corners: they stay as they are. pub fn set_corners(path: &mut PathData, live: &mut Option>, corners: &BTreeSet, radius: Option, kind: Option) { fn edit( base: &PathData, @@ -286,13 +294,31 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne } } +/// Convert relative `radii` (fractions, one per anchor of the outline) after the outline changed +/// from `before` to `after`: a corner that straightened keeps its document length as a fraction of +/// `after`'s length, and a corner that bent again takes that length back as a fraction of its new +/// maximum. Other radii are left as they are. +pub fn rebase_relative_radii(before: &PathData, after: &PathData, radii: &mut [f64]) { + let (old_corners, new_corners) = (path_corners(before), path_corners(after)); + let (old_dormant_scale, new_dormant_scale) = (dormant_radius_scale(before), dormant_radius_scale(after)); + for (index, r) in radii.iter_mut().enumerate() { + let old = old_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &old_corners[i]); + let new = new_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &new_corners[i]); + match (old, new) { + (Some(c), None) => *r = (*r).clamp(0.0, 1.0) * c.max_radius() / new_dormant_scale, + (None, Some(c)) => *r = (*r * old_dormant_scale / c.max_radius()).clamp(0.0, 1.0), + _ => {} + } + } +} + /// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the /// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors, /// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a /// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map /// the anchors as drawn to the corners they come from. /// Returns `None`, leaving the path unchanged, when the path has no live shape or -/// no cut corner, or is a rectangle sheared or scaled unevenly. +/// no corner with a radius, or is a rectangle sheared or scaled unevenly. pub fn edit_corner_anchors( path: &mut PathData, live: &mut Option>, @@ -307,9 +333,11 @@ pub fn edit_corner_anchors( return None; } } - let (mut base, moved, radii, kinds, relative) = { + let (mut base, moved, mut radii, kinds, relative) = { let lc = LiveCorners::new(path, live.as_deref())?; - if !lc.drawn.iter().any(|r| *r > 0.0) { + // The stored radii decide, not the drawn ones: a corner the edit straightened draws no + // arc but keeps its radius, and rounds again when a later edit bends it. + if !lc.radii.iter().any(|r| *r > 0.0) { return None; } let moved: BTreeSet = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect(); @@ -330,7 +358,11 @@ pub fn edit_corner_anchors( k += 1; } } + let before = relative.then(|| base.clone()); edit(&mut base, &on_base); + if let Some(before) = before { + rebase_relative_radii(&before, &base, &mut radii); + } let l = LiveShape::Path { base, radii, kinds, radii_relative: relative }; *path = l.to_path(); *live = Some(Box::new(l)); @@ -423,6 +455,48 @@ mod tests { assert!(!p.transform(Affine::translate((5.0, 0.0))), "a move needs no new cuts"); } + /// Moving the anchor of the only rounded corner into a straight line and back keeps its + /// stored radius, so the corner is rounded again. + #[test] + fn a_straightened_corner_rounds_again_when_it_bends_back() { + let pen = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false)); + let (mut path, mut live) = (pen.clone(), None); + set_corners(&mut path, &mut live, &set(&[1]), Some(10.0), None); + let corner = LiveCorners::new(&path, live.as_deref()).unwrap().anchors_of(&set(&[1])); + let move_corner = |path: &mut PathData, live: &mut Option>, to: Point| { + let sel = LiveCorners::new(path, live.as_deref()).unwrap().anchors_of(&set(&[1])); + let sel = if sel.is_empty() { anchors(&[1]) } else { sel }; + edit_corner_anchors(path, live, &sel, |base, on_base| { + for &(si, ai) in on_base { + if let Some(a) = base.anchor_mut(si, ai) { + (a.p, a.h_in, a.h_out) = (to, to, to); + } + } + }) + }; + assert_eq!(corner.len(), 2, "the corner is cut"); + // Straight: the corner has nothing to cut. + assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some()); + assert!(matches!(live.as_deref(), Some(LiveShape::Path { radii, .. }) if radii.get(1) == Some(&10.0))); + assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0, "the straight corner draws no arc"); + // Bent again: the stored radius cuts it again. + assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some(), "the straightened corner stays live"); + let c = LiveCorners::new(&path, live.as_deref()).unwrap(); + assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius: {live:?}"); + + for relative in [true, false] { + assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some()); + assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0); + let l = live.as_deref_mut().unwrap(); + convert_radii_relative(l, relative); + assert_eq!(l.radii_relative(), relative); + path = l.to_path(); + assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some()); + let c = LiveCorners::new(&path, live.as_deref()).unwrap(); + assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius after changing modes: {live:?}"); + } + } + #[test] fn relative_radii_scale_with_rectangle_size() { let l = LiveShape::Rectangle { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index dc1e082ac0..7fdcf3a784 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -318,7 +318,7 @@ impl Document { /// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as /// [`Document::index_path`] finds it. pub fn node(&self, id: NodeId) -> Option<&Node> { - if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) { + if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id).or_else(|| cached.added_node_in(&self.layers, id))) { crate::id_index::note_path_lookup(); return Some(n); } @@ -365,10 +365,21 @@ impl Document { Some(None) => return self.walk_index_path(id), _ => {} } + let stale = cached.contains_key(&id); + // An id the table doesn't have, at the path an earlier walk found for it, while the node + // there still has the id. + if !stale + && let Some(p) = cached.added(&id) + && self.node_at(&p).is_some_and(|n| n.id == id) + { + return Some(p); + } // A stale path (the tree changed) or an id the cache doesn't have (deleted or added // since): walk, and rebuild now and then. let found = self.walk_index_path(id); - let stale = cached.contains_key(&id); + if !stale && let Some(p) = &found { + cached.note_added(id, p); + } if (stale || found.is_some()) && self.index.missed() { self.index.rebuild(&self.layers); } @@ -425,23 +436,37 @@ impl Document { // Cached paths that still check out ([`id_index`]); the rest take one walk. For a good // share of the document, one walk is quicker than checking each cached path. if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { - want.retain(|id| match cache.get(id) { - Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + want.retain(|id| match self.cached_path(&cache, *id) { + Some(p) => { out.insert(*id, p); false } - _ => true, + None => true, }); } if !want.is_empty() { crate::id_index::note_tree_walk(); let mut rest = HashMap::with_capacity(want.len()); walk(&self.layers, &want, &mut Vec::new(), &mut rest); + // The cache keeps the paths of found ids it doesn't have, for the next lookup. + if let Some(cache) = self.index.get().filter(|_| rest.len() <= crate::id_index::ADDED_PATHS) { + rest.iter().for_each(|(id, p)| cache.note_added(*id, p)); + } out.extend(rest); } out } + /// The path the lookup cache `cache` has for `id`, while the node there has the id: the table's + /// path, or for an id the table doesn't have, the path an earlier walk found ([`id_index`]). + fn cached_path(&self, cache: &crate::id_index::Paths, id: NodeId) -> Option> { + let p = match cache.get(&id) { + Some(p) => p?, + None => cache.added(&id)?, + }; + self.node_at(&p).is_some_and(|n| n.id == id).then_some(p) + } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still @@ -452,7 +477,8 @@ impl Document { let want: std::collections::HashSet> = ids.into_iter().collect(); // As in `index_paths`, one walk is quicker than checking the cached paths of a good share // of the document. - if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let cache = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()); + if let Some(cache) = &cache { let mut paths = Vec::with_capacity(want.len()); let cached = want.iter().all(|id| match cache.get(id) { Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { @@ -476,6 +502,10 @@ impl Document { out.push(n); } }); + // Found ids the table doesn't have count toward a rebuild for later ordered lookups. + if cache.is_some_and(|cache| out.iter().any(|n| !cache.contains_key(&n.id))) && self.index.missed() { + self.index.rebuild(&self.layers); + } } out } @@ -584,10 +614,14 @@ impl Document { /// Remove a node and return it. pub fn remove(&mut self, id: NodeId) -> Result, DocError> { - let parent = self.parent_of(id); let path = self.index_path(id).ok_or(DocError::NoNode(id))?; - let idx = *path.last().ok_or(DocError::NoNode(id))?; - let ch = self.children_mut(parent)?; + self.remove_at(id, &path) + } + + /// Remove the node at `path`, the index path [`Document::index_path`] gave for `id`, and return it. + fn remove_at(&mut self, id: NodeId, path: &[usize]) -> Result, DocError> { + let (&idx, up) = path.split_last().ok_or(DocError::NoNode(id))?; + let ch = self.children_at(up).ok_or(DocError::NoNode(id))?; if idx >= ch.len() { return Err(DocError::NoNode(id)); } @@ -602,10 +636,11 @@ impl Document { { return Err(DocError::Invalid("cannot move an object into itself".into())); } - if let Some(n) = self.node(id) { + let path = self.index_path(id).ok_or(DocError::NoNode(id))?; + if let Some(n) = self.node_at(&path) { self.check_ruler_guide_place(n, parent)?; } - let n = self.remove(id)?; + let n = self.remove_at(id, &path)?; let ch = self.children_mut(parent)?; let i = Node::insert_index(ch, index, &n); ch.insert(i, n); @@ -623,9 +658,15 @@ impl Document { /// Position of `id` within its parent: (parent, index, sibling count). pub fn position(&self, id: NodeId) -> Option<(Option, usize, usize)> { - let parent = self.parent_of(id); - let idx = *self.index_path(id)?.last()?; - let n = self.children(parent)?.len(); + let path = self.index_path(id)?; + let (&idx, up) = path.split_last()?; + let (parent, n) = match up { + [] => (None, self.layers.len()), + _ => { + let parent = self.node_at(up)?; + (Some(parent.id), parent.children()?.len()) + } + }; Some((parent, idx, n)) } diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 0e1673580a..05f899efac 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -4,10 +4,15 @@ //! The tree is edited in many places through public fields, so the cache can't be kept in step //! with it. It is checked instead: a cached path is used only while the node at that path still //! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache, -//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before. +//! and an id the cache doesn't have (added since, or removed) is looked up by walking. //! An id that appears more than once (a damaged file) is never cached, so lookups keep returning //! its first place in tree order. //! +//! The path a walk finds for an id the table doesn't have is kept beside the table, shared by every +//! document that reads it, and checked the same way before it is used. Documents that each start +//! from the same copy and add the same object (every preview of a drag starts from the document as +//! it was at the press) then find that object without walking the tree. +//! //! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache //! places each node after a removed sibling one lower and finds no path for a removed node or one //! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first @@ -16,8 +21,10 @@ //! The one case a cached lookup can answer differently from a walk: a second node with an //! existing id put in the tree *after* the cache was built, earlier in tree order than the first. //! The lookup then returns the original node (also one with that id) instead of the new one. The -//! app never makes such a node (paste and duplicate give new ids, undo restores whole trees); -//! duplicated ids come from damaged files, which are cached afresh when opened. +//! same holds for an id the table doesn't have: once a walk in one document has found it, a copy +//! that holds a second node with that id earlier in tree order gets the node at the path the walk +//! found. The app never makes such a node (paste and duplicate give new ids, undo restores whole +//! trees); duplicated ids come from damaged files, which are cached afresh when opened. use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hasher}; @@ -65,8 +72,15 @@ type Gaps = HashMap>; pub(crate) struct Paths { table: Arc, gaps: Arc, + /// The index paths that walks found for ids the table doesn't have, at most [`ADDED_PATHS`] of + /// them. Every document that reads the table reads them too, and checks a path against its own + /// tree before using it. + added: Arc>>>, } +/// The most paths [`Paths`] keeps for ids its table doesn't have; one more lets the kept ones go. +pub(crate) const ADDED_PATHS: usize = 4096; + /// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level /// layer) and its index among its siblings. One flat table, so building it allocates nothing per /// node. @@ -152,6 +166,36 @@ impl Paths { Err(k) => Some(i - k as u32), } } + /// The index path a walk found for `id`, an id the table doesn't have ([`Paths::note_added`]); + /// the caller checks that the node there has the id. + pub(crate) fn added(&self, id: &NodeId) -> Option> { + let path = self.added.read().ok()?.get(id)?.clone(); + note_path_copy(); + Some(path) + } + /// The node with `id` in `layers` at the path [`Paths::added`] has for it, found without copying + /// the path: `None` when there is none or the node there does not have the id. + pub(crate) fn added_node_in<'a>(&self, layers: &'a [Arc], id: NodeId) -> Option<&'a Node> { + let added = self.added.read().ok()?; + let (first, rest) = added.get(&id)?.split_first()?; + let mut node: &Node = layers.get(*first)?; + for &i in rest { + node = node.children()?.get(i)?; + } + (node.id == id).then_some(node) + } + /// Keep `path`, which a walk found for `id`, when the table doesn't have `id`. Past + /// [`ADDED_PATHS`] ids, the kept paths are let go first. + pub(crate) fn note_added(&self, id: NodeId, path: &[usize]) { + if self.table.ids.contains_key(&id) { + return; + } + let Ok(mut added) = self.added.write() else { return }; + if added.len() >= ADDED_PATHS && !added.contains_key(&id) { + added.clear(); + } + added.insert(id, path.to_vec()); + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -297,7 +341,7 @@ impl IdIndex { note_tree_walk(); let mut table = Table::default(); walk(layers, u32::MAX, &mut table); - let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() }); + let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default(), added: Arc::default() }); if let Ok(mut g) = self.0.write() { *g = Some(out.clone()); } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 059a3d4bdc..7bddc2c482 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -103,7 +103,7 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use compound_shape::ShapeMode; -pub use corners::{LiveCorners, edit_corner_anchors}; +pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii}; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, 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/src/catalog.rs b/crates/effects/src/catalog.rs index b6131adb53..7a6663b603 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -262,7 +262,7 @@ pub fn effect_catalog() -> Vec { ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 883366a97f..6a9ddfbbff 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1013,6 +1013,12 @@ fn solid_items(shape: &Profile) -> impl Iterator { shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i) } +/// The fills and strokes 3D effect `id` draws for `shapes`: every one for Rotate, which draws a +/// plane for each ([`meshes_for`]), and [`solid_items`] for the other effects. +fn drawn_items<'a>(id: &str, shapes: &'a [Profile]) -> Box + 'a> { + if is_plane(id) { Box::new(shapes.iter().flat_map(|s| s.items.iter())) } else { Box::new(shapes.iter().flat_map(solid_items)) } +} + /// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes, /// a group's members from the back up, each with its shape's opacity, the region it paints and its /// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any): @@ -2086,7 +2092,7 @@ fn art_for( { let image = if rendered::reshapes_paths_only(later) { Err(rendered::PATHS_ONLY.into()) - } else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(solid_items), has_masks(shapes)) { + } else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) { meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { let lighting = rendered::lighting(&fx.id, &p); let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 275a747edc..403991b6ca 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -70,7 +70,7 @@ const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::IN fn rendered_eligibility_ignores_fills_below_the_top_fill() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let doc = vectorcraft_doc::Document::new(400.0, 400.0); - for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + for id in [super::super::EXTRUDE, super::super::INFLATE] { let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new( @@ -85,6 +85,28 @@ fn rendered_eligibility_ignores_fills_below_the_top_fill() { } } +/// Rotate draws a plane for every fill and stroke, so a gradient fill below the top fill keeps it +/// from rendering, as a gradient top fill does. +#[test] +fn rotate_rendered_eligibility_checks_every_fill() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + assert_eq!(crate::rendered_warning(&doc, &n), None); + assert_eq!(images(&drawn(&n)).len(), 1); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + stops, + )))))); + for at in [0, 1] { + let mut n = n.clone(); + n.appearance.items.insert(at, lower.clone()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "gradient fill at {at}"); + assert!(images(&drawn(&n)).is_empty(), "gradient fill at {at}"); + } +} + #[test] fn later_pathfinder_uses_shaded_faces_and_reports_the_fallback() { let doc = vectorcraft_doc::Document::new(400.0, 400.0); diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 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..982b3cd757 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -0,0 +1,206 @@ +//! 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; + } + // A last anchor on the first one only closes the path: the check above has kept its handles on that + // point, so the corners are read without it. + let m = if sp.anchors[n - 1].p == sp.anchors[0].p { n - 1 } else { n }; + let points: Vec = sp + .anchors + .iter() + .take(m) + .enumerate() + .filter_map(|(i, a)| { + let prev = sp.anchors[(i + m - 1) % m].p; + let next = sp.anchors[(i + 1) % m].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..492af2a371 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -0,0 +1,336 @@ +//! 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 a_closing_anchor_on_the_first_one_does_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 corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + for reverse in [false, true] { + let mut points = corners.to_vec(); + if reverse { + points.reverse(); + } + points.push(points[0]); + 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}), "reverse: {reverse}"); + 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/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index d5f241b4ee..8f4def2dcd 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -1,9 +1,10 @@ //! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the -//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path -//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork -//! Cleanup, are the UI's. +//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup, Release All +//! Containers ([`release`]) and Rejoin Path Pieces, and its text tools ([`text`]). Its panel and +//! its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's. mod checks; +mod release; #[cfg(test)] mod tests; mod text; @@ -87,6 +88,7 @@ pub fn specs() -> Vec { rejoin ), ]; + v.extend(release::specs()); v.extend(text::specs()); v } diff --git a/crates/engine/src/cmd/addons/cleanup/release.rs b/crates/engine/src/cmd/addons/cleanup/release.rs new file mode 100644 index 0000000000..2e09151866 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/release.rs @@ -0,0 +1,422 @@ +//! Artwork Cleanup's Release All Containers (`addon.cleanup.releaseAll`): every group, clipping +//! mask and compound path in the selection, the objects named or the whole document, taken apart +//! at every level of nesting as one undo step, so that only the objects they held are left. + +#[cfg(test)] +mod tests; + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_tools::builder::is_live_paint; + +use super::checks::{MAX_OBJECTS, Scope}; +use super::{named, retain_targets, scope_of}; +use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The command. +const COMMAND: &str = "addon.cleanup.releaseAll"; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.cleanup.releaseAll", + "Release All Containers…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), ids?: [id…] (the objects, groups and layers to release in, instead of `scope`; duplicate ids are an error), groups?: bool (true: groups are ungrouped), clipGroups?: bool (true: clipping groups are ungrouped and layers stop clipping unless their clipping path or clipped artwork overlaps a locked artboard, their released clipping paths kept as plain paths), compoundPaths?: bool (true: compound paths, and paths of several subpaths, become one path per subpath); at least one of the three true; `scope` and the three are never null} take apart every container of the kinds asked for, at every level of nesting, as one undo step when one goes; layers stay; each object keeps the opacity of the groups and compound paths it was in, and a compound path's paths take its paint; objects with live effects on their appearance or fill and stroke rows, groups with fill or stroke rows of their own, objects with an opacity mask, compound shapes, Live Paint groups, graphs, dimensions, flares, Objects on Path, generated art, Shaper Groups, Image Trace objects, paths with Live Corners, blends, envelopes, repeats, intertwines and other live objects stay whole, including directly selected or named descendants; the entire clipping mask subtree of a clipping group or layer that stays is left as it is, including directly selected or named descendants; from the selection or the document, locked and hidden objects, and objects on a locked artboard, stay whole; named by `ids`, locked and hidden ones are taken apart too (their objects become locked or hidden as they were), but not those on a locked artboard; the selection keeps what it held, each object taken apart replaced by what it left, locked and hidden objects left out → {scope (\"selection\", \"document\" or \"ids\"), ids (the objects selected), groups, clipGroups, compoundPaths (how many of each were released)}", + has_doc, + release_all + )] +} + +/// The kinds of container a request takes apart. +#[derive(Clone, Copy)] +struct Kinds { + groups: bool, + clips: bool, + compounds: bool, +} + +impl Kinds { + /// Whether a group is taken apart: a clipping group (`clip`) with `clips`, another with `groups`. + fn takes_group(self, clip: bool) -> bool { + if clip { self.clips } else { self.groups } + } +} + +/// One run over the objects: what it takes apart and what it found. +struct Release<'a> { + kinds: Kinds, + /// Locked and hidden objects are taken apart too. + named: bool, + /// The artwork on a locked artboard, which stays whole. + held: &'a HashSet, + /// Groups, clipping groups and layers, and compound paths released. + counts: [usize; 3], + /// Objects made from the containers taken apart. + made: usize, + /// Each container taken apart and the objects left in its place. + left: HashMap>, +} + +/// Whether `n` stays whole whatever is asked: a live object kept as a group or compound path +/// (a compound shape, Live Paint group, graph, dimension, flare, Objects on Path, generated art, +/// Shaper Group, Image Trace object, a clipping path's painted pieces), a path with Live Corners, +/// whose parts would lose their editable corners, one with an opacity mask or live effects +/// on its appearance or fill and stroke rows, or a group with fill or stroke rows of its own. +fn live(n: &Node) -> bool { + let x = n.extras(); + matches!(&n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. }) + || matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. })) + || !n.appearance.effects.is_empty() + || n.appearance.items.iter().any(|item| !item.effects().is_empty()) + || x.mask.is_some() + || x.shaper.is_some() + || x.trace.is_some() + || x.graph.is_some() + || x.dimension.is_some() + || x.flare.is_some() + || x.objects_on_path.is_some() + || x.generated.is_some() + || x.live_paint_gaps.is_some() + || x.clip_pieces + || (matches!(&n.kind, NodeKind::Group { .. }) && !n.appearance.items.is_empty()) + || n.is_compound_shape() + || is_live_paint(n) +} + +/// The artwork under `n` is added to `out`. +fn candidates(n: &Node, clips: bool, out: &mut Vec) { + let candidate = match &n.kind { + NodeKind::Layer { .. } => false, + NodeKind::Group { .. } | NodeKind::Compound { .. } => true, + NodeKind::Path { path, .. } => clips || path.subpaths.len() > 1, + _ => clips, + }; + if candidate { + out.push(n.id); + } + if let Some(children) = n.children() { + children.iter().for_each(|c| candidates(c, clips, out)); + } +} + +impl Release<'_> { + fn total(&self) -> usize { + self.counts.iter().sum() + } + + /// Whether `n` is left as it is: locked or hidden (unless named), on a locked artboard, or live. + fn keeps(&self, n: &Node) -> bool { + (!self.named && (n.locked || !n.visible)) || self.held.contains(&n.id) || live(n) + } + + /// `n` with the containers in it released, into `out`; `member` counts what a container left. + fn node(&mut self, d: &mut Document, n: Arc, member: bool, out: &mut Vec>) -> Result<()> { + if self.keeps(&n) { + if member { + self.made(1)?; + } + out.push(n); + return Ok(()); + } + match &n.kind { + NodeKind::Group { clip, .. } if self.kinds.takes_group(*clip) => { + let clip = *clip; + self.counts[usize::from(clip)] += 1; + self.take_apart(d, n, clip, false, out) + } + NodeKind::Compound { .. } if self.kinds.compounds => { + self.counts[2] += 1; + self.take_apart(d, n, false, true, out) + } + NodeKind::Path { path, clipping: false, guide: false, .. } if self.kinds.compounds && path.subpaths.len() > 1 => { + self.counts[2] += 1; + self.split(d, (*n).clone(), out) + } + NodeKind::Group { .. } | NodeKind::Layer { .. } => self.keep(d, n, member, out), + _ => { + if member { + self.made(1)?; + } + out.push(n); + Ok(()) + } + } + } + + /// Group or compound path `n` replaced by its members, released in turn. Members take on the + /// container's opacity, are hidden when it was hidden and locked when it was locked; a + /// compound path's take its paint; a clipping group's clipping path becomes a plain path. + fn take_apart(&mut self, d: &mut Document, n: Arc, clip: bool, compound: bool, out: &mut Vec>) -> Result<()> { + let Some(children) = n.children() else { return Ok(()) }; + let mut parts = vec![]; + for (k, c) in children.iter().enumerate() { + let mut c = (**c).clone(); + if clip + && k == 0 + && let NodeKind::Path { clipping, .. } = &mut c.kind + { + *clipping = false; + } + if compound { + c.appearance = n.appearance.clone(); + if n.extras().pixel_aligned { + c.extras_mut().pixel_aligned = true; + } + } + c.opacity *= n.opacity; + c.visible &= n.visible; + c.locked |= n.locked; + self.node(d, Arc::new(c), true, &mut parts)?; + } + self.left.insert(n.id, parts.iter().map(|p| p.id).collect()); + out.extend(parts); + Ok(()) + } + + /// Path `n` of several subpaths as one path per subpath with its paint, in the same stacking + /// order; the first keeps its id. + fn split(&mut self, d: &mut Document, n: Node, out: &mut Vec>) -> Result<()> { + let Some(path) = n.path_data() else { return Ok(()) }; + if self.made.saturating_add(path.subpaths.len()) > MAX_OBJECTS { + return Err(EngineError::Other("Release All Containers: too many objects to release at once".into())); + } + let mut template = n.clone(); + if let NodeKind::Path { path, live, .. } = &mut template.kind { + (*path, *live) = (PathData::single(Default::default()), None); + } + let mut parts = Vec::with_capacity(path.subpaths.len()); + for (k, sp) in path.subpaths.iter().enumerate() { + let mut c = if k == 0 { template.clone() } else { d.reid(&template) }; + if let NodeKind::Path { path, live, .. } = &mut c.kind { + (*path, *live) = (PathData::single(sp.clone()), None); + } + parts.push(Arc::new(c)); + } + self.made(parts.len())?; + self.left.insert(n.id, parts.iter().map(|p| p.id).collect()); + out.extend(parts); + Ok(()) + } + + /// Group or layer `n` kept, with the containers in it released. A layer stops clipping when + /// clipping groups are released; the clipping path of a group or layer that still clips is + /// left as it is. Unchanged, `n` itself goes to `out`. + fn keep(&mut self, d: &mut Document, mut n: Arc, member: bool, out: &mut Vec>) -> Result<()> { + if member { + self.made(1)?; + } + let before = self.total(); + let mut clips = n.clips(); + if clips && n.is_layer() && self.kinds.clips && !n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c))) { + self.counts[1] += 1; + let n = Arc::make_mut(&mut n); + n.set_clips(false); + clips = false; + if let Some(first) = n.children_mut().and_then(|c| c.first_mut()) + && let NodeKind::Path { clipping, .. } = &mut Arc::make_mut(first).kind + { + *clipping = false; + } + } + let Some(children) = n.children() else { + out.push(n); + return Ok(()); + }; + let mut kept = Vec::with_capacity(children.len()); + for (k, c) in children.iter().enumerate() { + if clips && k == 0 { + if member { + self.made(1)?; + } + kept.push(Arc::clone(c)); + } else { + self.node(d, Arc::clone(c), member, &mut kept)?; + } + } + if self.total() != before + && let Some(ch) = Arc::make_mut(&mut n).children_mut() + { + *ch = kept; + } + out.push(n); + Ok(()) + } + + fn holds_art(&self, n: &Node) -> bool { + self.held.contains(&n.id) || n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c))) + } + + /// Counts the objects made, refusing a run that makes too many. + fn made(&mut self, count: usize) -> Result<()> { + self.made += count; + if self.made > MAX_OBJECTS { + return Err(EngineError::Other("Release All Containers: too many objects to release at once".into())); + } + Ok(()) + } + + /// `id`, or the objects left in its place when it was taken apart. + fn replaced(&self, id: NodeId, into: &mut Vec) { + match self.left.get(&id) { + Some(ids) => into.extend(ids), + None => into.push(id), + } + } +} + +/// Whether shown artwork in `n` overlaps a locked artboard: a plain group that is not live +/// ([`live`]) by its shown members, anything else by its own bounds. +fn shows_on(locks: &LockedArtboards<'_>, n: &Node) -> bool { + if !n.visible { + return false; + } + match (&n.kind, n.children()) { + (NodeKind::Group { clip: false, .. }, Some(children)) if !live(n) => children.iter().any(|c| shows_on(locks, c)), + _ => locks.holds(n), + } +} + +/// Whether `id` is in the clipping mask subtree of a clipping group or layer. +fn in_clipping_mask(d: &Document, id: NodeId) -> bool { + d.ancestry(id).is_some_and(|chain| { + chain + .windows(2) + .any(|pair| d.node(pair[0]).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == pair[1]))) + }) +} + +fn release_all(s: &mut Session, p: &Value) -> Result { + if !p.is_object() { + return Err(bad(COMMAND, "parameters must be an object")); + } + for key in ["groups", "clipGroups", "compoundPaths"] { + if p.get(key).is_some_and(|v| !v.is_boolean()) { + return Err(bad(COMMAND, format!("`{key}` must be true or false"))); + } + } + if p.get("scope").is_some_and(|v| !matches!(v.as_str(), Some("selection" | "document"))) { + return Err(bad(COMMAND, "`scope` must be \"selection\" or \"document\"")); + } + if let Some(ids) = p.get("ids").filter(|v| !v.is_null()) { + let ids = ids.as_array().ok_or_else(|| bad(COMMAND, "`ids` must be an array of non-negative integer object ids"))?; + let mut seen = HashSet::new(); + for id in ids { + let id = id.as_u64().ok_or_else(|| bad(COMMAND, "`ids` must contain non-negative integer object ids"))?; + if !seen.insert(id) { + return Err(bad(COMMAND, format!("duplicate object id {id} in `ids`"))); + } + } + } + let kinds = Kinds { + groups: switch_or(p, "groups", true, COMMAND)?, + clips: switch_or(p, "clipGroups", true, COMMAND)?, + compounds: switch_or(p, "compoundPaths", true, COMMAND)?, + }; + if !(kinds.groups || kinds.clips || kinds.compounds) { + return Err(bad(COMMAND, "`groups`, `clipGroups` and `compoundPaths` are all false: there is nothing to release")); + } + let named = named(p); + if named && p.get("scope").is_some() { + return Err(bad(COMMAND, "give `scope` or `ids`, not both")); + } + let (roots, name) = if named { + let mut roots = checked_ids_or_selection(s, p, COMMAND)?; + retain_targets(&s.doc()?.doc, &mut roots, true, |id| *id); + (roots, "ids") + } else { + match scope_of(s, p, COMMAND)? { + (Scope::Document, name) => (s.doc()?.doc.layers.iter().map(|l| l.id).collect(), name), + (Scope::Objects(mut roots), name) => { + retain_targets(&s.doc()?.doc, &mut roots, false, |id| *id); + (roots, name) + } + } + }; + let st = s.doc()?; + let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone()); + // The artwork on a locked artboard, found while nothing is changed yet. + let held: HashSet = if d.artboards.iter().any(|a| a.locked) { + let mut found = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + candidates(n, kinds.clips, &mut found); + } + let locks = d.locked_artboards(); + let mut held: HashSet = found.iter().copied().filter(|id| locks.holds_id(*id)).collect(); + // A shown clipping group whose clipped artwork overlaps a locked artboard stays whole, + // wherever its clipping path lies, when clipping groups are released; the clipping groups + // the targets are in count too. + let ancestors = roots.iter().filter_map(|id| d.ancestry(*id)).flatten(); + let clip_groups: HashSet = found + .iter() + .copied() + .chain(ancestors) + .filter(|id| kinds.clips && d.node(*id).is_some_and(|n| matches!(&n.kind, NodeKind::Group { clip: true, .. }))) + .collect(); + // Pattern editing mode's art is on no artboard. + let pattern_layer = d.pattern_edit.as_ref().map(|e| e.layer); + for id in clip_groups { + let shown = d.ancestry(id).is_some_and(|chain| chain.iter().all(|a| Some(*a) != pattern_layer && d.node(*a).is_some_and(|n| n.visible))); + if shown + && let Some(n) = d.node(id) + && n.children().is_some_and(|c| c.iter().skip(1).any(|c| shows_on(&locks, c))) + { + held.insert(id); + } + } + held + } else { + HashSet::new() + }; + let mut run = Release { kinds, named, held: &held, counts: [0; 3], made: 0, left: HashMap::new() }; + let mut items = vec![]; + for id in roots { + // Direct targets inside a live object or clipping mask stay whole. + let protected = + d.ancestry(id).is_some_and(|chain| chain.iter().take(chain.len().saturating_sub(1)).filter_map(|id| d.node(*id)).any(|n| run.keeps(n))); + if in_clipping_mask(&d, id) || protected { + continue; + } + let Some(n) = d.node_arc(id).cloned() else { continue }; + let before = run.total(); + let mut out = vec![]; + run.node(&mut d, n, false, &mut out)?; + if run.total() != before { + items.push((id, out.into_iter().map(Arc::unwrap_or_clone).collect())); + } + } + let [groups, clips, compounds] = run.counts; + // With nothing to release, the document, the selection and the undo history stay as they are. + if run.total() == 0 { + let ids: Vec = sel.objects.iter().map(|i| i.0).collect(); + return Ok(json!({ "scope": name, "ids": ids, "groups": 0, "clipGroups": 0, "compoundPaths": 0 })); + } + d.insert_beside(items, true)?; + let mut ids = vec![]; + for id in sel.objects.iter() { + run.replaced(*id, &mut ids); + } + // Locked and hidden objects, and those in locked or hidden groups, are not selected. + { + let editable = d.editable(); + ids.retain(|id| editable(*id)); + } + let kept: HashSet = ids.iter().copied().collect(); + let removed: Vec = sel.objects.iter().copied().filter(|id| run.left.contains_key(id) || !kept.contains(id)).collect(); + sel.remove_all(removed); + let mut seen = HashSet::new(); + sel.objects = ids.into_iter().filter(|id| seen.insert(*id)).collect(); + sel.prune(&d); + let ids: Vec = sel.objects.iter().map(|i| i.0).collect(); + s.edit("Release All Containers", |doc, selection| { + *doc = d; + *selection = sel; + Ok(()) + })?; + Ok(json!({ "scope": name, "ids": ids, "groups": groups, "clipGroups": clips, "compoundPaths": compounds })) +} diff --git a/crates/engine/src/cmd/addons/cleanup/release/tests.rs b/crates/engine/src/cmd/addons/cleanup/release/tests.rs new file mode 100644 index 0000000000..991e74f854 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/release/tests.rs @@ -0,0 +1,860 @@ +//! Release All Containers: every level taken apart as one undo step, the kinds asked for only, +//! the selection, the document and named objects, clipping layers, what stays whole, and refusals. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, LiveShape, Node, NodeId, NodeKind}; + +use crate::Session; + +const C: &str = "addon.cleanup.releaseAll"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).cloned() +} + +fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) { + s.edit("t", |d, _| { + f(d.node_mut(id).unwrap()); + Ok(()) + }) + .unwrap(); +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.to_vec() +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The objects directly in layer `k`. +fn layer(s: &Session, k: usize) -> Vec { + s.doc().unwrap().doc.layers[k].children().unwrap().iter().map(|n| n.id).collect() +} + +fn group(s: &mut Session, ids: &[NodeId]) -> NodeId { + select(s, ids); + id_of(&s.execute("object.group", &json!({})).unwrap()) +} + +fn compound(s: &mut Session, ids: &[NodeId]) -> NodeId { + select(s, ids); + id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()) +} + +/// A clipping group of `ids`, the last of them the clipping path. +fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId { + select(s, ids); + id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()) +} + +fn counts(r: &Value) -> (u64, u64, u64) { + (r["groups"].as_u64().unwrap(), r["clipGroups"].as_u64().unwrap(), r["compoundPaths"].as_u64().unwrap()) +} + +fn plain(s: &Session, id: NodeId) -> bool { + matches!(node(s, id).unwrap().kind, NodeKind::Path { clipping: false, ref path, .. } if path.subpaths.len() == 1) +} + +fn red() -> Appearance { + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0) +} + +#[test] +fn release_all_takes_apart_every_level_as_one_step() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let p = rect(&mut s, 70.0, 10.0); + let q = rect(&mut s, 75.0, 15.0); + let holes = compound(&mut s, &[p, q]); + change(&mut s, holes, |n| n.appearance = red().into()); + let inner = group(&mut s, &[b, holes]); + change(&mut s, inner, |n| n.opacity = 0.5); + let clipped = rect(&mut s, 110.0, 10.0); + let clip = rect(&mut s, 105.0, 5.0); + let masked = clip_group(&mut s, &[clipped, clip]); + let outer = group(&mut s, &[a, inner, masked]); + select(&mut s, &[outer]); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(counts(&r), (2, 1, 1), "{r}"); + assert_eq!(r["scope"], "selection"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Release All Containers"); + assert_eq!(layer(&s, 0), [a, b, p, q, clip, clipped], "only paths are left, in their stacking order"); + assert!([a, b, p, q, clip, clipped].iter().all(|id| plain(&s, *id)), "the clipping path is a plain path"); + assert!(node(&s, outer).is_none() && node(&s, inner).is_none() && node(&s, holes).is_none() && node(&s, masked).is_none()); + assert_eq!((node(&s, b).unwrap().opacity, node(&s, p).unwrap().opacity), (0.5, 0.5), "members keep their groups' opacity"); + assert_eq!(*node(&s, q).unwrap().appearance, red(), "a compound path's paths take its paint"); + assert_eq!(selected(&s), [a, b, p, q, clip, clipped], "what the selected group left is selected"); + assert_eq!(r["ids"], json!([a.0, b.0, p.0, q.0, clip.0, clipped.0])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer(&s, 0), [outer]); +} + +#[test] +fn release_all_counts_each_object_left_once() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let c = rect(&mut s, 70.0, 10.0); + let p = rect(&mut s, 100.0, 10.0); + let second = node(&s, p).unwrap().path_data().unwrap().subpaths[0].clone(); + change(&mut s, p, |n| { + if let NodeKind::Path { path, .. } = &mut n.kind { + path.subpaths.push(second); + } + }); + let inner = group(&mut s, &[a, b, c, p]); + change(&mut s, inner, |n| n.set_clips(true)); + let middle = group(&mut s, &[inner]); + let outer = group(&mut s, &[middle]); + let held = std::collections::HashSet::new(); + for clips in [true, false] { + let mut d = (*s.doc().unwrap().doc).clone(); + let n = d.node_arc(outer).unwrap().clone(); + let mut run = super::Release { + kinds: super::Kinds { groups: true, clips, compounds: true }, + named: false, + held: &held, + counts: [0; 3], + made: 0, + left: std::collections::HashMap::new(), + }; + let mut out = vec![]; + run.node(&mut d, n, false, &mut out).unwrap(); + if clips { + assert_eq!(out.len(), 5); + assert_eq!(run.made, out.len(), "each path is counted once"); + } else { + assert_eq!(out.len(), 1); + let children = out[0].children().unwrap(); + assert_eq!(children.len(), 5); + assert_eq!(run.made, out.len() + children.len(), "the kept group and its paths are counted once"); + } + } +} + +#[test] +fn release_all_takes_only_the_kinds_asked_for() { + let mut s = session(); + let p = rect(&mut s, 10.0, 10.0); + let q = rect(&mut s, 15.0, 15.0); + let holes = compound(&mut s, &[p, q]); + let clipped = rect(&mut s, 110.0, 10.0); + let e = rect(&mut s, 105.0, 5.0); + let f = rect(&mut s, 108.0, 8.0); + let clip = compound(&mut s, &[e, f]); + let masked = clip_group(&mut s, &[clipped, clip]); + let outer = group(&mut s, &[holes, masked]); + // Without groups, the group stays and what is inside it is still released, but for the + // clipping path of the clipping group that stays. + select(&mut s, &[outer]); + let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap(); + assert_eq!(counts(&r), (0, 0, 1), "{r}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(p), Some(outer)); + assert!(d.node(holes).is_none() && d.node(clip).is_some() && d.node(masked).is_some()); + assert_eq!(selected(&s), [outer]); + // Without compound paths, the groups go and the compound path stays. + let r = s.execute(C, &json!({"compoundPaths": false})).unwrap(); + assert_eq!(counts(&r), (1, 1, 0), "{r}"); + assert_eq!(layer(&s, 0), [p, q, clip, clipped]); + assert!(matches!(node(&s, clip).unwrap().kind, NodeKind::Compound { .. })); + // Then only compound paths: the clipping path's paths, unpainted as it was. + select(&mut s, &[clip]); + let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap(); + assert_eq!(counts(&r), (0, 0, 1), "{r}"); + assert_eq!(layer(&s, 0), [p, q, e, f, clipped]); +} + +#[test] +fn release_all_splits_paths_of_several_subpaths() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone(); + change(&mut s, a, |n| { + if let NodeKind::Path { path, .. } = &mut n.kind { + path.subpaths.push(second); + } + }); + s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap(); + select(&mut s, &[a]); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(counts(&r), (0, 0, 1), "{r}"); + let left = layer(&s, 0); + assert_eq!(left.len(), 2); + assert_eq!(left[0], a, "the first subpath keeps the path's id"); + assert!(left.iter().all(|id| plain(&s, *id))); + assert_eq!(selected(&s), left); + assert_eq!(node(&s, left[1]).unwrap().appearance, node(&s, a).unwrap().appearance, "each part keeps the path's paint"); +} + +#[test] +fn release_all_keeps_a_path_of_several_subpaths_with_live_corners_whole() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let plain_path = rect(&mut s, 80.0, 10.0); + let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone(); + for id in [a, plain_path] { + let second = second.clone(); + change(&mut s, id, |n| { + if let NodeKind::Path { path, live, .. } = &mut n.kind { + path.subpaths.push(second); + *live = None; + } + }); + } + change(&mut s, a, |n| { + if let NodeKind::Path { path, live, .. } = &mut n.kind { + let base = path.clone(); + *live = Some(Box::new(LiveShape::Path { base, radii: vec![4.0], kinds: vec![], radii_relative: false })); + } + }); + s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap(); + select(&mut s, &[a, plain_path]); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(counts(&r), (0, 0, 1), "only the plain path is split: {r}"); + let kept = node(&s, a).unwrap(); + assert!(matches!(kept.kind, NodeKind::Path { live: Some(_), ref path, .. } if path.subpaths.len() == 2), "Live Corners stay"); + assert_eq!(layer(&s, 0).len(), 3); +} + +#[test] +fn release_all_runs_on_the_document_while_nothing_is_selected() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let c = rect(&mut s, 70.0, 10.0); + let e = rect(&mut s, 100.0, 10.0); + let plain_group = group(&mut s, &[a]); + let locked = group(&mut s, &[b]); + change(&mut s, locked, |n| n.locked = true); + let hidden = group(&mut s, &[c]); + change(&mut s, hidden, |n| n.visible = false); + // A second layer that clips its art by its first path. + let second = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let mask = rect(&mut s, 0.0, 100.0); + let art = rect(&mut s, 10.0, 110.0); + let art_group = group(&mut s, &[art]); + s.edit("t", |d, _| { + let layer = d.node_mut(second).unwrap(); + layer.set_clips(true); + if let Some(NodeKind::Path { clipping, .. }) = layer.children_mut().unwrap().first_mut().map(|c| &mut std::sync::Arc::make_mut(c).kind) { + *clipping = true; + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[]); + assert!(s.execute(C, &json!({"scope": "selection"})).is_err(), "nothing selected"); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r["scope"], "document"); + assert_eq!(counts(&r), (2, 1, 0), "{r}"); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(layer(&s, 0), [a, locked, hidden, e], "locked and hidden groups stay whole"); + assert!(node(&s, plain_group).is_none() && node(&s, art_group).is_none()); + let d = &s.doc().unwrap().doc; + assert!(!d.node(second).unwrap().clips(), "the layer stays and stops clipping"); + assert!(plain(&s, mask), "its clipping path is a plain path"); + assert_eq!(layer(&s, 1), [mask, art]); + assert!(selected(&s).is_empty(), "nothing was selected"); + // Asked for the document with a selection, the selection keeps what it held. + let g = group(&mut s, &[e]); + select(&mut s, &[g]); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (1, 0, 0), "{r}"); + assert_eq!(selected(&s), [e]); +} + +#[test] +fn release_all_takes_named_locked_and_hidden_containers() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let locked = group(&mut s, &[a]); + change(&mut s, locked, |n| n.locked = true); + let hidden = group(&mut s, &[b]); + change(&mut s, hidden, |n| n.visible = false); + select(&mut s, &[locked, hidden]); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "from the selection, they stay whole"); + let r = s.execute(C, &json!({"ids": [locked.0, hidden.0]})).unwrap(); + assert_eq!(r["scope"], "ids"); + assert_eq!(counts(&r), (2, 0, 0), "{r}"); + assert_eq!(undo_steps(&s), steps + 1); + let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap()); + assert!(na.locked && na.visible && !nb.visible && !nb.locked, "their objects become locked or hidden as they were"); + assert!(selected(&s).is_empty(), "locked and hidden objects are not selected"); + // On a locked artboard, a named group stays whole. + let c = rect(&mut s, 10.0, 200.0); + let on_board = group(&mut s, &[c]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({"ids": [on_board.0]})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps)); + assert!(node(&s, on_board).is_some()); + // Nor does one inside a named layer. + let layer_id = s.doc().unwrap().doc.layers[0].id; + let r = s.execute(C, &json!({"ids": [layer_id.0]})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps)); +} + +#[test] +fn release_all_leaves_masked_groups_whole_and_changes_nothing_without_a_container() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 15.0, 15.0); + let held = group(&mut s, &[a, b]); + let m = rect(&mut s, 0.0, 0.0); + s.execute("transparency.makeOpacityMask", &json!({"ids": [held.0, m.0]})).unwrap(); + let masked = layer(&s, 0)[0]; + assert!(node(&s, masked).unwrap().extras().mask.is_some()); + let c = rect(&mut s, 100.0, 10.0); + select(&mut s, &[masked, c]); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "no step when nothing is released"); + assert_eq!(r["ids"], json!([masked.0, c.0]), "the selection stays"); + assert_eq!(layer(&s, 0), [masked, c]); + // A compound shape is a group that stays whole too. + let e = rect(&mut s, 200.0, 10.0); + let f = rect(&mut s, 210.0, 15.0); + select(&mut s, &[e, f]); + s.execute("object.compoundShape.make", &json!({})).unwrap(); + let shape = selected(&s)[0]; + assert!(node(&s, shape).unwrap().is_compound_shape()); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps)); + assert!(node(&s, shape).unwrap().is_compound_shape()); +} + +#[test] +fn release_all_leaves_a_picked_clipping_path_of_a_clipping_group_that_stays() { + let mut s = session(); + let clipped = rect(&mut s, 10.0, 10.0); + let e = rect(&mut s, 5.0, 5.0); + let f = rect(&mut s, 8.0, 8.0); + let clip = compound(&mut s, &[e, f]); + let masked = clip_group(&mut s, &[clipped, clip]); + let steps = undo_steps(&s); + for p in [json!({"ids": [clip.0]}), json!({"ids": [clip.0], "clipGroups": false})] { + let r = s.execute(C, &p).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "{p}"); + } + select(&mut s, &[clip]); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps)); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(clip), Some(masked)); + assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Compound { .. })); +} + +#[test] +fn release_all_keeps_a_directly_named_descendant_of_a_live_object() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let inner = group(&mut s, &[a]); + let sources = group(&mut s, &[inner]); + change(&mut s, sources, |n| n.name = Some("Live Paint Sources".into())); + let live = group(&mut s, &[sources]); + change(&mut s, live, |n| n.name = Some("Live Paint Group".into())); + change(&mut s, sources, |n| n.visible = false); + assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap())); + let steps = undo_steps(&s); + for id in [sources, inner] { + let r = s.execute(C, &json!({"ids": [id.0]})).unwrap(); + assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps)); + assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap())); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner)); + } +} + +#[test] +fn release_all_keeps_appearance_effects_and_directly_targeted_descendants() { + for item in [None, Some(0), Some(1)] { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 15.0, 15.0); + let inner = compound(&mut s, &[a, b]); + let c = rect(&mut s, 20.0, 20.0); + select(&mut s, &[inner, c]); + let applied = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap(); + assert_eq!(applied["grouped"], true); + let live = selected(&s)[0]; + assert!(matches!(node(&s, live).unwrap().kind, NodeKind::Group { clip: false, .. })); + assert!(!node(&s, live).unwrap().is_compound_shape()); + assert_eq!(node(&s, live).unwrap().appearance.effects[0].id, "pathfinder.add"); + if let Some(item) = item { + change(&mut s, live, |n| { + let effects = n.appearance.effects.clone(); + *n.appearance = red(); + *n.appearance.effects_mut(Some(item)).unwrap() = effects; + }); + } + let before = s.doc().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (target, params) in [ + (live, json!({})), + (live, json!({"scope": "document"})), + (live, json!({"ids": [live.0]})), + (inner, json!({})), + (inner, json!({"ids": [inner.0]})), + ] { + select(&mut s, &[target]); + let r = s.execute(C, ¶ms).unwrap(); + assert_eq!(counts(&r), (0, 0, 0), "{item:?}: {params}: {r}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(selected(&s), [target]); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(live)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner)); + } + } +} + +#[test] +fn release_all_keeps_a_layer_mask_over_locked_artboard_artwork() { + for named in [false, true] { + let mut s = session(); + let mask = rect(&mut s, 0.0, 0.0); + let art = rect(&mut s, 10.0, 10.0); + let outside = rect(&mut s, 500.0, 10.0); + let g = group(&mut s, &[outside]); + let layer_id = s.doc().unwrap().doc.layers[0].id; + change(&mut s, layer_id, |n| n.set_clips(true)); + change(&mut s, mask, |n| { + if let NodeKind::Path { clipping, .. } = &mut n.kind { + *clipping = true; + } + }); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) }; + let r = s.execute(C, &p).unwrap(); + assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}"); + assert!(node(&s, layer_id).unwrap().clips()); + assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(layer(&s, 0), [mask, art, outside]); + assert!(node(&s, g).is_none()); + } +} + +#[test] +fn release_all_keeps_a_layer_mask_that_alone_overlaps_a_locked_artboard() { + for named in [false, true] { + let mut s = session(); + let mask = rect(&mut s, 0.0, 0.0); + let outside = rect(&mut s, 500.0, 10.0); + let g = group(&mut s, &[outside]); + let layer_id = s.doc().unwrap().doc.layers[0].id; + change(&mut s, layer_id, |n| n.set_clips(true)); + change(&mut s, mask, |n| { + if let NodeKind::Path { clipping, .. } = &mut n.kind { + *clipping = true; + } + }); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let original_mask = s.doc().unwrap().doc.node_arc(mask).unwrap().clone(); + let steps = undo_steps(&s); + let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) }; + let r = s.execute(C, &p).unwrap(); + assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}"); + assert_eq!(undo_steps(&s), steps + 1); + assert!(node(&s, layer_id).unwrap().clips()); + assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. })); + assert!(std::sync::Arc::ptr_eq(&original_mask, s.doc().unwrap().doc.node_arc(mask).unwrap())); + assert_eq!(layer(&s, 0), [mask, outside]); + assert!(node(&s, g).is_none()); + } +} + +#[test] +fn release_all_keeps_a_clipping_group_whose_clipped_art_overlaps_a_locked_artboard() { + let mut s = session(); + let art = rect(&mut s, 10.0, 10.0); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[art, mask]); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (0, 0, 0), "{r}"); + assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(g)); + assert!(node(&s, g).unwrap().clips()); +} + +#[test] +fn release_all_keeps_a_named_group_in_a_clipping_group_over_a_locked_artboard() { + let mut s = session(); + let art = rect(&mut s, 10.0, 10.0); + let other = rect(&mut s, 40.0, 10.0); + let inner = group(&mut s, &[art, other]); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[inner, mask]); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"ids": [inner.0]})).unwrap(); + assert_eq!(counts(&r), (0, 0, 0), "{r}"); + assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(inner)); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g)); +} + +#[test] +fn release_all_takes_apart_a_named_hidden_clipping_group_with_visible_art() { + let mut s = session(); + let art = rect(&mut s, 10.0, 10.0); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[art, mask]); + change(&mut s, g, |n| n.visible = false); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"ids": [g.0]})).unwrap(); + assert_eq!(counts(&r), (0, 1, 0), "{r}"); + assert!(node(&s, g).is_none()); + assert!(!node(&s, art).unwrap().visible); +} + +#[test] +fn release_all_takes_apart_a_clipping_group_in_a_named_hidden_group() { + let mut s = session(); + let art = rect(&mut s, 10.0, 10.0); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[art, mask]); + let other = rect(&mut s, 40.0, 10.0); + let outer = group(&mut s, &[g, other]); + change(&mut s, outer, |n| n.visible = false); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"ids": [outer.0]})).unwrap(); + assert_eq!(counts(&r), (1, 1, 0), "{r}"); + assert!(node(&s, g).is_none()); +} + +#[test] +fn release_all_ignores_hidden_clipped_art_over_a_locked_artboard() { + let mut s = session(); + let hidden = rect(&mut s, 10.0, 10.0); + let shown = rect(&mut s, 600.0, 10.0); + let inner = group(&mut s, &[hidden, shown]); + change(&mut s, hidden, |n| n.visible = false); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[inner, mask]); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (1, 1, 0), "{r}"); + assert!(node(&s, g).is_none()); + assert!(!node(&s, hidden).unwrap().visible); +} + +#[test] +fn release_all_keeps_a_clipping_group_whose_group_stroke_reaches_a_locked_artboard() { + let mut s = session(); + let a = rect(&mut s, 600.0, 10.0); + let b = rect(&mut s, 640.0, 10.0); + let inner = group(&mut s, &[a, b]); + change(&mut s, inner, |n| n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 500.0).into()); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[inner, mask]); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (0, 0, 0), "{r}"); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g)); +} + +#[test] +fn release_all_ungroups_off_artboard_groups_in_a_kept_clipping_group() { + let mut s = session(); + let a = rect(&mut s, 600.0, 10.0); + let b = rect(&mut s, 640.0, 10.0); + let inner = group(&mut s, &[a, b]); + let on = rect(&mut s, 10.0, 10.0); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[inner, on, mask]); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"scope": "document", "clipGroups": false})).unwrap(); + assert_eq!(counts(&r), (1, 0, 0), "{r}"); + assert!(node(&s, inner).is_none()); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g)); +} + +#[test] +fn release_all_takes_apart_pattern_editing_art_over_a_locked_artboard() { + let mut s = session(); + let art = rect(&mut s, 10.0, 10.0); + let mask = rect(&mut s, 500.0, 10.0); + let g = clip_group(&mut s, &[art, mask]); + select(&mut s, &[]); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + let layer = d.layers[0].id; + d.pattern_edit = Some(vectorcraft_doc::PatternEdit { pattern: "Checks".into(), layer, original: None }); + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (0, 1, 0), "{r}"); + assert!(node(&s, g).is_none()); +} + +#[test] +fn release_all_keeps_a_group_with_its_own_fill_or_stroke() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let g = group(&mut s, &[a, b]); + change(&mut s, g, |n| n.appearance = red().into()); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (0, 0, 0), "{r}"); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g)); + assert_eq!(*node(&s, g).unwrap().appearance, red()); +} + +#[test] +fn release_all_reuses_unchanged_siblings_when_rebuilding_a_layer() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let g = group(&mut s, &[b]); + let original = s.doc().unwrap().doc.node_arc(a).unwrap().clone(); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (1, 0, 0)); + assert!(node(&s, g).is_none()); + assert!(std::sync::Arc::ptr_eq(&original, s.doc().unwrap().doc.node_arc(a).unwrap())); +} + +#[test] +fn release_all_keeps_selection_details_for_untouched_artwork() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let c = rect(&mut s, 70.0, 10.0); + let g = group(&mut s, &[c]); + s.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap(); + let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap(); + s.select(|_, sel| { + sel.set([a, b, g]); + sel.anchors.insert(a, [(0, 0), (0, 2)].into_iter().collect()); + sel.anchors.insert(b, [(0, 0), (0, 1)].into_iter().collect()); + sel.segments.insert(b, [(0, 0)].into_iter().collect()); + sel.guides.push(guide); + sel.key_anchor = Some((a, (0, 0))); + }) + .unwrap(); + let before = s.doc().unwrap().selection.clone(); + let r = s.execute(C, &json!({"scope": "document"})).unwrap(); + assert_eq!(counts(&r), (1, 0, 0)); + let after = &s.doc().unwrap().selection; + assert_eq!(after.objects, [a, b, c]); + assert_eq!(after.anchors, before.anchors); + assert_eq!(after.segments, before.segments); + assert_eq!(after.guides, before.guides); + assert_eq!(after.key_anchor, before.key_anchor); + assert!(!after.objects.contains(&g)); + change(&mut s, c, |n| { + if let NodeKind::Path { path, live, .. } = &mut n.kind { + path.subpaths.push(path.subpaths[0].clone()); + *live = None; + } + }); + s.select(|_, sel| { + sel.anchors.insert(c, [(0, 0), (0, 1)].into_iter().collect()); + sel.segments.insert(c, [(0, 0)].into_iter().collect()); + }) + .unwrap(); + let r = s.execute(C, &json!({"ids": [c.0]})).unwrap(); + assert_eq!(counts(&r), (0, 0, 1)); + let after = &s.doc().unwrap().selection; + assert_eq!(after.anchors, before.anchors); + assert_eq!(after.segments, before.segments); + assert_eq!(after.guides, before.guides); +} + +#[test] +fn release_all_keeps_a_directly_named_blend_key() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let b = rect(&mut s, 40.0, 10.0); + let key = group(&mut s, &[a, b]); + let c = rect(&mut s, 100.0, 10.0); + select(&mut s, &[key, c]); + let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(key), Some(blend)); + let before = s.doc().unwrap().doc.clone(); + let selection = selected(&s); + let steps = undo_steps(&s); + let r = s.execute(C, &json!({"ids": [key.0]})).unwrap(); + assert_eq!(counts(&r), (0, 0, 0)); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(selected(&s), selection); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn release_all_keeps_a_direct_target_inside_a_compound_clipping_mask() { + for clipping_layer in [false, true] { + let mut s = session(); + let art = rect(&mut s, 10.0, 10.0); + let a = rect(&mut s, 5.0, 5.0); + let b = rect(&mut s, 8.0, 8.0); + change(&mut s, a, |n| { + if let NodeKind::Path { path, live, .. } = &mut n.kind { + path.subpaths.push(path.subpaths[0].clone()); + *live = None; + } + }); + let mask = compound(&mut s, &[a, b]); + let container = if clipping_layer { + let id = s.doc().unwrap().doc.layers[0].id; + change(&mut s, id, |n| { + n.children_mut().unwrap().swap(0, 1); + n.set_clips(true); + }); + id + } else { + clip_group(&mut s, &[art, mask]) + }; + assert_eq!(node(&s, container).unwrap().children().unwrap()[0].id, mask); + let before = s.doc().unwrap().doc.clone(); + let steps = undo_steps(&s); + for named in [false, true] { + select(&mut s, &[a]); + let p = if named { json!({"ids": [a.0]}) } else { json!({"clipGroups": false}) }; + let r = s.execute(C, &p).unwrap(); + assert_eq!(counts(&r), (0, 0, 0), "{p}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(selected(&s), [a]); + assert_eq!(undo_steps(&s), steps); + } + } +} + +#[test] +fn release_all_rejects_null_options_without_editing_artwork() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let g = group(&mut s, &[a]); + for selection in [vec![], vec![g]] { + select(&mut s, &selection); + let before = s.doc().unwrap().doc.clone(); + let steps = undo_steps(&s); + for key in ["scope", "groups", "clipGroups", "compoundPaths"] { + let mut p = json!({}); + p[key] = Value::Null; + let error = s.execute(C, &p).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { ref cmd, .. } if cmd == C), "{p}: {error}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(selected(&s), selection); + assert_eq!(undo_steps(&s), steps); + } + } +} + +#[test] +fn release_all_rejects_duplicate_ids_before_traversal() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let g = group(&mut s, &[a]); + let b = rect(&mut s, 50.0, 10.0); + select(&mut s, &[g]); + let before = s.doc().unwrap().doc.clone(); + let steps = undo_steps(&s); + for ids in [vec![g.0, g.0], vec![b.0, b.0], vec![g.0, a.0, a.0]] { + let error = s.execute(C, &json!({"ids": ids})).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { ref cmd, ref msg } if cmd == C && msg.contains("duplicate")), "{error}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(selected(&s), [g]); + assert_eq!(undo_steps(&s), steps); + } +} + +#[test] +fn release_all_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0); + let g = group(&mut s, &[a]); + select(&mut s, &[g]); + let steps = undo_steps(&s); + for bad in [ + json!({"groups": false, "clipGroups": false, "compoundPaths": false}), + json!({"groups": "yes"}), + json!({"compoundPaths": 1}), + json!({"scope": "layer"}), + json!({"scope": "document", "ids": [g.0]}), + json!({"ids": [999_999]}), + ] { + assert!(s.execute(C, &bad).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), steps); + assert!(node(&s, g).is_some()); +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 28a9fbaaa9..59f36b835a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -22,7 +22,9 @@ use vectorcraft_color::Swatch; use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; use vectorcraft_geom::{PathData, Rect}; -pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; +pub use flavours::{ + AI, BITMAP, DWG, DXF, EMF, EPS, FILE_HEAD, Flavour, HPGL, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture, +}; pub use flavours::{ImageRead, read_image, read_pixels}; pub(crate) use resources::SwatchChoices; pub use resources::{ArtResources, SymbolOptions, art_resources}; diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 80e31e849e..8201d8f915 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -1,5 +1,6 @@ //! Clipboard flavours: what Copy offers other apps besides SVG (PNG, PDF and plain text) and what -//! Paste takes from them (bitmaps, plain text, PDF, EPS and Windows metafiles). +//! Paste takes from them (bitmaps, plain text, PDF, EPS, Windows metafiles, and copied CAD drawing +//! and plot files). //! //! The UI owns the platform clipboard (`Services::system_clipboard` in the egui frontend): on Copy //! it publishes [`Session::clipboard_flavours`]; before a Paste it turns what another app put on @@ -34,9 +35,20 @@ pub const EPS: &str = "application/postscript"; /// reads it as `document.open` does, from its editing data. The type is VectorCraft's own: no /// system clipboard carries it, and Paste asks for [`PDF`] to get it. pub const AI: &str = "application/x-ai"; +/// A DXF drawing file copied in a file manager ([`file_flavour`]): Paste reads it with +/// `clipboard.importCad`. No system clipboard carries it, and Paste takes it when it asks for any +/// vector art. +pub const DXF: &str = "image/vnd.dxf"; +/// A DWG drawing file copied in a file manager, read as [`DXF`] is. +pub const DWG: &str = "image/vnd.dwg"; +/// An HP-GL plot file (`.plt`, `.hpgl`…) copied in a file manager, read as [`DXF`] is. +pub const HPGL: &str = "application/vnd.hp-hpgl"; /// What Paste reads from other apps, best first: vector art before text, text before bitmaps /// (word processors offer a picture of copied text too). pub const PASTE_ORDER: [&str; 6] = [SVG, PDF, EPS, EMF, TEXT, BITMAP]; +/// The types Paste asks for that a copied CAD drawing or plot file ([`DXF`], [`DWG`], [`HPGL`]) +/// pastes as. +const VECTOR_ART: [&str; 4] = [SVG, PDF, EPS, EMF]; /// Is `text` only an address (a web page's, an image's, a file's)? A browser's Copy Image puts the /// image's address as text next to the picture: then the picture is what Paste takes (#597). An /// address alone pastes as text, and nothing is fetched. @@ -76,25 +88,31 @@ pub const FILE_HEAD: usize = 4096; /// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap): /// SVG, PDF, EPS, a Windows metafile or a bitmap (its own `image/…` type), told from its first /// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file is [`AI`] when its bytes are a PDF (it -/// pastes when PDF is asked for) and EPS when they are PostScript. The file's bytes are that -/// flavour's data. +/// pastes when PDF is asked for) and EPS when they are PostScript. A DXF or DWG drawing or an +/// HP-GL plot file is [`DXF`], [`DWG`] or [`HPGL`], and pastes when any vector art (SVG, PDF, EPS +/// or EMF) is asked for. The file's bytes are that flavour's data. pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> { let f = fileio::detect(name, head)?; - let (asked, mime) = match f.id { - "svg" => (SVG, SVG), + let (asked, mime): (&[&str], _) = match f.id { + "svg" => (&[SVG], SVG), // `detect` names gzip data SVGZ (a compressed native file aside); `clipboard.importSvg` // reads SVGZ data. - "svgz" if unpacks_to_svg(head) => (SVG, SVG), - "pdf" => (PDF, PDF), - "ps" => (EPS, EPS), - "eps" => (EPS, EPS), - "ai" | "ait" if head.starts_with(b"%PDF") => (PDF, AI), - "ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (EPS, EPS), - "emf" | "wmf" => (EMF, EMF), - _ if f.raster => (BITMAP, f.mime), + "svgz" if unpacks_to_svg(head) => (&[SVG], SVG), + "pdf" => (&[PDF], PDF), + "ps" => (&[EPS], EPS), + "eps" => (&[EPS], EPS), + "ai" | "ait" if head.starts_with(b"%PDF") => (&[PDF], AI), + "ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (&[EPS], EPS), + "emf" | "wmf" => (&[EMF], EMF), + // A file with a drawing's or a plot file's name may hold something else (`.plt` is also a + // chart program's script): it pastes only when its bytes are a drawing or a plot. + "dxf" if vectorcraft_cad::is_dxf(head) => (&VECTOR_ART, DXF), + "dwg" if vectorcraft_cad::is_dwg(head) => (&VECTOR_ART, DWG), + "hpgl" if vectorcraft_cad::hpgl::is_named_hpgl(head) => (&VECTOR_ART, HPGL), + _ if f.raster => (&[BITMAP], f.mime), _ => return None, }; - mimes.contains(&asked).then_some(mime) + mimes.iter().any(|m| asked.contains(m)).then_some(mime) } /// Does gzip data `head` (a file's first bytes, often a stream cut short) unpack to SVG markup? @@ -222,6 +240,15 @@ pub fn specs() -> Vec { has_doc, import_eps ), + cmd!( + query "clipboard.importCad", + "Load CAD Drawing into Clipboard", + [], + None, + "{dataBase64 (a DXF or DWG drawing, or an HP-GL plot file), format: dxf|dwg|hpgl (what the data is; data of another format is refused), center?: [x, y]} replace the clipboard with the drawing's objects as document.open reads the file (DXF and DWG: the Model layout at 1:1 in its own unit), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste. The app runs it for a .dxf, .dwg or HP-GL file copied in a file manager", + has_doc, + import_cad + ), ] } @@ -565,6 +592,22 @@ fn import_eps(s: &mut Session, p: &Value) -> Result { import_picture(s, p, C, "Clipboard.eps", &bytes) } +fn import_cad(s: &mut Session, p: &Value) -> Result { + const C: &str = "clipboard.importCad"; + let (is_it, name, not_it): (fn(&[u8]) -> bool, _, _) = match p.get("format").and_then(Value::as_str) { + Some("dxf") => (vectorcraft_cad::is_dxf, "Clipboard.dxf", "the data isn't a DXF drawing"), + Some("dwg") => (vectorcraft_cad::is_dwg, "Clipboard.dwg", "the data isn't a DWG drawing"), + Some("hpgl") => (vectorcraft_cad::hpgl::is_named_hpgl, "Clipboard.plt", "the data isn't an HP-GL plot file"), + _ => return Err(bad(C, "format must be dxf, dwg or hpgl")), + }; + let bytes = data_param(p, C)?; + // Data of another format is refused, not read as the format its name gives. + if !is_it(&bytes) { + return Err(bad(C, not_it)); + } + import_picture(s, p, C, name, &bytes) +} + /// Replace the clipboard with the objects of the picture `bytes`, read as the file `name` is /// opened (command `cmd`). fn import_picture(s: &mut Session, p: &Value, cmd: &str, name: &str, bytes: &[u8]) -> Result { diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index bff15c6540..3b15730f9a 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -99,12 +99,19 @@ fn family_names(d: &Document) -> Result> { note(family); } } - let mut graphs = Vec::new(); + let (mut graphs, mut dimensions) = (Vec::new(), Vec::new()); view.visit_stored(|node, _| { + // A dimension's options name the family its label is redrawn in. + if let Some(dimension) = &node.extras().dimension { + dimensions.push(dimension.options.font_family.clone()); + } if node.extras().graph.is_some() { graphs.push(node.id); } }); + for mut family in dimensions { + note(&mut family); + } for id in graphs { if let Some(node) = view.stored_node_mut(id) { graph_families(node, &mut note); @@ -112,6 +119,9 @@ fn family_names(d: &Document) -> Result> { } fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) { graph_families(node, note); + if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) { + note(&mut dimension.options.font_family); + } if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) { brush_graphs(Arc::make_mut(&mut mask.art), note); } @@ -140,6 +150,20 @@ 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 dimension redraws its label from its own options, so they follow the label's family. + // A spelling that already names the same font, or one too long for the options, is kept. + if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) { + let family = &mut dimension.options.font_family; + let mut renamed = family.clone(); + visit(&mut renamed); + if !CompositeFont::same_name(&renamed, family) && renamed.len() <= ALIAS_BYTES_MAX { + *family = renamed; + } } graph_families(node, visit); } @@ -162,12 +186,22 @@ impl CompositeImport { } } +/// The longest family name in bytes that a dimension's options keep (`DimensionOptions::validate`). +const ALIAS_BYTES_MAX: usize = 256; + fn composite_alias(base: &str, reserved: &BTreeSet, cmd: &str) -> Result { let db = FontDb::global(); let mut number = 2_u64; loop { let suffix = format!(" {number}"); - let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect(); + let bytes = ALIAS_BYTES_MAX.saturating_sub(suffix.len()); + let mut stem = String::new(); + for c in base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())) { + if stem.len() + c.len_utf8() > bytes { + break; + } + stem.push(c); + } let name = format!("{}{suffix}", stem.trim_end()); if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str()) && !reserved.contains(&name.to_lowercase()) @@ -181,7 +215,13 @@ fn composite_alias(base: &str, reserved: &BTreeSet, cmd: &str) -> Result /// Plan used incoming definitions before changing either document or the font database. /// Keep existing meanings even for an uninstalled family that destination art still names. -pub(super) fn plan_import(source: Vec, source_families: BTreeSet, target: &Document, cmd: &str) -> Result { +pub(super) fn plan_import( + source: Vec, + source_families: BTreeSet, + dimension_families: BTreeSet, + target: &Document, + cmd: &str, +) -> Result { if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX { return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); } @@ -198,6 +238,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()) { @@ -208,12 +262,15 @@ pub(super) fn plan_import(source: Vec, source_families: BTreeSet< let mut names = BTreeMap::new(); let mut combined = target.composite_fonts.to_vec(); for font in source { - let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom; - let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent); + let dimension = dimension_families.contains(&font.name.to_lowercase()); + let equal = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom; + // A dimension keeps its own spelling of a reused name of the same font, so only an alias + // under another name has to fit the bytes its options keep. + let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equal); let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name)); if needs_alias { // A repeated import reuses its already-installed equal alias. - reused = target.composite_fonts.iter().find(equivalent); + reused = target.composite_fonts.iter().find(|other| equal(other) && (!dimension || other.name.len() <= ALIAS_BYTES_MAX)); } let name = match reused { Some(other) => other.name.clone(), @@ -226,12 +283,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/fileio.rs b/crates/engine/src/cmd/fileio.rs index 1a24bf623b..9e67ab1916 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -117,8 +117,8 @@ pub use save::{ }; pub(crate) use screens::{ PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS, - check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings, - with_export_preset as with_screen_export_preset, + check_settings as check_screen_settings, export as export_screens, safe_file_name, sharing_names as sharing_screen_names, + store_settings as store_screen_settings, with_export_preset as with_screen_export_preset, }; pub use screens::{ PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS, @@ -184,7 +184,7 @@ pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions, - readable_format, readable_format_for_name, titled_for_export, writable_format, + readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index dcb26b94b5..821c74acb0 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -28,6 +28,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + let style_trail = s.script_in_run.then(|| s.script_style_trail.clone()); // A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record. let swatch_renames = s.swatch_renames.clone(); let opens = s.plugin_events_mark(); @@ -46,6 +47,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { Err(e) => { s.swatch_renames = swatch_renames; roll_back(s, start, &stash); + if let Some(mut trail) = style_trail { + trail.resources_scanned = s.script_style_trail.resources_scanned; + s.script_style_trail = trail; + } // The documents the steps opened are closed again: plug-ins are not told of them. s.forget_plugin_opens_since(opens); s.notify_text_tool("batch.rollBack"); 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 66ee66a5a0..0d7cfd03c7 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 ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,