mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/artboard-seam-zero-spacing
This commit is contained in:
commit
cf10a40bc7
255 files changed
+20406
-1876
No files matched your search
@@ -67,7 +67,8 @@ jobs:
|
||||
# The warm build runs as one `cache warm <k>/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
|
||||
|
||||
Generated
+132
-122
@@ -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",
|
||||
|
||||
+56
-53
@@ -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" }
|
||||
+3
-1
@@ -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.
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<usize>, 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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Flavour> {
|
||||
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<u8> = (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");
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<Geom> {
|
||||
if p.is_mesh() || p.is_polyface() {
|
||||
self.warn(MESHES);
|
||||
return None;
|
||||
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
|
||||
// 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<Vertex> =
|
||||
@@ -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<BezPath> {
|
||||
let points: Vec<Point> = 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<Vec<(Point, bool)>> = 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<BezPath> {
|
||||
let points: Vec<Point> = 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<Point> = (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<Geom> {
|
||||
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<Point> = 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<Point> = 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]]
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
+51
-13
@@ -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>,
|
||||
block_names: Names,
|
||||
next: u32,
|
||||
layers: Vec<Layer>,
|
||||
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<Node>], 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<Point> = 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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Pairs>)> {
|
||||
let mut found: Vec<(String, Vec<Pairs>)> = 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::<usize>()
|
||||
};
|
||||
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<String> = 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);
|
||||
}
|
||||
+91
-17
@@ -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<Box<LiveShape>>, corners: &BTreeSet<usize>, radius: Option<f64>, kind: Option<CornerKind>) {
|
||||
fn edit(
|
||||
base: &PathData,
|
||||
@@ -286,13 +294,31 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, 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<Box<LiveShape>>,
|
||||
@@ -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<usize> = 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<Box<LiveShape>>, 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 {
|
||||
|
||||
+55
-14
@@ -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<Vec<usize>> {
|
||||
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<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = 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<Arc<Node>, 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<Arc<Node>, 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<NodeId>, 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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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<u32, Vec<u32>>;
|
||||
pub(crate) struct Paths {
|
||||
table: Arc<Table>,
|
||||
gaps: Arc<Gaps>,
|
||||
/// 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<RwLock<IdMap<Vec<usize>>>>,
|
||||
}
|
||||
|
||||
/// 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<Vec<usize>> {
|
||||
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<Node>], 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());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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::<Vec<_>>(), [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::<Vec<_>>(), [added], "lookup {lookup}");
|
||||
}
|
||||
assert!(tree_walks() - walks <= 5, "walks of the tree for 20 ordered lookups");
|
||||
}
|
||||
@@ -262,7 +262,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
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(
|
||||
|
||||
@@ -1013,6 +1013,12 @@ fn solid_items(shape: &Profile) -> impl Iterator<Item = &AppearanceItem> {
|
||||
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<dyn Iterator<Item = &'a AppearanceItem> + '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))? {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<Option<f64>> {
|
||||
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<NodeId> = 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<bool> {
|
||||
@@ -214,6 +229,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
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<bool> {
|
||||
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<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -271,7 +294,7 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.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<Value> {
|
||||
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<NodeId> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
_ => 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
};
|
||||
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<NodeId, Point> = HashMap::new();
|
||||
// The turned targets whose reference point is checked after pixel snapping.
|
||||
let mut checked: HashMap<NodeId, Point> = 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<Value> {
|
||||
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<Rect>| {
|
||||
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<Value> {
|
||||
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<NodeId>| 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<Value> {
|
||||
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<NodeId> = 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<Value> {
|
||||
// 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<Affine> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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)
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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<u32>| 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<NodeId> {
|
||||
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<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn guide_rectangles(d: &Document, layer: Option<NodeId>) -> 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<Point> = 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<Value> {
|
||||
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<usize> = 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::<Vec<_>>(), "layer": layer.0, "skipped": skipped }))
|
||||
}
|
||||
@@ -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<NodeId> {
|
||||
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<String> {
|
||||
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());
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
rejoin
|
||||
),
|
||||
];
|
||||
v.extend(release::specs());
|
||||
v.extend(text::specs());
|
||||
v
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<NodeId>,
|
||||
/// 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<NodeId, Vec<NodeId>>,
|
||||
}
|
||||
|
||||
/// 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<NodeId>) {
|
||||
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<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> 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<Node>, clip: bool, compound: bool, out: &mut Vec<Arc<Node>>) -> 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<Arc<Node>>) -> 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<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> 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<NodeId>) {
|
||||
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<Value> {
|
||||
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<NodeId> = 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<NodeId> = 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<NodeId> = 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<u64> = 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<NodeId> = ids.iter().copied().collect();
|
||||
let removed: Vec<NodeId> = 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<u64> = 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 }))
|
||||
}
|
||||
@@ -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<Node> {
|
||||
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<NodeId> {
|
||||
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<NodeId> {
|
||||
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());
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
import_picture(s, p, C, "Clipboard.eps", &bytes)
|
||||
}
|
||||
|
||||
fn import_cad(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
|
||||
@@ -99,12 +99,19 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
|
||||
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<BTreeSet<String>> {
|
||||
}
|
||||
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<String>, cmd: &str) -> Result<String> {
|
||||
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<String>, 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<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
|
||||
pub(super) fn plan_import(
|
||||
source: Vec<CompositeFont>,
|
||||
source_families: BTreeSet<String>,
|
||||
dimension_families: BTreeSet<String>,
|
||||
target: &Document,
|
||||
cmd: &str,
|
||||
) -> Result<CompositeImport> {
|
||||
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<CompositeFont>, 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<String> = 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<CompositeFont>, 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<CompositeFont>, 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() {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -28,6 +28,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 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<Value> {
|
||||
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");
|
||||
|
||||
@@ -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<String>)> {
|
||||
}
|
||||
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?
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
Line truncated
|
||||
"{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 assignPro
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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.<plug-in id>, 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 <stem>.html / <stem>.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 f
Line truncated
|
||||
"{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.<plug-in id>, 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 <stem>.html / <stem>.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 chos
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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 <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is
Line truncated
|
||||
"{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 <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is
Line truncated
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export DXF",
|
||||
[],
|
||||
None,
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, groupBlocks?: false (Always Export Group as Block Reference: each group a block of its contents, nested groups blocks inside it, placed by an INSERT on the group's layer), selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
has_doc,
|
||||
export_dxf
|
||||
)]
|
||||
@@ -86,6 +86,12 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
description: "Alter Paths for Appearance: strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14",
|
||||
},
|
||||
FormatOption { name: "outlineText", ty: "boolean", default: "false", description: "type as glyph outlines (always with preserve: appearance)" },
|
||||
FormatOption {
|
||||
name: "groupBlocks",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "Always Export Group as Block Reference: each group is a block, placed by an INSERT on its layer",
|
||||
},
|
||||
FormatOption { name: "selectedOnly", ty: "boolean", default: "false", description: "only the selected objects, in their layers" },
|
||||
];
|
||||
|
||||
@@ -113,14 +119,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
|
||||
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
|
||||
}
|
||||
|
||||
/// Formats VectorCraft opens but doesn't write, with what to export instead.
|
||||
const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")];
|
||||
/// Formats VectorCraft opens but doesn't write (by id or extension), with what to export instead.
|
||||
const READ_ONLY_HINTS: &[(&[&str], &str)] =
|
||||
&[(&["dwg", "dws", "dwt"], "DWG files open but can't be written: export DXF instead, which CAD apps open")];
|
||||
|
||||
/// What to write instead of the format an id or extension (any case, leading dot allowed) names,
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG).
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG,
|
||||
/// also a `.dws` or `.dwt` file).
|
||||
pub fn write_hint(id_or_ext: &str) -> Option<&'static str> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint))
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint))
|
||||
}
|
||||
|
||||
impl Unsupported {
|
||||
@@ -147,6 +155,7 @@ struct Params {
|
||||
preserve: Option<String>,
|
||||
alter_paths: Option<bool>,
|
||||
outline_text: Option<bool>,
|
||||
group_blocks: Option<bool>,
|
||||
}
|
||||
|
||||
/// A string or number param as text (`2018` and `"2018"` alike).
|
||||
@@ -192,6 +201,7 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
|
||||
outline_text: q.outline_text.unwrap_or(d.outline_text),
|
||||
group_blocks: q.group_blocks.unwrap_or(d.group_blocks),
|
||||
..d
|
||||
};
|
||||
Ok((opts, q.boards))
|
||||
|
||||
@@ -352,6 +352,7 @@ impl RasterOptions {
|
||||
interlaced: self.interlaced.unwrap_or(false),
|
||||
quality: self.quality()?.unwrap_or(90).min(100),
|
||||
webp_lossless: self.lossless.unwrap_or(true),
|
||||
webp_embed_icc: embed_icc,
|
||||
jpeg: JpegOptions {
|
||||
color_model,
|
||||
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
|
||||
|
||||
@@ -74,8 +74,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, key: im
|
||||
/// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}`
|
||||
/// (`files`: every file when there are several; `linked`: the images it links to); with no path
|
||||
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is
|
||||
/// checked against the file access in force before the first file is written, so a refused path
|
||||
/// writes none of them.
|
||||
/// checked against the file access in force before the first file is written, so a path that
|
||||
/// check refuses writes none of them. A write that fails after that check leaves the files
|
||||
/// written before it.
|
||||
pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result<Value> {
|
||||
let files = enc.named(doc, path.unwrap_or(name));
|
||||
let (main, linked) = files.split_at(enc.files.len());
|
||||
|
||||
@@ -159,7 +159,7 @@ const EMBED_ICC: FormatOption = FormatOption {
|
||||
name: "embedIcc",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk)",
|
||||
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk); WebP: the sRGB profile in an ICCP chunk",
|
||||
};
|
||||
|
||||
const IMAGE_MAP: FormatOption = FormatOption {
|
||||
@@ -470,7 +470,22 @@ pub const FORMATS: &[Format] = &[
|
||||
read: true,
|
||||
write: true,
|
||||
raster: true,
|
||||
options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, LOSSLESS, WEBP_QUALITY],
|
||||
options: &[
|
||||
ARTBOARD,
|
||||
ARTBOARDS,
|
||||
RANGE,
|
||||
USE_ARTBOARDS,
|
||||
RECT,
|
||||
PPI,
|
||||
SCALE,
|
||||
WIDTH,
|
||||
HEIGHT,
|
||||
BACKGROUND,
|
||||
ANTI_ALIAS,
|
||||
LOSSLESS,
|
||||
WEBP_QUALITY,
|
||||
EMBED_ICC,
|
||||
],
|
||||
},
|
||||
Format {
|
||||
id: "tiff",
|
||||
@@ -562,10 +577,19 @@ pub const FORMATS: &[Format] = &[
|
||||
// composite, the layers combined, or the preview with a note. Exports don't write them.
|
||||
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
|
||||
// DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF
|
||||
// reader with the DXF import options. Exports don't write them.
|
||||
reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false),
|
||||
// reader with the DXF import options; `.dws` drawing standards files are DWG drawings too.
|
||||
// Exports don't write them.
|
||||
reader("dwg", "DWG", &["dwg", "dws"], "image/vnd.dwg", false),
|
||||
// `.dwt` drawing templates, DWG drawings read as `dwg` is; a template opens as a new untitled
|
||||
// document. Exports don't write them.
|
||||
reader("dwt", "DWG Template", &["dwt"], "image/vnd.dwg", false),
|
||||
];
|
||||
|
||||
/// Is `id` a format read as a DWG drawing: `dwg` (also `.dws` files) or a `dwt` template?
|
||||
pub fn reads_as_dwg(id: &str) -> bool {
|
||||
matches!(id, "dwg" | "dwt")
|
||||
}
|
||||
|
||||
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
|
||||
pub const OPEN_EXTS: &[&str] = &[
|
||||
"vectorcraft",
|
||||
@@ -626,6 +650,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"cmx",
|
||||
"pcraft",
|
||||
"dwg",
|
||||
"dws",
|
||||
"dwt",
|
||||
];
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
@@ -634,10 +660,10 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings either.
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -729,6 +755,8 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"cmx",
|
||||
"pcraft",
|
||||
"dwg",
|
||||
"dws",
|
||||
"dwt",
|
||||
"txt",
|
||||
"rtf",
|
||||
"docx",
|
||||
|
||||
@@ -47,12 +47,14 @@ impl Loaded {
|
||||
/// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or
|
||||
/// what an importer plug-in reads, as the reference app opens such files (#5820). A native
|
||||
/// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the
|
||||
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was
|
||||
/// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows
|
||||
/// change, not its art.
|
||||
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (also a DWG
|
||||
/// template; the unit it was read in) and a `.ai` or EPS with ruler units keep theirs. Only the
|
||||
/// units the document shows change, not its art.
|
||||
pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self {
|
||||
let records_units =
|
||||
self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg");
|
||||
let records_units = self.restored
|
||||
|| self.doc.units_from_file
|
||||
|| matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf")
|
||||
|| super::reads_as_dwg(self.format.id);
|
||||
if !records_units {
|
||||
self.doc.units = crate::units::pref_unit(&prefs.units_general);
|
||||
}
|
||||
@@ -126,7 +128,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
return format("dxf");
|
||||
}
|
||||
if vectorcraft_cad::is_dwg(bytes) {
|
||||
return format("dwg");
|
||||
// A template keeps its meaning from the extension.
|
||||
return by_name.filter(|f| f.id == "dwt").or_else(|| format("dwg"));
|
||||
}
|
||||
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
|
||||
return format(kind.id());
|
||||
@@ -563,8 +566,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
read
|
||||
}
|
||||
// A DWG drawing is read as the DXF craft-dwg converts it to.
|
||||
"dxf" | "dwg" => {
|
||||
// A DWG drawing (or template) is read as the DXF craft-dwg converts it to.
|
||||
"dxf" | "dwg" | "dwt" => {
|
||||
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
@@ -1021,9 +1024,9 @@ fn open_loaded(
|
||||
.cloned()
|
||||
.collect();
|
||||
let source_path = path.clone().filter(|_| !losses.is_empty());
|
||||
// A template (saved by Save as Template, or an .ait, .vctemplate or .cdt file) opens as a new
|
||||
// untitled document.
|
||||
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt");
|
||||
// A template (saved by Save as Template, or an .ait, .vctemplate, .cdt or .dwt file) opens as a
|
||||
// new untitled document.
|
||||
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt" | "dwt");
|
||||
if template {
|
||||
doc.template = false;
|
||||
doc.title = s.next_untitled();
|
||||
|
||||
@@ -176,8 +176,8 @@ impl LoadOptions {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
|
||||
/// `.ai` with Illustrator private data opens on its trim boxes by default,
|
||||
/// with the bleed around them. An explicit crop-box request uses its crop box.
|
||||
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
|
||||
let pages = match &self.pages {
|
||||
@@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
|
||||
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
|
||||
/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the
|
||||
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
|
||||
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
|
||||
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
|
||||
@@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
|
||||
};
|
||||
let bounding = o.crop == CropTo::Bounding;
|
||||
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
|
||||
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
// A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]);
|
||||
// an explicit crop-box request keeps its crop boxes.
|
||||
let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
|
||||
doc.artboards.clear();
|
||||
|
||||
@@ -282,7 +282,11 @@ impl Row {
|
||||
// The resolution is stored in the file too.
|
||||
ScreenSize::Ppi(ppi) => o["ppi"] = json!(ppi),
|
||||
size => {
|
||||
o["scale"] = json!(size.scale_for(C, region)?);
|
||||
let scale = size.scale_for(C, region)?;
|
||||
if !scale.is_finite() || !(0.01..=64.0).contains(&scale) {
|
||||
return Err(bad(C, "the effective raster scale must be between 0.01 and 64 pixels per point"));
|
||||
}
|
||||
o["scale"] = json!(scale);
|
||||
if let Some(m) = o.as_object_mut() {
|
||||
m.remove("ppi");
|
||||
}
|
||||
@@ -638,6 +642,25 @@ fn fold(name: &str) -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The [`fold`]ed names the exports run by [`sharing_names`] on this thread have taken so far.
|
||||
static SHARED_NAMES: std::cell::RefCell<Option<HashSet<String>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// `f`, with every `document.exportForScreens` it runs on this thread naming its files around
|
||||
/// the names the ones before it took, so a later export does not write over an earlier one's file
|
||||
/// (it numbers its own: `-2`, `-3`…).
|
||||
pub(crate) fn sharing_names<T>(f: impl FnOnce() -> T) -> T {
|
||||
let outer = SHARED_NAMES.with(|n| n.borrow_mut().replace(HashSet::new()));
|
||||
let r = f();
|
||||
SHARED_NAMES.with(|n| *n.borrow_mut() = outer);
|
||||
r
|
||||
}
|
||||
|
||||
/// The key the names taken by an earlier export are held under in [`Output::taken`]: no file of
|
||||
/// this export has it.
|
||||
const EARLIER_EXPORT: &str = "\0earlier export";
|
||||
|
||||
/// The file names (and bytes) an export wrote, or the files it returns.
|
||||
#[derive(Default)]
|
||||
struct Output {
|
||||
@@ -1194,6 +1217,11 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
for row in rows.iter().filter(|row| row.format.raster) {
|
||||
for item in &items {
|
||||
row.options_for(item.region, item.artboard)?;
|
||||
}
|
||||
}
|
||||
// Before the folder is made or any row is written, with the artboards each file holds.
|
||||
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
|
||||
let st = s.doc()?;
|
||||
@@ -1348,6 +1376,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
create_dir(dir)?;
|
||||
}
|
||||
let mut out = Output::default();
|
||||
// The names earlier exports of a [`sharing_names`] run took into the same files.
|
||||
if !o.zip {
|
||||
SHARED_NAMES.with(|n| {
|
||||
for name in n.borrow().iter().flatten() {
|
||||
out.taken.insert(name.clone(), EARLIER_EXPORT.to_string());
|
||||
}
|
||||
});
|
||||
}
|
||||
// The notes on the options, then the encoders' notes for every file, each once.
|
||||
let mut notes: Vec<Note> = Vec::new();
|
||||
for text in unused {
|
||||
@@ -1426,6 +1462,13 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
files += 1;
|
||||
}
|
||||
}
|
||||
if !o.zip {
|
||||
SHARED_NAMES.with(|n| {
|
||||
if let Some(shared) = n.borrow_mut().as_mut() {
|
||||
shared.extend(out.taken.keys().cloned());
|
||||
}
|
||||
});
|
||||
}
|
||||
// A cancel that came while the last file was encoded returns no files. A folder export
|
||||
// without a ZIP has written every file by now, so it returns them.
|
||||
if o.zip || folder.is_none() {
|
||||
|
||||
@@ -89,6 +89,8 @@ fn versions_3_and_4_open_and_place_as_editable_art() {
|
||||
assert_eq!(r["format"], "cdr", "{version} {name}");
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect();
|
||||
assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}");
|
||||
// The reader opens PowerClip frames from version 4 on.
|
||||
assert_eq!(w.iter().any(|w| w.contains("PowerClip")), version >= 400, "{version}: {w:?}");
|
||||
}
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}");
|
||||
@@ -535,6 +537,35 @@ fn containers_open_as_clipping_groups() {
|
||||
assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })));
|
||||
}
|
||||
|
||||
/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or
|
||||
/// whose group holds a container of that same group, opens as a plain shape, and the warnings
|
||||
/// say that such frames opened empty.
|
||||
#[test]
|
||||
fn containers_whose_contents_were_left_out_are_named_in_the_warnings() {
|
||||
let v = V(1100);
|
||||
let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| {
|
||||
let mut args = vec![(30, v.rect(w, w, 0.0))];
|
||||
args.extend(extra);
|
||||
synth::object(v, 1, &args, None)
|
||||
};
|
||||
let open = |clipped: Vec<synth::Node>| {
|
||||
let doc = list(b"doc ", vec![synth::clpt(vec![(5, clipped)])]);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]);
|
||||
super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap()
|
||||
};
|
||||
let frames = "PowerClip frames whose contents were left out opened empty";
|
||||
let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]);
|
||||
let p = paths(&doc);
|
||||
let [frame] = p.as_slice() else { panic!("{p:?}") };
|
||||
assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind);
|
||||
assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}");
|
||||
// The inner container names the group already being read, so it is left out at the limit.
|
||||
let (_, warnings) = open(vec![rect(10.0, vec![synth::container(5)])]);
|
||||
assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// An object with a lens or transparency opens opaque, and the warnings say so.
|
||||
#[test]
|
||||
fn lenses_and_transparency_are_named_in_the_warnings() {
|
||||
|
||||
@@ -62,6 +62,35 @@ fn document_open_reads_a_dwg_drawing_as_its_dxf() {
|
||||
assert!(open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"layout": "Sheet 9"}})).is_err());
|
||||
}
|
||||
|
||||
/// A DWG drawing copied in a file manager pastes the objects its DXF pastes; a DXF given as DWG is
|
||||
/// refused.
|
||||
#[test]
|
||||
fn a_copied_dwg_drawing_pastes_as_its_dxf_does() {
|
||||
use crate::cmd::clipboard::{DWG, PASTE_ORDER, file_flavour};
|
||||
let dwg = plan_dwg();
|
||||
assert_eq!(file_flavour("plan.dwg", &dwg, &PASTE_ORDER), Some(DWG));
|
||||
let pasted = |data: &[u8], format: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s.execute("clipboard.importCad", &json!({"dataBase64": b64(data), "format": format})).unwrap();
|
||||
s.execute("edit.paste", &json!({"center": [300, 200]})).unwrap();
|
||||
leaves(&s).iter().map(|n| n.geometric_bounds()).collect::<Vec<_>>()
|
||||
};
|
||||
let (from_dwg, from_dxf) = (pasted(&dwg, "dwg"), pasted(&plan(), "dxf"));
|
||||
assert!(!from_dwg.is_empty());
|
||||
assert_eq!(from_dwg.len(), from_dxf.len());
|
||||
for (a, b) in from_dwg.iter().zip(&from_dxf) {
|
||||
let close = match (a, b) {
|
||||
(Some(a), Some(b)) => [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-3),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
};
|
||||
assert!(close, "{a:?} {b:?}");
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
assert!(s.execute("clipboard.importCad", &json!({"dataBase64": b64(&plan()), "format": "dwg"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_opened_is_never_written_back_as_dwg() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwg-save-{}", std::process::id()));
|
||||
@@ -111,3 +140,69 @@ fn dwg_is_read_only_and_detected_by_content() {
|
||||
assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg"));
|
||||
}
|
||||
|
||||
/// A `.dwt` drawing template opens as a new untitled document and a `.dws` standards file as the
|
||||
/// drawing it is, each read as a `.dwg` with the same content is; a DXF named `.dwt` stays a DXF.
|
||||
#[test]
|
||||
fn a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwt-open-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dwg = plan_dwg();
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "plan.dwg", &dwg, json!({})).unwrap();
|
||||
let (want_layers, want_leaves) = (layer_names(&s), leaves(&s).len());
|
||||
|
||||
let template = dir.join("plan.dwt");
|
||||
std::fs::write(&template, &dwg).unwrap();
|
||||
let r = s.execute("document.open", &json!({"path": template.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["format"], "dwt");
|
||||
assert!(r["title"].as_str().is_some_and(|t| t.starts_with("Untitled")), "a template opens untitled: {}", r["title"]);
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.path.is_none());
|
||||
assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters, "the drawing's unit");
|
||||
assert_eq!((layer_names(&s), leaves(&s).len()), (want_layers.clone(), want_leaves));
|
||||
|
||||
let standards = dir.join("plan.dws");
|
||||
std::fs::write(&standards, &dwg).unwrap();
|
||||
let r = s.execute("document.open", &json!({"path": standards.to_string_lossy()})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dws")));
|
||||
assert_eq!((layer_names(&s), leaves(&s).len()), (want_layers, want_leaves));
|
||||
|
||||
assert_eq!(detect("plan.dwt", &plan()).map(|f| f.id), Some("dxf"), "the content tells");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// File › Place reads a `.dwt` or `.dws` drawing as it reads a `.dwg`: fitted to the artboard with
|
||||
/// the same `dxf` options, in one undo step.
|
||||
#[test]
|
||||
fn a_dwt_or_dws_drawing_places_as_a_dwg_does() {
|
||||
let dwg = plan_dwg();
|
||||
let place = |name: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": b64(&dwg), "dxf": {"fit": true, "center": false}})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{name}: one undo step");
|
||||
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
(r["format"].as_str().map(str::to_string), [b.x0, b.y0, b.x1, b.y1])
|
||||
};
|
||||
let (format, want) = place("plan.dwg");
|
||||
assert_eq!(format.as_deref(), Some("dwg"));
|
||||
assert_eq!(place("plan.dws"), (Some("dwg".to_string()), want));
|
||||
assert_eq!(place("plan.dwt"), (Some("dwt".to_string()), want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf() {
|
||||
let f = format("dwt").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert_eq!(readable_format("dws").map(|f| f.id), Some("dwg"));
|
||||
for ext in ["dws", "dwt"] {
|
||||
assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let e = s.execute("document.export", &json!({"format": ext})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "{ext}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -174,6 +174,27 @@ fn placed_images_come_back_as_linked_files() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// `groupBlocks` writes a group as an INSERT of a block holding its contents; off by default, and
|
||||
/// not set by CNC / CAM.
|
||||
#[test]
|
||||
fn group_blocks_write_a_group_as_an_insert() {
|
||||
let mut s = two_boards();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let plain = s.execute("document.exportDxf", &json!({})).unwrap();
|
||||
assert_eq!(entities(&text(&plain)), ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "HATCH"]);
|
||||
for (cmd, p) in
|
||||
[("document.exportDxf", json!({"groupBlocks": true})), ("document.export", json!({"format": "dxf", "dxfPreset": "cnc", "groupBlocks": true}))]
|
||||
{
|
||||
let dxf = text(&s.execute(cmd, &p).unwrap());
|
||||
assert_eq!(entities(&dxf), ["INSERT"], "{p}");
|
||||
let blocks = &dxf[dxf.find("\nBLOCKS\n").unwrap()..dxf.find("\nENTITIES\n").unwrap()];
|
||||
assert_eq!(blocks.matches("\nLWPOLYLINE\n").count(), 2, "{p}: the group's rectangles are in its block");
|
||||
}
|
||||
let cnc = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap();
|
||||
assert!(!entities(&text(&cnc)).contains(&"INSERT".to_string()));
|
||||
}
|
||||
|
||||
/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill
|
||||
/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves
|
||||
/// out both, and the options given override it.
|
||||
@@ -259,6 +280,7 @@ fn bad_dxf_options_are_refused() {
|
||||
json!({"alterPaths": "yes"}),
|
||||
json!({"includeImages": "no"}),
|
||||
json!({"includeHatches": 0}),
|
||||
json!({"groupBlocks": "yes"}),
|
||||
] {
|
||||
let e = s.execute("document.exportDxf", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("DXF"), "{p}: {e}");
|
||||
@@ -286,6 +308,7 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
"preserve",
|
||||
"alterPaths",
|
||||
"outlineText",
|
||||
"groupBlocks",
|
||||
"selectedOnly",
|
||||
"useArtboards",
|
||||
] {
|
||||
|
||||
@@ -184,6 +184,33 @@ fn dxf_is_readable_and_detected_by_content() {
|
||||
assert!(r["readable"].as_array().unwrap().contains(&json!("dxf")));
|
||||
}
|
||||
|
||||
/// A DXF drawing copied in a file manager pastes as its objects at 1:1, centred where the paste
|
||||
/// puts it; data that isn't a DXF drawing, and a format `clipboard.importCad` doesn't read, are
|
||||
/// refused.
|
||||
#[test]
|
||||
fn a_copied_dxf_drawing_pastes_as_its_objects() {
|
||||
use crate::cmd::clipboard::{BITMAP, DXF, PASTE_ORDER, TEXT, file_flavour};
|
||||
let dxf = plan();
|
||||
assert_eq!(file_flavour("plan.dxf", &dxf, &PASTE_ORDER), Some(DXF));
|
||||
assert_eq!(file_flavour("plan.txt", &dxf, &PASTE_ORDER), Some(DXF), "the content tells");
|
||||
assert_eq!(file_flavour("plan.dxf", &dxf, &[TEXT, BITMAP]), None, "not when only text or a bitmap is asked for");
|
||||
assert_eq!(file_flavour("plan.dxf", b"a note, not a drawing", &PASTE_ORDER), None, "by its bytes, not its name");
|
||||
let mut s = page();
|
||||
let r = s.execute("clipboard.importCad", &json!({"dataBase64": b64(&dxf), "format": "dxf"})).unwrap();
|
||||
assert!(r["count"].as_u64().is_some_and(|n| n > 0), "{r}");
|
||||
s.execute("edit.paste", &json!({"center": [300, 200]})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let pasted: Vec<_> = doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).collect();
|
||||
let b = pasted.iter().fold(None, |b, n| vectorcraft_geom::union_opt(b, n.geometric_bounds())).unwrap();
|
||||
assert!((b.width() - 200.0 * MM).abs() < 1e-6 && (b.height() - 100.0 * MM).abs() < 1e-6, "{b:?}");
|
||||
assert!((b.center().x - 300.0).abs() < 1e-6 && (b.center().y - 200.0).abs() < 1e-6, "{b:?}");
|
||||
let mut refused = |p: Value| s.execute("clipboard.importCad", &p).unwrap_err().to_string();
|
||||
let plot = b64(b"IN;SP1;PA0,0;PD100,0;");
|
||||
assert!(refused(json!({"dataBase64": plot, "format": "dxf"})).contains("isn't a DXF drawing"));
|
||||
assert!(refused(json!({"dataBase64": b64(&dxf), "format": "svg"})).contains("format must be"));
|
||||
assert!(refused(json!({"dataBase64": b64(&dxf)})).contains("format must be"));
|
||||
}
|
||||
|
||||
/// A document of one 600 × 400 artboard.
|
||||
fn page() -> Session {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -80,6 +80,34 @@ fn files_that_are_not_hpgl_are_refused() {
|
||||
assert_eq!(text["format"], "txt", "{text}");
|
||||
}
|
||||
|
||||
/// A plot file copied in a file manager pastes as its paths, also one named as a plot file that
|
||||
/// starts with an instruction plot files seldom start with; a file of that name holding something
|
||||
/// else does not paste as a plot, and data that isn't one is refused.
|
||||
#[test]
|
||||
fn a_copied_plot_file_pastes_as_its_paths() {
|
||||
use crate::cmd::clipboard::{BITMAP, HPGL, PASTE_ORDER, TEXT, file_flavour};
|
||||
let script = b"set terminal png\nplot sin(x)\n";
|
||||
assert_eq!(file_flavour("part.plt", PLOT, &PASTE_ORDER), Some(HPGL));
|
||||
assert_eq!(file_flavour("part.plt", b"SI0.2,0.3;SP1;PA0,0;PD1016,0;", &PASTE_ORDER), Some(HPGL));
|
||||
assert_eq!(file_flavour("graph.plt", script, &PASTE_ORDER), None);
|
||||
assert_eq!(file_flavour("part.plt", PLOT, &[TEXT, BITMAP]), None);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
s.execute("clipboard.importCad", &json!({"dataBase64": b64(PLOT), "format": "hpgl"})).unwrap();
|
||||
s.execute("edit.paste", &json!({"center": [150, 100]})).unwrap();
|
||||
let mut paths = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
paths.extend(n.geometric_bounds());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 2, "{paths:?}");
|
||||
assert!(paths.iter().all(|b| (b.width() - 72.0).abs() < 0.5), "an inch wide: {paths:?}");
|
||||
for (data, format) in [(&script[..], "hpgl"), (PLOT, "dwg")] {
|
||||
assert!(s.execute("clipboard.importCad", &json!({"dataBase64": b64(data), "format": format})).is_err(), "{format}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plot file named as one opens when its first instruction is one a plot file seldom starts with;
|
||||
/// under another name it isn't taken for HP-GL.
|
||||
#[test]
|
||||
|
||||
@@ -229,6 +229,31 @@ fn png_says_it_is_srgb_unless_embed_icc_is_false() {
|
||||
assert!(f["options"].get("embedIcc").is_some(), "png lists embedIcc");
|
||||
}
|
||||
|
||||
/// WebP, lossless or lossy, holds the sRGB profile in an `ICCP` chunk unless `embedIcc` is false,
|
||||
/// in Export As and in Export for Screens' `settings.webp`, without a note on an unused option.
|
||||
#[test]
|
||||
fn webp_embeds_the_srgb_profile_unless_embed_icc_is_false() {
|
||||
let mut s = session(40.0, 30.0, 1);
|
||||
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
|
||||
let has_iccp = |file: &[u8]| file.windows(4).any(|w| w == b"ICCP");
|
||||
for lossless in [true, false] {
|
||||
let on = s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap();
|
||||
assert!(has_iccp(&b64(&on)), "lossless {lossless}");
|
||||
let off = s.execute("document.export", &json!({"format": "webp", "lossless": lossless, "embedIcc": false})).unwrap();
|
||||
assert!(!has_iccp(&b64(&off)), "lossless {lossless}");
|
||||
assert_eq!(off["warnings"], json!([]), "lossless {lossless}: embedIcc is a WebP option");
|
||||
}
|
||||
let screens = |s: &mut Session, settings: Value| {
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp"}], "settings": settings})).unwrap();
|
||||
b64(&r["files"][0])
|
||||
};
|
||||
assert!(has_iccp(&screens(&mut s, json!({}))));
|
||||
assert!(!has_iccp(&screens(&mut s, json!({"webp": {"embedIcc": false}}))));
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "webp").unwrap();
|
||||
assert!(f["options"].get("embedIcc").is_some(), "webp lists embedIcc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_list_the_raster_options() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -95,13 +95,13 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
|
||||
(b64(&r), r["warnings"].clone())
|
||||
};
|
||||
let (lossless, warnings) = export(&mut s, json!({}));
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8X", *b"ICCP", *b"VP8L"], "lossless with the profile by default");
|
||||
assert_eq!(warnings, json!([]));
|
||||
// Quality doesn't change a lossless file.
|
||||
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
|
||||
|
||||
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"VP8 "], "opaque art has no alpha chunk");
|
||||
assert_eq!(warnings, json!([]), "no note: the file is lossy");
|
||||
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
|
||||
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
|
||||
@@ -114,10 +114,11 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
|
||||
// Lower quality, smaller file.
|
||||
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
|
||||
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
|
||||
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
|
||||
assert_eq!(webp_chunks(&low), [*b"VP8X", *b"ICCP", *b"VP8 "]);
|
||||
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
|
||||
for q in [0, 100] {
|
||||
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
|
||||
let file = export(&mut s, json!({"lossless": false, "quality": q, "embedIcc": false})).0;
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "], "quality {q}: a plain lossy file without the profile");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +131,7 @@ fn lossy_webp_keeps_translucent_pixels() {
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
|
||||
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"ALPH", *b"VP8 "]);
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
|
||||
@@ -161,7 +162,7 @@ fn webp_quality_out_of_its_range_is_refused() {
|
||||
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
|
||||
let file = b64(&r["files"][0]);
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ICCP", *b"VP8 "]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder",
|
||||
[],
|
||||
None,
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard (unless it is new art there that is still selected), and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
has_doc,
|
||||
move_node
|
||||
),
|
||||
@@ -192,7 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make/Release Clipping Mask",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{id?: layer or group (default: the one highlighted layer or group row, else the one selected group, else the current layer)} make: its top object (a path, compound path or text, which loses its paint) clips the rest and moves to the bottom (new art added on top is clipped); release: it stops clipping, the clipping path stays unpainted → {clip}",
|
||||
"{id?: layer or group (default: the one highlighted layer or group row, else the one selected group, else the current layer)} make: its top object (a path, compound path or text, which loses its paint) clips the rest and moves to the bottom (new art added on top is clipped; a Shaper group is refused and changes nothing); release: it stops clipping, the clipping path stays unpainted → {clip}",
|
||||
has_doc,
|
||||
clip_toggle
|
||||
),
|
||||
@@ -526,6 +526,11 @@ fn clip_toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
let id = given.or(row).or(group).or(st.current_layer()).ok_or_else(|| bad("layer.clippingMask.toggle", "no layer"))?;
|
||||
// A Shaper group keeps its source art first; a clipping path there would replace it. The
|
||||
// check comes before the edit so that a refused call leaves any typing as it is.
|
||||
if st.doc.node(id).is_some_and(|n| !n.clips() && n.extras().shaper.is_some()) {
|
||||
return Err(bad("layer.clippingMask.toggle", format!("{} is a Shaper group, whose contents are made from its source art", id.0)));
|
||||
}
|
||||
let clip = s.edit("Make/Release Clipping Mask", |d, _| {
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
|
||||
@@ -1051,7 +1056,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A path in a compound path keeps no paint, live shape or pixel alignment of its own, as
|
||||
// Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when
|
||||
// the path was, or when the compound path it leaves was.
|
||||
// the path was, or when the compound path it leaves was. A compound path that is
|
||||
// pixel-aligned snaps the path it takes in.
|
||||
if let Some(c) = into {
|
||||
let mut aligned = from_aligned;
|
||||
if let Some(m) = d.node_mut(id) {
|
||||
@@ -1061,9 +1067,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*live = None;
|
||||
}
|
||||
}
|
||||
if aligned && let Some(cn) = d.node_mut(c) {
|
||||
cn.extras_mut().pixel_aligned = true;
|
||||
super::object::snap_if_aligned(cn);
|
||||
if let Some(cn) = d.node_mut(c) {
|
||||
aligned |= cn.extras().pixel_aligned;
|
||||
if aligned {
|
||||
cn.extras_mut().pixel_aligned = true;
|
||||
super::object::snap_if_aligned(cn);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((appearance, aligned)) = out_of
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}",
|
||||
has_doc, show_missing_links),
|
||||
cmd!(query "links.marked", "Marked Missing Links", [], None,
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off; a caller whose read folders do not cover the same files as the document's, or a script command, gets its own answer and the canvas markers stay as they are → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
has_doc, marked),
|
||||
cmd!(
|
||||
query "links.check",
|
||||
@@ -2693,7 +2693,19 @@ fn marked(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
|
||||
})
|
||||
.collect();
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
// The canvas draws the markers the link watch finds with the read roots the document was
|
||||
// opened with ([`Session::start_link_scan`]). An answer found with other read roots stays the
|
||||
// caller's, as is one found by a script command, whose file-read gate the link watch does
|
||||
// not have.
|
||||
let same_roots = !crate::file_access::in_script_command()
|
||||
&& match (crate::file_access::current(), &st.opened_by) {
|
||||
(None, None) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(&a, b) || a.same_reads(b),
|
||||
_ => false,
|
||||
};
|
||||
if same_roots {
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
}
|
||||
Ok(json!({"on": st.show_missing_links, "images": images}))
|
||||
}
|
||||
|
||||
|
||||
@@ -377,6 +377,11 @@ impl DocSettings {
|
||||
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
|
||||
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
|
||||
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
|
||||
// The columns that rows give the artboards as they are now, which a layout that replaces the
|
||||
// rows without its own `columns` keeps.
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
if let Some(id) = l.as_str() {
|
||||
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
|
||||
if self.layout != ArtboardLayout::GridByColumn {
|
||||
|
||||
@@ -33,12 +33,12 @@ mod transform;
|
||||
|
||||
pub(crate) use align::choice;
|
||||
pub(crate) use arrange::group_nodes;
|
||||
pub(crate) use bounds::{bounds_rewrite, object_bounds_transform};
|
||||
pub(crate) use bounds::{bounds_rewrite, object_bounds_transform, object_bounds_transform_keeping, refit_drawn};
|
||||
pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, copy_transparency, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{
|
||||
align_new_object, aligned_symbol_transforms, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned, keep_pixel_aligned,
|
||||
keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art,
|
||||
align_new_object, aligned_symbol_transforms, aligned_symbols, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned,
|
||||
keep_pixel_aligned, keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art, snaps_after_edit,
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
|
||||
@@ -129,6 +129,10 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() {
|
||||
return Err(bad(C, format!("{} is not a layer or group", parent.0)));
|
||||
}
|
||||
// A Shaper group rebuilds its contents from the source art it holds first.
|
||||
if n.extras().shaper.is_some() {
|
||||
return Err(bad(C, format!("{} is a Shaper group, whose contents are made from its source art", parent.0)));
|
||||
}
|
||||
if !d.is_editable(parent) {
|
||||
return Err(bad(C, "the layer or group is hidden or locked"));
|
||||
}
|
||||
|
||||
@@ -45,7 +45,13 @@ pub(crate) fn bounds_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<(
|
||||
/// `object.setBounds` measures them (Use Preview Bounds, `strokes`, `reference`, `proportional`),
|
||||
/// whatever anchors are direct-selected. The art keeps at least 1e-4 of its width and height.
|
||||
pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Result<Affine> {
|
||||
match bounds_transform(s, p, vec![id], 1e-4, false)? {
|
||||
object_bounds_transform_keeping(s, p, id, 1e-4)
|
||||
}
|
||||
|
||||
/// [`object_bounds_transform`] with the art keeping at least `least` of its width and height
|
||||
/// (0: any scale the values ask for).
|
||||
pub(crate) fn object_bounds_transform_keeping(s: &Session, p: &Value, id: NodeId, least: f64) -> Result<Affine> {
|
||||
match bounds_transform(s, p, vec![id], least, false)? {
|
||||
Bounds::Objects(_, xf) => Ok(xf),
|
||||
Bounds::Anchors(..) => Err(EngineError::Other("no bounds".into())),
|
||||
}
|
||||
@@ -163,7 +169,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
// smaller than that reach. Strokes and effects that scale shrink the reach with the art, so
|
||||
// the search then starts from the size wanted over the size as drawn.
|
||||
let seed = |s: f64, size: f64, now: f64| if s <= 0.0 && size > 0.0 && now > 1e-9 { size / now } else { s };
|
||||
refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9])
|
||||
refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9], None)
|
||||
} else {
|
||||
Spans::measure(d, &ids, &frame, strokes).refit(rp, refi, [w, h], (sx, sy, new_rp))
|
||||
};
|
||||
@@ -186,26 +192,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
/// change with the y scale and the height with the x scale (a geometry effect can turn the art). A
|
||||
/// scale that `free` marks false stays as it is. The search stops when both sizes are within 1e-9
|
||||
/// of the sizes wanted (of the largest of 1 and those sizes), when no scale moves, when `measure`
|
||||
/// finds no box, or after 16 steps, and returns the scales that came nearest. `None` when `measure`
|
||||
/// finds no box for `start`.
|
||||
fn refit_drawn(
|
||||
/// finds no box, or after 16 steps. It returns the scales whose box met both stopping tolerances,
|
||||
/// and otherwise the scales whose box came nearest. `None` when `measure`
|
||||
/// finds no box for `start`. Each stopping tolerance in `tolerances`, when given, is capped at
|
||||
/// the default tolerance.
|
||||
pub(crate) fn refit_drawn(
|
||||
measure: impl Fn(f64, f64) -> Option<Rect>,
|
||||
refi: usize,
|
||||
size: [f64; 2],
|
||||
start: (f64, f64),
|
||||
free: [bool; 2],
|
||||
tolerances: Option<[f64; 2]>,
|
||||
) -> Option<(f64, f64, Point)> {
|
||||
let [w, h] = size;
|
||||
let tolerance = 1e-9 * w.max(h).max(1.0);
|
||||
let tolerances = tolerances.unwrap_or([tolerance; 2]).map(|t| t.min(tolerance));
|
||||
let miss = |b: Rect| (b.width() - w).abs() + (b.height() - h).abs();
|
||||
let met = |b: Rect| (b.width() - w).abs() <= tolerances[0] && (b.height() - h).abs() <= tolerances[1];
|
||||
let (mut sx, mut sy) = start;
|
||||
let mut b = measure(sx, sy)?;
|
||||
let mut best = (sx, sy, b);
|
||||
for _ in 0..16 {
|
||||
let f = [b.width() - w, b.height() - h];
|
||||
if f[0].abs() <= tolerance && f[1].abs() <= tolerance {
|
||||
if met(b) {
|
||||
break;
|
||||
}
|
||||
let f = [b.width() - w, b.height() - h];
|
||||
// How the width and the height change with the x scale (`a`) and the y scale (`c`).
|
||||
let change = |x: bool| -> Option<[f64; 2]> {
|
||||
let (on, s) = if x { (free[0], sx) } else { (free[1], sy) };
|
||||
@@ -235,7 +246,8 @@ fn refit_drawn(
|
||||
}
|
||||
let Some(next) = measure(nx, ny) else { break };
|
||||
(sx, sy, b) = (nx, ny, next);
|
||||
if miss(b) < miss(best.2) {
|
||||
// A box that meets both tolerances wins over a nearer sum that misses one of them.
|
||||
if met(b) || miss(b) < miss(best.2) {
|
||||
best = (sx, sy, b);
|
||||
}
|
||||
}
|
||||
@@ -291,3 +303,28 @@ fn scaling_box(d: &Document, ids: &[NodeId], frame: &OrientedBox) -> Option<Rect
|
||||
vectorcraft_geom::union_opt(acc, b)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Rect, refit_drawn};
|
||||
|
||||
#[test]
|
||||
fn refit_drawn_prefers_the_box_that_meets_both_tolerances() {
|
||||
// The start box is 2e-6 too wide (outside the 1e-9 width tolerance). The step lands on the
|
||||
// right width with the height 3e-6 too tall (inside the 1e-4 height tolerance), a larger
|
||||
// summed miss than the start's.
|
||||
let measure = |sx: f64, _sy: f64| {
|
||||
let width = 0.05 * sx + 2e-6;
|
||||
let height = if sx < 1.0 { 100_000.000_003 } else { 100_000.0 };
|
||||
Some(Rect::new(0.0, 0.0, width, height))
|
||||
};
|
||||
let tolerances = [1e-9, 1e-4];
|
||||
let Some((sx, _, _)) = refit_drawn(measure, 0, [0.05, 100_000.0], (1.0, 1.0), [true, false], Some(tolerances)) else {
|
||||
panic!("refit_drawn found no box");
|
||||
};
|
||||
assert!(sx < 1.0, "the start scale came back: {sx}");
|
||||
let Some(b) = measure(sx, 1.0) else { panic!("no box") };
|
||||
assert!((b.width() - 0.05).abs() <= tolerances[0], "width {}", b.width());
|
||||
assert!((b.height() - 100_000.0).abs() <= tolerances[1], "height {}", b.height());
|
||||
}
|
||||
}
|
||||
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Group",
|
||||
[],
|
||||
None,
|
||||
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
|
||||
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group (a Shaper group is refused and changes nothing); an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
|
||||
has_doc,
|
||||
new_group
|
||||
),
|
||||
@@ -314,7 +314,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once no corner stores a radius or a corner kind other than round (a corner that an anchor move straightens draws no arc but keeps its radius and the path stays live); sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -492,6 +492,18 @@ pub(crate) fn snap_if_aligned(n: &mut Node) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pixel-grid snap after an edit ([`refresh`]) can move object `n`: `n` holds
|
||||
/// pixel-aligned art ([`holds_aligned`]) or an instance of a symbol in `symbols`, the document's
|
||||
/// pixel-aligned symbols ([`aligned_symbols`]).
|
||||
pub(crate) fn snaps_after_edit(n: &Node, symbols: &HashMap<String, Affine>) -> bool {
|
||||
holds_aligned(n) || !symbols.is_empty() && holds_instance(n, symbols)
|
||||
}
|
||||
|
||||
/// The pixel-aligned symbols of `d`, keyed by name, for [`snaps_after_edit`].
|
||||
pub(crate) fn aligned_symbols(d: &Document) -> HashMap<String, Affine> {
|
||||
d.pixel_aligned_symbols().into_iter().map(|name| (name, Affine::IDENTITY)).collect()
|
||||
}
|
||||
|
||||
/// Whether `n` or an object in it, or in the art of a linked opacity mask in it, is pixel-aligned.
|
||||
/// It goes only where a transform of `n` goes: not into unlinked masks.
|
||||
fn holds_aligned(n: &Node) -> bool {
|
||||
@@ -586,14 +598,19 @@ fn round_strokes(n: &mut Node) -> bool {
|
||||
/// Snap path object `n`'s horizontal and vertical straight segments ([`snap_segments`]). A path
|
||||
/// with Live Corners snaps the outline its corners are cut from. Another live shape is moved and
|
||||
/// scaled as a whole instead, from its path's bounds to the bounds of the snapped path, so that it
|
||||
/// stays a live shape. Returns whether it changed.
|
||||
/// stays a live shape. Relative radii of corners the snap straightens or bends are converted as an
|
||||
/// anchor edit converts them ([`vectorcraft_doc::rebase_relative_radii`]). Returns whether it changed.
|
||||
fn snap_path_node(n: &mut Node, half: bool, sc: Scaling) -> bool {
|
||||
let NodeKind::Path { path, live, .. } = &mut n.kind else { return false };
|
||||
let Some(shape) = live.as_deref_mut() else { return snap_segments(path, half) };
|
||||
if let LiveShape::Path { base, .. } = shape {
|
||||
if let LiveShape::Path { base, radii, radii_relative, .. } = shape {
|
||||
let before = radii_relative.then(|| base.clone());
|
||||
if !snap_segments(base, half) {
|
||||
return false;
|
||||
}
|
||||
if let Some(before) = before {
|
||||
vectorcraft_doc::rebase_relative_radii(&before, base, radii);
|
||||
}
|
||||
*path = shape.to_path();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// The Objects on Path groups of `ids`: the ones among them, and the innermost one around each
|
||||
/// object in one.
|
||||
fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let group = d.ancestry(*id).unwrap_or_default().into_iter().rev().find(|a| d.node(*a).is_some_and(is_objects_on_path));
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with Live Corners that store a radius (rounded, or straightened by an earlier move), each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target, and a straightened corner that bends again rounds again; refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -266,6 +266,22 @@ fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl F
|
||||
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
|
||||
continue;
|
||||
};
|
||||
// Relative radii of corners the edit bent and the snap straightened again are converted
|
||||
// twice, and can come back off by rounding: an outline back where it was, with the same
|
||||
// kinds and those radii, counts as no change.
|
||||
if let Some(vectorcraft_doc::LiveShape::Path { base, radii, kinds, radii_relative: true }) = live.as_deref() {
|
||||
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
|
||||
&& let Some(vectorcraft_doc::LiveShape::Path { base: b, radii: r, kinds: k, radii_relative: true }) = after.as_deref()
|
||||
&& b == base
|
||||
&& k == kinds
|
||||
&& r.len() == radii.len()
|
||||
&& r.iter().zip(radii).all(|(x, y)| (x - y).abs() <= 1e-12 * x.abs().max(y.abs()).max(1.0))
|
||||
{
|
||||
after.clone_from(live);
|
||||
after_path.clone_from(path);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
|
||||
// needs the comparison below.
|
||||
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
|
||||
|
||||
@@ -357,7 +357,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
let (natural, warnings) = (s.frame, s.warnings.clone());
|
||||
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
|
||||
}
|
||||
let anchored = matches!(format.id, "dxf" | "dwg") && (opts.dxf.fit || !opts.dxf.center);
|
||||
let anchored = (format.id == "dxf" || fileio::reads_as_dwg(format.id)) && (opts.dxf.fit || !opts.dxf.center);
|
||||
let (mut doc, warnings) = {
|
||||
// Of the open options, only a DXF or DWG drawing's apply (the colour mode stays the file's).
|
||||
let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() };
|
||||
@@ -380,7 +380,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored);
|
||||
let layers = std::mem::take(&mut doc.layers);
|
||||
let symbols = doc.symbol_boxes();
|
||||
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "dwg" | "hpgl") {
|
||||
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") || fileio::reads_as_dwg(format.id) {
|
||||
// An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard),
|
||||
// as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By
|
||||
// default, as Illustrator places one, it is its art's bounds.
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_doc::{AppearanceItem, CompositeFont, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::super::Result;
|
||||
use super::super::clipboard::SymbolOptions;
|
||||
@@ -545,17 +545,22 @@ fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, bru
|
||||
|
||||
/// Discover the incoming resource frontier and its composite-font users before planning
|
||||
/// names or changing either document. Resource order and the no-composite fast path stay shared.
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec<Brush>, BTreeSet<String>, BTreeSet<String>) {
|
||||
let mut used = Used::default();
|
||||
let composites = !src.composite_fonts.is_empty();
|
||||
let mut families = BTreeSet::new();
|
||||
let mut note_family = |name: &mut String| {
|
||||
families.insert(name.to_lowercase());
|
||||
let mut dimension_families = BTreeSet::new();
|
||||
let mut note_families = |node: &mut Node| {
|
||||
if let Some(dimension) = &node.extras().dimension {
|
||||
dimension_families.insert(dimension.options.font_family.to_lowercase());
|
||||
}
|
||||
node_families(node, &mut |name| {
|
||||
families.insert(name.to_lowercase());
|
||||
});
|
||||
};
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(n, &mut |node| node_families(node, &mut note_family));
|
||||
each_mut(n, &mut note_families);
|
||||
}
|
||||
}
|
||||
let src_brushes = vectorcraft_brush::library(src);
|
||||
@@ -586,20 +591,26 @@ fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, B
|
||||
for mut a in art {
|
||||
refs(&mut a, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
|
||||
each_mut(&mut a, &mut note_families);
|
||||
}
|
||||
}
|
||||
}
|
||||
(used, src_brushes, families)
|
||||
(used, src_brushes, families, dimension_families)
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes);
|
||||
let composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty();
|
||||
let (used, mut src_brushes, families, dimension_families) = collect_resources(src, nodes, composites);
|
||||
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
|
||||
// A family the source does not define as a composite font, which the destination defines as
|
||||
// one, would draw in the destination's composite font after placement.
|
||||
let undefined_clash = families
|
||||
.iter()
|
||||
.any(|family| CompositeFont::named(&src.composite_fonts, family).is_none() && CompositeFont::named(&dst.composite_fonts, family).is_some());
|
||||
// All representability/validation errors precede incoming or destination mutation.
|
||||
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dimension_families, dst, cmd)?) };
|
||||
let staged;
|
||||
let mut aliased = false;
|
||||
let src = if let Some(plan) = &plan {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
/// Commands a plug-in may call when its manifest lists them, in order.
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.artboardGuides",
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
@@ -23,6 +24,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.cleanup.fix",
|
||||
"addon.cleanup.joinText",
|
||||
"addon.cleanup.rejoin",
|
||||
"addon.cleanup.releaseAll",
|
||||
"addon.cleanup.removeBreaks",
|
||||
"addon.cleanup.replaceFonts",
|
||||
"addon.cleanup.resetTextTransform",
|
||||
|
||||
@@ -402,6 +402,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
|
||||
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
|
||||
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
|
||||
p!("smoothBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images", bool),
|
||||
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
|
||||
p!(
|
||||
"updateLinks",
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properti
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with both the color and its model unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist,
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Script Palette Event",
|
||||
[],
|
||||
None,
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; when a waiting event's run cannot begin in the app, the status bar shows the error and the events in line wait until the next input in the window, another script.palette.event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the recoveryFolder or recoveryOffForComplex preference; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
always,
|
||||
palette_event
|
||||
),
|
||||
|
||||
@@ -4,8 +4,10 @@ use super::{NodeId, Value, cmd, find_command};
|
||||
/// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute
|
||||
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
|
||||
/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
|
||||
/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [
|
||||
/// on it, and Add Artboard Guides puts its guide around it. A `command.batch` given `artboard`
|
||||
/// passes it on to each of their steps that names none.
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 11] = [
|
||||
"addon.arrange.artboardGuides",
|
||||
"edit.copy",
|
||||
"edit.cut",
|
||||
"edit.pasteInPlace",
|
||||
@@ -37,10 +39,11 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 38] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
("addon.arrange.artboardGuides", "artboard"),
|
||||
("edit.newDocumentFromState", "created"),
|
||||
("document.save", "modified"),
|
||||
("file.saveAs", "modified"),
|
||||
|
||||
@@ -163,6 +163,13 @@ impl AutomationRoots {
|
||||
within(&self.read, &other.read) && within(&self.write, &other.write)
|
||||
}
|
||||
|
||||
/// Whether these roots and `other` let the same files be read: each read root of either lies
|
||||
/// inside a read root of the other.
|
||||
pub(crate) fn same_reads(&self, other: &Self) -> bool {
|
||||
let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved)));
|
||||
within(&self.read, &other.read) && within(&other.read, &self.read)
|
||||
}
|
||||
|
||||
/// The roots for people: `read A, B; write C` (`none` for a kind without any).
|
||||
pub fn describe(&self) -> String {
|
||||
let list = |roots: &[Root]| {
|
||||
|
||||
@@ -458,6 +458,13 @@ pub struct Session {
|
||||
/// The pointer button is held: the last pointer event was a press or a drag, not a release or
|
||||
/// a move ([`Session::pointer_held`]).
|
||||
pub(crate) pointer_held: bool,
|
||||
/// While [`Session::pointer_samples`] feeds a pass's samples to the tool, the tool's previews are
|
||||
/// held in [`Self::sampled_preview`] instead of being applied.
|
||||
pub(crate) holds_previews: bool,
|
||||
/// The last preview the tool asked for during [`Session::pointer_samples`], not yet applied. It is
|
||||
/// applied before any other action of the tool, before a preview of another command, and when the
|
||||
/// samples end.
|
||||
pub(crate) sampled_preview: Option<(String, serde_json::Value)>,
|
||||
/// The id and persistent options of the tool when the press under way began, which a dropped
|
||||
/// press puts back ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
|
||||
|
||||
@@ -306,7 +306,16 @@ pub struct Prefs {
|
||||
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
|
||||
/// fallback font with the missing-font warning (#4568).
|
||||
pub pdf_import_embedded_fonts: bool,
|
||||
/// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: smooths images
|
||||
/// (except images marked pixelated, such as envelope images made with Anti-Alias off) while Pixel Preview draws its own pixel raster (the view zoomed above one screen pixel per
|
||||
/// document pixel and the region within the largest texture side); otherwise
|
||||
/// `smooth_bitmaps` applies, in Pixel Preview too.
|
||||
pub anti_aliased_bitmaps: bool,
|
||||
/// File Handling › Display Bitmaps as Anti-aliased Images: placed and embedded bitmaps drawn
|
||||
/// larger than their pixels are smoothed (on by default); off, each of their pixels shows as a
|
||||
/// hard-edged square (#10712). It applies whenever Pixel Preview does not draw its own pixel
|
||||
/// raster; while it does, `anti_aliased_bitmaps` applies.
|
||||
pub smooth_bitmaps: bool,
|
||||
pub update_links: String,
|
||||
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
|
||||
/// becomes when the open or place does not say (`text`: editable type in the file's fonts;
|
||||
@@ -698,6 +707,7 @@ impl Default for Prefs {
|
||||
low_res_proxy_eps: false,
|
||||
pdf_import_embedded_fonts: true,
|
||||
anti_aliased_bitmaps: false,
|
||||
smooth_bitmaps: true,
|
||||
update_links: s("askWhenModified"),
|
||||
pdf_text_as: s("text"),
|
||||
copy_as_svg: true,
|
||||
|
||||
@@ -274,6 +274,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
super::dom::forget_removed(h)?;
|
||||
if let Err(e) = r {
|
||||
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
|
||||
return Err(match e {
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the
|
||||
//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and
|
||||
//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel.
|
||||
//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and
|
||||
//! returns the color picked for OK, or a new object of the color it was given for Cancel.
|
||||
//!
|
||||
//! In the app the run waits at the call for the person's answer, and spends no fuel while it
|
||||
//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with
|
||||
//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no
|
||||
//! answer left, or with the next answer for another kind of dialog, ends the run. The report's
|
||||
//! `dialogs` lists each dialog and its answer.
|
||||
//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts
|
||||
//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s
|
||||
//! `answers`; a call with no answer left, or with the next answer for another kind of dialog,
|
||||
//! ends the run. The report's `dialogs` lists each dialog and its answer.
|
||||
//!
|
||||
//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`],
|
||||
//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and
|
||||
@@ -21,6 +23,7 @@ use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
|
||||
|
||||
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
|
||||
@@ -51,22 +54,34 @@ pub enum DialogKind {
|
||||
Prompt,
|
||||
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
|
||||
Window,
|
||||
/// `app.showColorPicker`.
|
||||
ColorPicker,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
/// The function's name, which is also the `kind` of an answer and of a report's dialog.
|
||||
/// The `kind` of an answer and of a report's dialog, which is also the function's name for
|
||||
/// `alert`, `confirm` and `prompt`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Window => "window",
|
||||
Self::ColorPicker => "colorPicker",
|
||||
}
|
||||
}
|
||||
|
||||
/// The function's name, as its errors give it.
|
||||
fn function(self) -> &'static str {
|
||||
match self {
|
||||
Self::ColorPicker => "showColorPicker",
|
||||
k => k.id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a script opened, which waits for its answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptDialog {
|
||||
pub kind: DialogKind,
|
||||
pub message: String,
|
||||
@@ -78,10 +93,15 @@ pub struct ScriptDialog {
|
||||
pub no_as_default: bool,
|
||||
/// `prompt`: the text its field starts with.
|
||||
pub preset: String,
|
||||
/// `showColorPicker`: the color the picker starts with. `None` for the other dialogs.
|
||||
pub color: Option<Color>,
|
||||
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
|
||||
/// gives an RGB pick back as CMYK. False for the other dialogs.
|
||||
pub cmyk_document: bool,
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum DialogAnswer {
|
||||
/// OK, for `alert`.
|
||||
Ok,
|
||||
@@ -91,6 +111,8 @@ pub enum DialogAnswer {
|
||||
Prompt(Option<String>),
|
||||
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
|
||||
Window(Vec<UiStep>),
|
||||
/// OK with the color picked, or Cancel (`None`), for `showColorPicker`.
|
||||
ColorPicker(Option<Color>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
@@ -100,30 +122,101 @@ impl DialogAnswer {
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
Self::Window(_) => DialogKind::Window,
|
||||
Self::ColorPicker(_) => DialogKind::ColorPicker,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
/// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it
|
||||
/// started with.
|
||||
fn data(&self, d: &ScriptDialog) -> Data {
|
||||
match self {
|
||||
Self::Ok | Self::Window(_) => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string or `null`.
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands
|
||||
/// take it, or `null`.
|
||||
fn json(&self) -> Value {
|
||||
match self {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
Self::Window(steps) => json!(steps.len()),
|
||||
Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the paint commands take it.
|
||||
fn color_json(c: &Color) -> Value {
|
||||
serde_json::to_value(c).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from
|
||||
/// -128 to 128, as a script's `LabColor` takes them?
|
||||
fn in_range(c: &Color) -> bool {
|
||||
let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x));
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => unit(&[r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]),
|
||||
Color::Gray { k } => unit(&[k]),
|
||||
Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key
|
||||
/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components
|
||||
/// into their ranges. An array or object is checked as written too, in f64 and with the scale
|
||||
/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded
|
||||
/// onto it when it narrows to f32.
|
||||
fn answer_color(v: &Value) -> Option<Color> {
|
||||
// Parsed as f64, so that a value just past a limit is not rounded onto it.
|
||||
let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x));
|
||||
let num = |o: &serde_json::Map<String, Value>, key: &str| o.get(key).and_then(Value::as_f64);
|
||||
let written_in_range = match v {
|
||||
Value::String(s) if Color::from_hex(s).is_none() => {
|
||||
let mut it = s.split_whitespace();
|
||||
let model = it.next()?.to_ascii_lowercase();
|
||||
let n: Vec<f64> = it.map(|t| t.parse::<f64>().ok().filter(|x| x.is_finite())).collect::<Option<_>>()?;
|
||||
match (model.as_str(), n.as_slice()) {
|
||||
("rgb", [_, _, _]) => within(&n, 0.0, 255.0),
|
||||
("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0),
|
||||
("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0),
|
||||
Value::Object(o) => {
|
||||
if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) {
|
||||
let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 };
|
||||
within(&[c, m, y, k], 0.0, scale)
|
||||
} else if let Some(g) = o.get("gray") {
|
||||
let g = g.as_f64()?;
|
||||
within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0)
|
||||
} else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) {
|
||||
within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0)
|
||||
} else {
|
||||
match o.get("model").and_then(Value::as_str) {
|
||||
Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0),
|
||||
Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0),
|
||||
Some("gray") => within(&[num(o, "k")?], 0.0, 1.0),
|
||||
Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
if !written_in_range {
|
||||
return None;
|
||||
}
|
||||
crate::cmd::color_value(v).filter(in_range)
|
||||
}
|
||||
|
||||
/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together
|
||||
/// is a line break; every other control character, and with `lines` false every line break too,
|
||||
/// shows as its Unicode Control Picture, as the Script Console shows it.
|
||||
@@ -156,9 +249,10 @@ pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
|
||||
/// empty list.
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}`, `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]) and `{kind: "colorPicker", value: color | null}`, the color in any form
|
||||
/// the paint commands take. An empty object, which the parameter took before dialogs existed, is
|
||||
/// an empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
@@ -196,7 +290,12 @@ fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm, prompt or window"),
|
||||
(Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)),
|
||||
(Some("colorPicker"), v) => match answer_color(v) {
|
||||
Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))),
|
||||
None => Err("is a color picker's answer, whose `value` must be a color or null"),
|
||||
},
|
||||
_ => Err("must have `kind` alert, confirm, prompt, window or colorPicker"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,9 +564,10 @@ impl Dialogs {
|
||||
}
|
||||
let Some(d) = waiting.take() else { return false };
|
||||
drop(waiting);
|
||||
let data = answer.data(&d);
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { data };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
@@ -523,13 +623,16 @@ impl Dialogs {
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
if d.kind != DialogKind::ColorPicker {
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
}
|
||||
match d.kind {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
DialogKind::Window => None,
|
||||
DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)),
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
self.push_record(Value::Object(r));
|
||||
@@ -584,7 +687,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) };
|
||||
let (title, error_icon, no_as_default, preset) = match kind {
|
||||
DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
// `showColorPicker` opens through `show_color_picker`, not here.
|
||||
DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()),
|
||||
DialogKind::Prompt => {
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
@@ -601,7 +705,33 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset };
|
||||
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
|
||||
/// and a new object of `color` for Cancel.
|
||||
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
|
||||
// During a slice the session holds the run's working copy, whose active document may be one
|
||||
// the script made; between slices the app sees the documents as they were before the run.
|
||||
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
|
||||
let dialog = ScriptDialog {
|
||||
kind: DialogKind::ColorPicker,
|
||||
message: String::new(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: false,
|
||||
preset: String::new(),
|
||||
color: Some(color),
|
||||
cmyk_document,
|
||||
};
|
||||
wait_or_answer(host, dialog)
|
||||
}
|
||||
|
||||
/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of
|
||||
/// `answers`.
|
||||
fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result<Data, HostError> {
|
||||
let kind = dialog.kind;
|
||||
let name = kind.function();
|
||||
let d = &host.dialogs;
|
||||
if d.framed {
|
||||
if !d.can_wait.get() {
|
||||
@@ -616,11 +746,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
match next {
|
||||
Some(a) if a.kind() == kind => {
|
||||
d.record(&dialog, a.json());
|
||||
Ok(a.data())
|
||||
Ok(a.data(&dialog))
|
||||
}
|
||||
Some(a) => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id())))
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id())))
|
||||
}
|
||||
None => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
|
||||
+194
-62
@@ -38,7 +38,8 @@
|
||||
//! - After `documents[0]`, documents are listed from the one active most recently to the one
|
||||
//! active longest ago. A change a script makes to a document in the back does not move it.
|
||||
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
|
||||
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
|
||||
//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the
|
||||
//! order of a layer's, a group's and a compound path's lists. An index out of range gives
|
||||
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
|
||||
//! - Script coordinates are points with Y up from the bottom of the first artboard
|
||||
//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of
|
||||
@@ -110,6 +111,7 @@ mod print;
|
||||
mod raster_capture;
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT;
|
||||
mod resources;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
@@ -117,18 +119,37 @@ mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
/// Resources a command's steps removed or renamed (a document's uid, the kind and the name), and
|
||||
/// the names the steps compared.
|
||||
type GoneResources = (HashSet<(u64, ResourceKind, String)>, u64);
|
||||
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
/// ([`variables::before_command`]).
|
||||
/// ([`variables::before_command`]). The resources earlier commands removed stay noted until the
|
||||
/// run next looks up a resource object or [`forget_removed`] runs.
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
|
||||
tracing::before_command(h);
|
||||
variables::before_command(h, id)
|
||||
}
|
||||
|
||||
/// Charges the run for the resource names the last command's steps compared, whether it was kept
|
||||
/// or not, and whether `vc.run` or the object model ran it.
|
||||
pub(super) fn charge_scanned(h: &Host) -> std::result::Result<(), HostError> {
|
||||
let scanned = std::mem::take(&mut h.dom.resources_gone.borrow_mut().1);
|
||||
if scanned > 0 {
|
||||
h.charge_call(scanned)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After each command a script runs ([`variables::after_command`]).
|
||||
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataSet>)>) {
|
||||
variables::after_command(h, before);
|
||||
@@ -142,6 +163,8 @@ pub const STALE_ITEM: &str = "Stale page item";
|
||||
const TRACING_NAME: &str = "The name of a tracing cannot be changed";
|
||||
/// The error for the tracing's name given to a group that holds an image first.
|
||||
const NOT_A_TRACING: &str = "Only Image Trace can make a tracing";
|
||||
/// The error of `move` and `remove()` for a tracing's source image.
|
||||
const SOURCE_STAYS: &str = "a tracing's source image cannot leave its tracing";
|
||||
/// The error for a document that was closed, or that came from an earlier run.
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
@@ -199,16 +222,21 @@ thread_local! {
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// points, the swatches, symbols, styles and brushes the run's objects name, whether a call's own
|
||||
/// savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and
|
||||
/// layers its layers and groups gave, the active artboard of each document, and the tool
|
||||
/// `app.selectTool` chose last.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
|
||||
paths: RefCell<Vec<ItemList>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
/// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's
|
||||
/// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is
|
||||
/// unchanged.
|
||||
paths: RefCell<Vec<paths::PathList>>,
|
||||
/// A path and its subpaths with the point changes the run has made to it and not written yet
|
||||
/// ([`flush`]).
|
||||
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
|
||||
@@ -227,14 +255,19 @@ pub(super) struct State {
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
/// The resources the steps of kept commands removed or renamed, which the next lookup of a
|
||||
/// resource object or [`forget_removed`] marks stale, and how many names the last command's
|
||||
/// steps compared, which [`charge_scanned`] charges when the command ends.
|
||||
resources_gone: RefCell<GoneResources>,
|
||||
/// The swatches, symbols, styles and brushes the run's objects name ([`resources`]).
|
||||
resources: RefCell<resources::Table>,
|
||||
saving: Cell<bool>,
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
art: RefCell<Vec<layers::ArtList>>,
|
||||
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
|
||||
/// first, each kept while its document is unchanged.
|
||||
layers: RefCell<Vec<layers::LayerList>>,
|
||||
/// The last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first,
|
||||
/// each kept while its document is unchanged.
|
||||
layer_lists: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
@@ -299,6 +332,9 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
flush(h)?;
|
||||
// The removals noted before `f` are applied first, so that a failure drops only the ones its
|
||||
// commands noted.
|
||||
resources::settle_removed(h);
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
@@ -316,32 +352,23 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// The resources `f`'s commands removed are back with the documents.
|
||||
h.dom.resources_gone.borrow_mut().0.clear();
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
/// Makes the run's swatch, symbol, style and brush objects whose resource a command removed or
|
||||
/// renamed stale, so a new resource that takes the name later is not theirs, and checks every
|
||||
/// object against the documents after a `vc.run` command. The check is charged to the run.
|
||||
pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> {
|
||||
resources::forget_removed(h)
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
|
||||
const KEPT_LISTS: usize = 8;
|
||||
|
||||
/// The list kept in `lists` for the document `st`, while that document is unchanged.
|
||||
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
|
||||
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
|
||||
let mut l = lists.borrow_mut();
|
||||
l.retain(|(uid, ..)| *uid != st.uid);
|
||||
if l.len() >= KEPT_LISTS {
|
||||
l.remove(0);
|
||||
}
|
||||
l.push((st.uid, st.doc.clone(), ids.clone()));
|
||||
}
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
@@ -623,6 +650,15 @@ fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] {
|
||||
[float(h.run), float(st.uid), high, low, float(st.reverts)]
|
||||
}
|
||||
|
||||
/// The handle of a collection that lists the art of the layer, group or compound path `id` in the
|
||||
/// document `uid`, with the document's revert count as [`node_handle`] gives it, so that a
|
||||
/// collection read before File > Revert is stale.
|
||||
fn scoped_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
[float(h.run), float(uid), high, low, float(reverts)]
|
||||
}
|
||||
|
||||
fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
|
||||
let &[run, uid, high, low, reverts] = handle else { return None };
|
||||
let doc = find_doc(h, run, uid)?;
|
||||
@@ -691,7 +727,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id)))
|
||||
}
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
None => layers::layer_ref(h, st.uid, id),
|
||||
},
|
||||
None => Data::Null,
|
||||
}
|
||||
@@ -866,7 +902,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
|
||||
} else {
|
||||
// One `select.anchorsMany` selects every object in its order: a partly selected path with
|
||||
// its anchors, a whole path with all of them and any other object with none.
|
||||
// its anchors, a whole path with all of them and any other object with none. A path with
|
||||
// only segments selected gets no anchors here, so `select.segments` below selects it with
|
||||
// just those segments.
|
||||
let items: Vec<Value> = kept
|
||||
.iter()
|
||||
.map(|i| {
|
||||
@@ -1055,11 +1093,31 @@ fn ends_run(e: &HostError) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed, and notes
|
||||
/// the swatches, symbols, styles and brushes it removed or renamed with the ones earlier commands
|
||||
/// removed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
let (taken, scanned) = {
|
||||
let mut s = h.session.borrow_mut();
|
||||
let trail = &mut s.script_style_trail;
|
||||
(std::mem::take(&mut trail.resources_gone), std::mem::take(&mut trail.resources_scanned))
|
||||
};
|
||||
{
|
||||
let mut gone = h.dom.resources_gone.borrow_mut();
|
||||
gone.0.extend(taken);
|
||||
gone.1 = gone.1.saturating_add(scanned);
|
||||
}
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// After a command that is not kept: the resource names its steps compared are charged
|
||||
/// ([`charge_scanned`]), and the resources they removed are not marked stale.
|
||||
pub(super) fn keep_scanned(h: &Host) {
|
||||
let scanned = std::mem::take(&mut h.session.borrow_mut().script_style_trail.resources_scanned);
|
||||
let mut gone = h.dom.resources_gone.borrow_mut();
|
||||
gone.1 = gone.1.saturating_add(scanned);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
@@ -1155,12 +1213,25 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`,
|
||||
/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]).
|
||||
fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer {
|
||||
let color = colors::solid(arg(a, 1), "showColorPicker's color")?;
|
||||
super::dialogs::show_color_picker(h, color)
|
||||
}
|
||||
|
||||
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
|
||||
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
|
||||
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
|
||||
fn path_key(p: &str) -> String {
|
||||
path_key_on(p, cfg!(windows))
|
||||
}
|
||||
|
||||
/// [`path_key`] treating every path as a Windows path when `windows`, else only one that starts
|
||||
/// with a drive letter.
|
||||
pub(crate) fn path_key_on(p: &str, windows: bool) -> String {
|
||||
let b = p.as_bytes();
|
||||
let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
let windows = windows || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
@@ -1614,9 +1685,17 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
|
||||
// does not stand in for it. Settings the built-in preset refuses are an error.
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
let mut shadowed_by = None;
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
let full = first.clone().with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim()));
|
||||
if shadowed {
|
||||
// `file.new` would find the saved preset of that name first, so the name is left out
|
||||
// and the built-in preset's settings, with `presetSettings` over them, go as params.
|
||||
shadowed_by = Some(first.clone());
|
||||
} else {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
}
|
||||
if let Value::Object(settings) = full.to_json() {
|
||||
for key in BUILT_IN_SETTINGS {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
@@ -1635,6 +1714,15 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
let reason = e["reason"].as_str().unwrap_or_default();
|
||||
return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}")));
|
||||
}
|
||||
// The built-in preset's settings went as params: Recent keeps its name, as `file.new`
|
||||
// keeps a preset's name, unless its size changed (turning it doesn't count).
|
||||
if let Some(first) = &shadowed_by {
|
||||
let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) {
|
||||
r.name.clone_from(&first.name);
|
||||
}
|
||||
}
|
||||
// Each warning from reading the profile's file goes to the console.
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut));
|
||||
@@ -2222,7 +2310,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
}
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2231,7 +2319,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
@@ -2239,7 +2327,7 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
layers::scoped_typename(h, a)?;
|
||||
return Ok(text("[PageItems]"));
|
||||
}
|
||||
@@ -2248,7 +2336,7 @@ fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2261,30 +2349,55 @@ fn probing(a: &[Data]) -> bool {
|
||||
matches!(arg(a, 2), Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The answer of an indexer called with a name, from `found`, the collection's `getByName`: a
|
||||
/// name nothing has gives `undefined` for `name in collection` ([`probing`]) and throws otherwise.
|
||||
fn by_name_or_probe(a: &[Data], found: Answer) -> Answer {
|
||||
match found {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// The position an indexer key names when it is an array index, 0 to 2^32 - 2.
|
||||
fn position(n: f64) -> Option<usize> {
|
||||
whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// The arguments of an indexer called with a number that is not an array index, such as `-1` or
|
||||
/// `1.5`, with that key given as the text of the number, the name it is looked up by: a key such
|
||||
/// as `"-1"` reaches an indexer as a number.
|
||||
fn number_named(a: &[Data]) -> Option<Vec<Data>> {
|
||||
let Data::Number(n) = arg(a, 1) else { return None };
|
||||
if position(*n).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut named = a.to_vec();
|
||||
named[1] = text(vectorcraft_js::number_to_string(*n));
|
||||
Some(named)
|
||||
}
|
||||
|
||||
/// The answer of an indexer for a number key looked up as a name ([`number_named`]), from `found`,
|
||||
/// the collection's `getByName`: `undefined` when nothing has the name.
|
||||
fn named_or_undefined(found: Answer) -> Answer {
|
||||
match found {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::String(_) => by_name_or_probe(a, items_by_name(h, a)),
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
None => named_or_undefined(items_named(h, doc, &vectorcraft_js::number_to_string(*n))),
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
@@ -2296,7 +2409,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2315,7 +2428,7 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
@@ -2335,7 +2448,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
|
||||
/// and so does an object on a locked artboard.
|
||||
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2667,8 +2780,8 @@ fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
|
||||
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
|
||||
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
|
||||
/// path's.
|
||||
/// the visible bounds leave them out, a clip group or clipping layer gives only its clipping
|
||||
/// path's, and the source art a Shaper Group or a tracing keeps is left out.
|
||||
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
|
||||
*steps += 1;
|
||||
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
|
||||
@@ -2678,7 +2791,7 @@ fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
|
||||
*steps += 1;
|
||||
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
|
||||
}
|
||||
let children = n.children().map_or(&[][..], Vec::as_slice);
|
||||
let children = n.editing_children();
|
||||
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
|
||||
for c in children {
|
||||
r = take_in_handles(c, r, steps);
|
||||
@@ -2840,7 +2953,8 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or
|
||||
/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`]
|
||||
/// refuses it. A compound path whose last path this is stays, empty.
|
||||
/// refuses it. A tracing's source image is refused when it is shown as well. A compound path whose
|
||||
/// last path this is stays, empty.
|
||||
fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let (whole, on_locked) = with_doc(h, item.doc, |_, st| {
|
||||
@@ -2852,6 +2966,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// A tracing keeps its source image when a script has shown it, as `move` keeps it there.
|
||||
if with_doc(h, item.doc, |_, st| crate::cmd::is_trace_source(&st.doc, item.id)) {
|
||||
return Err(HostError::Error(SOURCE_STAYS.into()));
|
||||
}
|
||||
// An image left first in an ordinary group named as a tracing would make that group one.
|
||||
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
@@ -3078,7 +3196,7 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
if d.parent_of(id) == Some(to.parent) {
|
||||
return Ok(0);
|
||||
}
|
||||
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
|
||||
return Err(HostError::Error(SOURCE_STAYS.into()));
|
||||
}
|
||||
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
|
||||
// The clipping path itself, put back where it is, stays the clipping path.
|
||||
@@ -3281,7 +3399,7 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `toString()` of an object without a name: `[Class]`.
|
||||
fn class_text(name: &'static str) -> HostMember {
|
||||
pub(super) fn class_text(name: &'static str) -> HostMember {
|
||||
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
|
||||
}
|
||||
|
||||
@@ -3348,8 +3466,17 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in
|
||||
ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS)
|
||||
// An enumeration the save or rasterize options also define (`SVGFontType`, `AntiAliasingMethod`) is defined once,
|
||||
// with every member.
|
||||
let screens = save_open::screens::ENUMS.iter().filter(|(n, _)| !save_open::ENUMS.iter().chain(raster_capture::ENUMS).any(|(m, _)| m == n));
|
||||
for (name, members) in ENUMS
|
||||
.iter()
|
||||
.chain(save_open::ENUMS)
|
||||
.chain(screens)
|
||||
.chain(print::ENUMS)
|
||||
.chain(raster_capture::ENUMS)
|
||||
.chain(images::ENUMS)
|
||||
.chain(tracing::ENUMS)
|
||||
{
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
@@ -3360,6 +3487,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
paths::install_enums(realm)?;
|
||||
resources::install_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
@@ -3381,6 +3509,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("showColorPicker", method(l, app_show_color_picker), returns("Color", &[("color", "Color")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
@@ -3472,9 +3601,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(resources::document_members(l));
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
@@ -3631,13 +3760,16 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = layers::members(c, l);
|
||||
members.extend(variables::item_members(l, c));
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
match *c {
|
||||
"PathItem" => members.extend(paths::path_item_members(l)),
|
||||
"SymbolItem" => members.extend(resources::symbol_item_members(l)),
|
||||
_ => {}
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(resources::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(layers::classes(l));
|
||||
|
||||
@@ -10,11 +10,16 @@
|
||||
//! Components are checked when a color is assigned to an object, and a value out of range throws a
|
||||
//! `RangeError` with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0,
|
||||
//! and `new SpotColor()` starts with a `tint` of 100;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
//! says. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. A `SpotColor` (<https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/>)
|
||||
//! can be assigned to a path's `fillColor` and `strokeColor`, not to a swatch's `color`.
|
||||
//! `GradientColor` and `PatternColor` can be read from an object but not assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -24,7 +29,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{Link, current, num, text};
|
||||
|
||||
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
|
||||
/// The classes whose objects [`assigned`] refuses as not available yet. A path's `fillColor` and
|
||||
/// `strokeColor` take a `SpotColor` before [`assigned`] runs; a swatch's or spot's `color` does not.
|
||||
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
|
||||
|
||||
/// The components of each color class, with the value `new` gives them.
|
||||
@@ -66,7 +72,7 @@ fn shown(v: f32, scale: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
pub(in crate::script) fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
@@ -118,8 +124,20 @@ fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -
|
||||
}
|
||||
}
|
||||
|
||||
/// The `spot` and the `tint` (0 to 100, 0 when left out) of `d` when it is a `SpotColor`, else
|
||||
/// `None`.
|
||||
pub(super) fn spot_parts(d: &Data) -> std::result::Result<Option<(&Data, f64)>, HostError> {
|
||||
let Data::Object(o) = d else { return Ok(None) };
|
||||
if !matches!(o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v), Some(Data::String(s)) if s == "SpotColor") {
|
||||
return Ok(None);
|
||||
}
|
||||
let tint = component(o, "SpotColor", "tint", 0.0, 100.0)?;
|
||||
let spot = o.iter().find(|(k, _)| k == "spot").map_or(&Data::Undefined, |(_, v)| v);
|
||||
Ok(Some((spot, tint)))
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn unit(v: f64, scale: f64) -> f32 {
|
||||
pub(super) fn unit(v: f64, scale: f64) -> f32 {
|
||||
(v / scale) as f32
|
||||
}
|
||||
|
||||
@@ -149,6 +167,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color
|
||||
}))
|
||||
}
|
||||
|
||||
/// The solid color a script gave `what`, checked as [`assigned`] checks it: a `NoColor`, a
|
||||
/// `GradientColor`, a `SpotColor` or a `PatternColor` throws a `TypeError`.
|
||||
pub(super) fn solid(d: &Data, what: &str) -> std::result::Result<Color, HostError> {
|
||||
let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor"));
|
||||
match assigned(d, what) {
|
||||
Ok(Some(c)) => Ok(c),
|
||||
// A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error.
|
||||
Ok(None) | Err(HostError::Error(_)) => Err(not_solid()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
|
||||
//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's
|
||||
//! `pageItems`, `groupItems`, `compoundPathItems`, `pathItems` and `textFrames`, and a compound path's
|
||||
//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
|
||||
//! hold every group or compound path at any depth, in the order of the document's `pageItems`.
|
||||
//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes
|
||||
@@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
|
||||
|
||||
use super::{
|
||||
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref,
|
||||
later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity,
|
||||
returns, text, typed, typename, whole, with_doc,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method,
|
||||
named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename,
|
||||
whole, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
@@ -66,8 +66,6 @@ enum Kind {
|
||||
Group,
|
||||
/// Compound paths (`CompoundPathItem`).
|
||||
Compound,
|
||||
/// Paths (`PathItem`).
|
||||
Path,
|
||||
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
|
||||
Text,
|
||||
}
|
||||
@@ -78,7 +76,6 @@ impl Kind {
|
||||
Kind::Any => "PageItems",
|
||||
Kind::Group => "GroupItems",
|
||||
Kind::Compound => "CompoundPathItems",
|
||||
Kind::Path => "PathItems",
|
||||
Kind::Text => "TextFrames",
|
||||
}
|
||||
}
|
||||
@@ -88,7 +85,6 @@ impl Kind {
|
||||
Kind::Any => typename(n).is_some(),
|
||||
Kind::Group => typename(n) == Some("GroupItem"),
|
||||
Kind::Compound => typename(n) == Some("CompoundPathItem"),
|
||||
Kind::Path => typename(n) == Some("PathItem"),
|
||||
Kind::Text => typename(n) == Some("TextFrame"),
|
||||
}
|
||||
}
|
||||
@@ -109,14 +105,16 @@ fn result_id(v: &Value, key: &str) -> Option<u64> {
|
||||
/// The layer `d` names, which must still be a layer of its document.
|
||||
pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> {
|
||||
let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) };
|
||||
if handle.len() != 5 {
|
||||
return Err(type_error("Layer"));
|
||||
}
|
||||
// A layer read before File › Revert is stale like the page items read with it.
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| {
|
||||
let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some());
|
||||
HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into())
|
||||
})?;
|
||||
let [run, uid, high, low, _] = handle.as_slice() else { return Err(type_error("Layer")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
// A layer read before its document was reverted is stale as the page items read then are.
|
||||
let (doc, id) = super::node_of(h, &handle).filter(|(d, _)| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
held_layer(h, doc, id)
|
||||
}
|
||||
|
||||
/// The layer `id` of `doc`, which must still be a layer of the document.
|
||||
fn held_layer(h: &Host, doc: Doc, id: NodeId) -> Result<(Doc, NodeId)> {
|
||||
let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer));
|
||||
if !ok {
|
||||
return Err(HostError::Error(STALE_LAYER.into()));
|
||||
@@ -128,14 +126,12 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> {
|
||||
layer_of(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("Layer", &layer_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it.
|
||||
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
[float(h.run), float(uid), high, low, float(reverts_of(h, uid))]
|
||||
pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
let s = h.session.borrow();
|
||||
match s.documents().iter().find(|d| d.uid == uid) {
|
||||
Some(st) => host_ref("Layer", &super::node_handle(h, st, id)),
|
||||
None => Data::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the layer `this` names with `f`.
|
||||
@@ -285,22 +281,23 @@ fn layer_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
}))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_layer(h, a)?;
|
||||
Ok(text("Layer"))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is
|
||||
/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop
|
||||
/// not counted. The list comes from [`layer_ids`], so reading it for each layer of a loop
|
||||
/// lists the layers once. Each read is still charged for the search through the list.
|
||||
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
let at = with_doc(h, doc, |_, st| {
|
||||
let list = layers_listed(h, st, st.doc.parent_of(id))?;
|
||||
let list = layer_ids(h, st, st.doc.parent_of(id))?;
|
||||
// The scan is charged by itself: a list kept from an earlier read was charged once.
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
|
||||
})?;
|
||||
@@ -535,8 +532,9 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
[run, uid, high, low, reverts] => {
|
||||
let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low, *reverts]))?;
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its layer is.
|
||||
let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?;
|
||||
Ok((doc, Some(id)))
|
||||
}
|
||||
_ => Err(type_error("Layers")),
|
||||
@@ -554,33 +552,33 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
|
||||
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top
|
||||
/// level) and the layers it listed then.
|
||||
/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers.
|
||||
pub(super) type LayerList = (u64, Arc<Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while
|
||||
/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list
|
||||
/// is charged by the objects it looks at.
|
||||
fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
/// How many lists of layers [`super::State`] keeps at once.
|
||||
pub(super) const LAYER_LISTS: usize = 4;
|
||||
|
||||
/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a
|
||||
/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at.
|
||||
fn layer_ids(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
{
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent);
|
||||
if let Some(at) = at {
|
||||
let mut lists = h.dom.layer_lists.borrow_mut();
|
||||
if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let looked_at = match parent {
|
||||
let looked = match parent {
|
||||
None => st.doc.layers.len(),
|
||||
Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len),
|
||||
};
|
||||
h.charge_call(looked_at as u64)?;
|
||||
h.charge_call(looked as u64)?;
|
||||
let ids = Rc::new(layer_list(&st.doc, parent));
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let mut lists = h.dom.layer_lists.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= ART_LISTS {
|
||||
if lists.len() >= LAYER_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), parent, ids.clone()));
|
||||
@@ -589,12 +587,12 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<V
|
||||
|
||||
fn layers_of(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
Ok(host_ref("Layers", &layer_handle(h, doc.uid, id)))
|
||||
Ok(host_ref("Layers", &super::scoped_handle(h, doc.uid, id)))
|
||||
}
|
||||
|
||||
fn layers_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn layers_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -607,30 +605,26 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("Layers"))
|
||||
}
|
||||
|
||||
/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when
|
||||
/// nothing has the name, as the document's `pageItems` does.
|
||||
fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer {
|
||||
match by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// `layers[i]`, and `layers["name"]` as `getByName` reads it. A number key that is not an array
|
||||
/// index, such as `-1`, is looked up as a name, as `pageItems` looks it up.
|
||||
fn layers_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, layers_by_name);
|
||||
return super::by_name_or_probe(a, layers_by_name(h, a));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(layers_by_name(h, &named));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
}
|
||||
|
||||
fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = layers_listed(h, st, parent)?;
|
||||
let ids = layer_ids(h, st, parent)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -640,6 +634,12 @@ fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn layers_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => layers_by_name(h, a),
|
||||
// A number is a position here, never a name ([`layers_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
layers_scope(h, arg(a, 0))?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
Data::Number(_) => match layers_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -673,7 +673,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if parent.is_none() {
|
||||
return Err(HostError::Error("a document needs at least one layer".into()));
|
||||
}
|
||||
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
|
||||
let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?;
|
||||
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
|
||||
if ids.len() > crate::cmd::layer::MAX_ROWS {
|
||||
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
|
||||
@@ -692,13 +692,11 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
[run, uid, high, low, reverts] => {
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
// A collection read before File › Revert is stale like its container.
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its container is.
|
||||
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
whole(*reverts) == Some(st.reverts)
|
||||
&& st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
@@ -755,23 +753,15 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Whether a `PageItems` or `PathItems` object's handle names its container.
|
||||
pub(super) fn is_scoped(a: &[Data], class: &str) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn scoped_kind(a: &[Data]) -> Kind {
|
||||
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any }
|
||||
}
|
||||
|
||||
/// How many times File › Revert has reloaded the document with uid `uid`.
|
||||
fn reverts_of(h: &Host, uid: u64) -> u64 {
|
||||
h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts)
|
||||
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
|
||||
/// names the container.
|
||||
pub(super) fn is_scoped(a: &[Data]) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
|
||||
match container {
|
||||
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]),
|
||||
Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)),
|
||||
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
|
||||
}
|
||||
}
|
||||
@@ -787,26 +777,19 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
|
||||
}
|
||||
|
||||
/// `collection[i]`, and `collection["name"]` as `getByName` reads it. A number key that is not an
|
||||
/// array index, such as `-1`, is looked up as a name, as the document's `pageItems` looks it up.
|
||||
fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match art_by_name(h, a, kind) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
};
|
||||
return super::by_name_or_probe(a, art_by_name(h, a, kind));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(art_by_name(h, &named, kind));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
|
||||
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
|
||||
// The text of a number that is not an array index is looked up as a name.
|
||||
None => with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}),
|
||||
}
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
@@ -814,6 +797,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
// The scan is charged by itself: a list kept from an earlier read was charged once.
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -823,8 +807,9 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => art_by_name(h, a, kind),
|
||||
// A number is a position only. A stale collection throws its stale error first.
|
||||
Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => {
|
||||
// A number is a position here, never a name ([`art_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
art_scope(h, arg(a, 0), kind.class())?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
@@ -839,7 +824,8 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
/// `removeAll()`: deletes every object the collection lists (those inside another listed one go
|
||||
/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or
|
||||
/// one on a locked artboard stops it before anything is deleted, as the document's
|
||||
/// `pageItems.removeAll()` is stopped.
|
||||
/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an
|
||||
/// ordinary group named as a tracing.
|
||||
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
@@ -852,36 +838,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
// Deleting every path of a compound path would leave it empty, so a compound path that
|
||||
// clips counts as deleted too.
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect();
|
||||
let masks = kept_clipping_paths(d, &ids);
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
@@ -892,12 +849,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
}
|
||||
refuse_kept_clipping_paths(&masks)?;
|
||||
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
|
||||
if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
@@ -908,29 +860,75 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]).
|
||||
/// The ids (at most 20) among `ids` that are the clipping path of a group or layer that keeps other
|
||||
/// objects once `ids` are deleted. Deleting one would leave the next object clipping the rest.
|
||||
/// Deleting every path of a compound path would leave it empty, so a compound path that clips
|
||||
/// counts as deleted too.
|
||||
pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec<u64> {
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
ids.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The error of a `removeAll()` that would delete the clipping paths `masks`, or `Ok` when there
|
||||
/// are none.
|
||||
pub(super) fn refuse_kept_clipping_paths(masks: &[u64]) -> std::result::Result<(), HostError> {
|
||||
if masks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)))
|
||||
}
|
||||
|
||||
/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their
|
||||
/// handle names one ([`is_scoped`]).
|
||||
pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer {
|
||||
art_length(h, a, scoped_kind(a))
|
||||
art_length(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
art_parent(h, a, scoped_kind(a))
|
||||
art_parent(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer {
|
||||
art_at(h, a, scoped_kind(a))
|
||||
art_at(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
art_by_name(h, a, scoped_kind(a))
|
||||
art_by_name(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
|
||||
art_index(h, a, scoped_kind(a))
|
||||
art_index(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
art_remove_all(h, a, scoped_kind(a))
|
||||
art_remove_all(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn groups_length(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -976,7 +974,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
}
|
||||
|
||||
pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, scoped_kind(a))
|
||||
art_typename(h, a, Kind::Any)
|
||||
}
|
||||
fn groups_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, Kind::Group)
|
||||
@@ -986,15 +984,20 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the
|
||||
/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`.
|
||||
/// → the new object.
|
||||
/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. A
|
||||
/// Live Paint group takes none. → the new object.
|
||||
fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
if let Some(c) = c {
|
||||
let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let (compound, live) = with_doc(h, doc, |_, st| {
|
||||
(st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })), super::paths::is_live_paint_group(st, c))
|
||||
});
|
||||
if compound {
|
||||
return Err(HostError::Error("a compound path holds only paths".into()));
|
||||
}
|
||||
if live {
|
||||
return Err(HostError::Error(super::paths::LIVE_PAINT_CONTAINER.into()));
|
||||
}
|
||||
}
|
||||
let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0}));
|
||||
if kind == Kind::Compound
|
||||
@@ -1039,10 +1042,6 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Path)
|
||||
}
|
||||
|
||||
fn held_groups(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Group)
|
||||
}
|
||||
@@ -1051,6 +1050,24 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Compound)
|
||||
}
|
||||
|
||||
/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]).
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
let this = arg(a, 0);
|
||||
if handle_of(this, "Layer").is_some() {
|
||||
let (doc, id) = layer_of(h, this)?;
|
||||
return Ok(super::paths::held_path_items(h, doc.uid, id));
|
||||
}
|
||||
let item = this_item_of(h, a, "GroupItem")?;
|
||||
Ok(super::paths::held_path_items(h, item.doc.uid, item.id))
|
||||
}
|
||||
|
||||
/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it
|
||||
/// ([`super::paths`]).
|
||||
fn compound_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item_of(h, a, "CompoundPathItem")?;
|
||||
Ok(super::paths::held_path_items(h, item.doc.uid, item.id))
|
||||
}
|
||||
|
||||
fn held_text(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Text)
|
||||
}
|
||||
@@ -1126,12 +1143,13 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
("groupItems", get(l, held_groups), listed("GroupItems")),
|
||||
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
|
||||
("pathItems", get(l, held_paths), listed("PathItems")),
|
||||
("textFrames", get(l, held_text), listed("TextFrames")),
|
||||
]);
|
||||
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m.extend(["symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m
|
||||
}
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths), listed("PathItems"))]),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -1195,19 +1213,22 @@ fn board_index(st: &DocState, id: u32) -> Option<usize> {
|
||||
st.doc.artboards.iter().position(|a| a.id == id)
|
||||
}
|
||||
|
||||
/// The artboard `d` names. An artboard read before its document was reverted is stale, as a page
|
||||
/// item is: the loaded document's artboard with the same id is another artboard.
|
||||
fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> {
|
||||
let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) };
|
||||
let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
// An artboard read before File › Revert is stale, as the page items read with it are.
|
||||
let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts)))
|
||||
.ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
Ok((Board { doc }, index))
|
||||
}
|
||||
|
||||
/// An `Artboard` for the artboard `id` of the document `uid`, with the document's revert count.
|
||||
fn board_ref(h: &Host, uid: u64, id: u32) -> Data {
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))])
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)])
|
||||
}
|
||||
|
||||
fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> {
|
||||
@@ -1434,13 +1455,18 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
|
||||
.ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1))))
|
||||
}
|
||||
|
||||
/// `artboards[i]`, and `artboards["name"]` as `getByName` reads it. A number key that is not an
|
||||
/// array index, such as `-1`, is looked up as a name, as `pageItems` looks it up.
|
||||
fn boards_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, boards_by_name);
|
||||
return super::by_name_or_probe(a, boards_by_name(h, a));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(boards_by_name(h, &named));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id))))
|
||||
}
|
||||
|
||||
@@ -1457,6 +1483,12 @@ fn boards_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn boards_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => boards_by_name(h, a),
|
||||
// A number is a position here, never a name ([`boards_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
boards_doc(h, a)?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
Data::Number(_) => match boards_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -1542,7 +1574,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = reverts_of(h, doc.uid);
|
||||
let reverts = with_doc(h, doc, |_, st| st.reverts);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
@@ -1600,13 +1632,14 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("printable", property(l, layer_printable, layer_set_printable), typed("boolean")),
|
||||
("preview", property(l, layer_preview, layer_set_preview), typed("boolean")),
|
||||
("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("color", property(l, layer_color, layer_set_color), typed("RGBColor")),
|
||||
("parent", get(l, layer_parent), typed("*")),
|
||||
("layers", get(l, layers_of), listed("Layers")),
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
("groupItems", get(l, held_groups), listed("GroupItems")),
|
||||
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
|
||||
("pathItems", get(l, held_paths), listed("PathItems")),
|
||||
("textFrames", get(l, held_text), listed("TextFrames")),
|
||||
("zOrderPosition", get(l, layer_z_position), typed("number")),
|
||||
("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")),
|
||||
@@ -1616,9 +1649,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]);
|
||||
layer.extend(
|
||||
["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)),
|
||||
);
|
||||
layer.extend(["symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)));
|
||||
vec![
|
||||
class("Layer", None, layer, None),
|
||||
class(
|
||||
@@ -1679,7 +1710,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("name", property(l, board_name, board_set_name), typed("string")),
|
||||
("parent", get(l, board_parent), typed("Document")),
|
||||
("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin), typed("Array")),
|
||||
("rulerPAR", property(l, board_par, board_set_par), typed("number")),
|
||||
("rulerPAR", property(l, board_par, board_set_par), MemberInfo { min: Some(0.1), max: Some(10.0), ..typed("number") }),
|
||||
("showCenter", property(l, board_center, board_set_center), typed("boolean")),
|
||||
("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")),
|
||||
("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")),
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
|
||||
//! groups and compound paths included.
|
||||
//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in
|
||||
//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden
|
||||
//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`].
|
||||
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
|
||||
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
|
||||
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
|
||||
@@ -26,8 +28,8 @@
|
||||
//! fill or stroke only.
|
||||
//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes
|
||||
//! them all.
|
||||
//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever
|
||||
//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
|
||||
//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's
|
||||
//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
|
||||
//! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds
|
||||
//! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points.
|
||||
//! Removing the last points leaves the path, with no points.
|
||||
@@ -68,9 +70,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
|
||||
use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
|
||||
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
|
||||
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command,
|
||||
coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair,
|
||||
point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -168,8 +170,16 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
|
||||
host_ref("PathItem", &handle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`point_starts`] counted the points of a path on this thread.
|
||||
static INDEX_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The index of the first point of each subpath of `subs`, followed by the number of points.
|
||||
fn starts(subs: &[SubPath]) -> Vec<usize> {
|
||||
#[cfg(test)]
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let mut out = Vec::with_capacity(subs.len() + 1);
|
||||
let mut n = 0;
|
||||
for sp in subs {
|
||||
@@ -206,6 +216,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize
|
||||
{
|
||||
return Ok(kept.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let counted = Rc::new(read_points(h, item, starts)?);
|
||||
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted.clone()));
|
||||
return Ok(counted);
|
||||
@@ -217,6 +229,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize
|
||||
{
|
||||
return Ok(kept.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let counted = Rc::new(starts(&node.path_data().ok_or_else(|| HostError::Type("this is not a PathItem".into()))?.subpaths));
|
||||
*h.dom.point_starts.borrow_mut() = Some((Counted::Node(item.doc.uid, node), counted.clone()));
|
||||
Ok(counted)
|
||||
@@ -227,6 +241,12 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
|
||||
Ok(point_starts(h, item)?.last().copied().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// How many times [`point_starts`] counted the points of a path on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn index_builds() -> u64 {
|
||||
INDEX_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
|
||||
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
|
||||
for (s, sp) in subs.iter().enumerate() {
|
||||
@@ -265,7 +285,20 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
|
||||
/// points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
edit_points_keeping(h, item, false, f)
|
||||
}
|
||||
|
||||
/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as
|
||||
/// they are, so the [`starts`] of the waiting changes stay kept.
|
||||
fn edit_points_keeping<T>(
|
||||
h: &super::Host,
|
||||
item: Item,
|
||||
counts_kept: bool,
|
||||
f: impl FnOnce(&mut Vec<SubPath>) -> T,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if !counts_kept {
|
||||
forget_waiting_starts(h);
|
||||
}
|
||||
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
|
||||
&& same_path(*waiting, item)
|
||||
{
|
||||
@@ -306,7 +339,7 @@ fn forget_waiting_starts(h: &super::Host) {
|
||||
fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> {
|
||||
let counted = point_starts(h, item)?;
|
||||
let at = locate_at(&counted, i);
|
||||
edit_points(h, item, |subs| {
|
||||
edit_points_keeping(h, item, true, |subs| {
|
||||
if let Some((s, j)) = at
|
||||
&& let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j))
|
||||
{
|
||||
@@ -372,10 +405,12 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
}
|
||||
// The document as the edit's step keeps it, read after the switch to it, which can measure
|
||||
// its type again.
|
||||
let doc = super::edit_item_with(h, item, |h| {
|
||||
let doc = h.session.borrow().active().map(|st| st.doc.clone());
|
||||
super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
|
||||
Ok(doc)
|
||||
let doc = keeping_paths(h, item, || {
|
||||
super::edit_item_with(h, item, |h| {
|
||||
let doc = h.session.borrow().active().map(|st| st.doc.clone());
|
||||
super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
|
||||
Ok(doc)
|
||||
})
|
||||
})?;
|
||||
if let Some((doc, selection)) = doc.zip(kept)
|
||||
&& let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid)
|
||||
@@ -388,10 +423,67 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape
|
||||
/// when it is a member of one, since the paint commands paint that owner in its place.
|
||||
fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread listed a document's paths ([`path_items`]), for the tests.
|
||||
pub(crate) static PATH_LIST_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds,
|
||||
/// removes and reorders no object of its own. When it succeeds, the document made no new object,
|
||||
/// and the path is not inside a Shaper group, the lists of the document's, its layers' and its
|
||||
/// groups' paths ([`path_items`]) stay kept. An edit inside a Shaper group regenerates the group's
|
||||
/// paths, which can drop a path without making a new id.
|
||||
fn keeping_paths<T>(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| {
|
||||
let s = h.session.borrow();
|
||||
if let Some(st) = s.documents().iter().find(|d| d.uid == item.doc.uid) {
|
||||
run(st);
|
||||
}
|
||||
};
|
||||
let mut kept = None;
|
||||
doc_state(h, &mut |st| {
|
||||
let in_shaper = st.doc.ancestry(item.id).unwrap_or_default().iter().filter_map(|i| st.doc.node(*i)).any(|a| a.extras().shaper.is_some());
|
||||
if !in_shaper {
|
||||
let listed = h.dom.paths.borrow().iter().any(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc));
|
||||
if listed {
|
||||
kept = Some((st.doc.clone(), st.doc.peek_next_id()));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = f()?;
|
||||
if let Some((before, next)) = kept {
|
||||
doc_state(h, &mut |st| {
|
||||
if st.doc.peek_next_id() == next {
|
||||
for list in h.dom.paths.borrow_mut().iter_mut().filter(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &before)) {
|
||||
list.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The object whose paint the path `n` with id `id` shows: the outermost compound shape it is
|
||||
/// inside, at any depth, or else its compound path when it is a member of one. The paint setters
|
||||
/// paint that owner ([`edit_paint`]).
|
||||
pub(super) fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
|
||||
let ancestors = d.ancestry(id).unwrap_or_default();
|
||||
let above = ancestors.split_last().map_or(&[][..], |(_, rest)| rest);
|
||||
if let Some(shape) = above.iter().filter_map(|i| d.node(*i)).find(|p| p.is_compound_shape()) {
|
||||
return shape;
|
||||
}
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Runs the paint command `id` with `params` on the object whose paint the path shows
|
||||
/// ([`paint_owner`]).
|
||||
fn edit_paint(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
|
||||
let owner = read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).id)?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("ids".into(), json!([owner.0]));
|
||||
}
|
||||
edit_path(h, item, id, params)
|
||||
}
|
||||
|
||||
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
|
||||
@@ -429,7 +521,11 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
o.insert("objectOnly".into(), json!(true));
|
||||
}
|
||||
}
|
||||
let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?;
|
||||
let result = if KEEP_PATHS.contains(&id) {
|
||||
keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, ¶ms)))?
|
||||
} else {
|
||||
keeping_paint(h, || edit_item(h, item, id, ¶ms))?
|
||||
};
|
||||
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
|
||||
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
|
||||
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
|
||||
@@ -439,6 +535,10 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The commands [`edit_path`] runs that change only paint, stroke or fill rule, after which the
|
||||
/// document's paths are the ones listed before ([`keeping_paths`]).
|
||||
const KEEP_PATHS: &[&str] = &["paint.setFill", "paint.setStroke", "stroke.set", "object.setOverprint", "path.setFillRule"];
|
||||
|
||||
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
|
||||
/// and gradient and the recent colors as they were before it.
|
||||
fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
@@ -452,19 +552,50 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
r
|
||||
}
|
||||
|
||||
// ---- Document.pathItems ----
|
||||
// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ----
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items. Building the list again counts
|
||||
/// the page items it looks through against the run's host-call allowance.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
|
||||
return Ok(ids);
|
||||
/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the
|
||||
/// document's), and the ids it listed then.
|
||||
pub(super) type PathList = (u64, Arc<crate::Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// How many lists of paths [`super::State`] keeps at once.
|
||||
pub(super) const PATH_LISTS: usize = 4;
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items, or of the paths directly in the
|
||||
/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their
|
||||
/// documents are unchanged, so a loop over a collection builds its list once. A new list is
|
||||
/// charged by the objects it looks at.
|
||||
fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
{
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Rc<Vec<NodeId>> =
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
#[cfg(test)]
|
||||
PATH_LIST_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. });
|
||||
let ids: Rc<Vec<NodeId>> = match container {
|
||||
Some(c) => {
|
||||
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
|
||||
h.charge_call(children.len() as u64)?;
|
||||
Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect())
|
||||
}
|
||||
None => {
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect())
|
||||
}
|
||||
};
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= PATH_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), container, ids.clone()));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
@@ -473,54 +604,66 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
|
||||
/// The `pathItems` of the layer or group `id` in the document `uid`.
|
||||
pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("PathItems", &super::scoped_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths
|
||||
/// of, if any.
|
||||
fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)),
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its container is.
|
||||
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok((doc, Some(id)))
|
||||
}
|
||||
_ => Err(HostError::Type("this is not a PathItems".into())),
|
||||
}
|
||||
doc_of(h, arg(a, 0), "PathItems")
|
||||
}
|
||||
|
||||
/// `typename` of the paths of a document that is still open.
|
||||
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
items_scope(h, a)?;
|
||||
Ok(Data::String("PathItems".into()))
|
||||
}
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
Ok(match c {
|
||||
None => host_ref("Document", &[float(h.run), float(doc.uid)]),
|
||||
Some(c) => with_doc(h, doc, |_, st| {
|
||||
if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) }
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match super::position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Some(i) => item_at(h, doc, c, i),
|
||||
None => match items_named(h, doc, c, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
@@ -530,23 +673,20 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The path at position `i` of `pathItems`, or `undefined` past the end.
|
||||
fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
fn item_at(h: &super::Host, doc: Doc, c: Option<NodeId>, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
items_named(h, doc, c, name)
|
||||
}
|
||||
|
||||
/// The first path of `pathItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
fn items_named(h: &super::Host, doc: Doc, c: Option<NodeId>, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let ids = path_items(h, st, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -554,14 +694,11 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, c, i)).transpose()? {
|
||||
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
@@ -570,18 +707,17 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or
|
||||
/// layer that keeps other objects, or a compound path or group that clips one and would be left
|
||||
/// with no visible path or visible type that lays out glyphs to clip by.
|
||||
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
|
||||
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
|
||||
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
|
||||
/// or visible type that lays out glyphs to clip by.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st, c)?;
|
||||
let d = &st.doc;
|
||||
if h.session.borrow().menu.guides_locked
|
||||
&& let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
@@ -623,8 +759,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Clear removes compound paths emptied of direct members, but keeps empty groups.
|
||||
if matches!(n.kind, NodeKind::Compound { .. })
|
||||
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
|
||||
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none()
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
@@ -657,7 +795,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
masks.push(mask.id.0);
|
||||
}
|
||||
}
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
let going: Vec<NodeId> = going.into_iter().collect();
|
||||
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
|
||||
let tracing = super::removal_makes_tracing(d, &going);
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks, tracing))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
@@ -667,14 +808,13 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
super::layers::refuse_kept_clipping_paths(&masks)?;
|
||||
if tracing {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -685,13 +825,66 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
|
||||
/// and reverses the new path's direction when `reversed`. → the new path. Selecting the new path
|
||||
/// and putting the selection back load the selected objects' paint and stroke width into new art,
|
||||
/// so new art's paint from before, the defaults a script set included, is put back.
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or
|
||||
/// locked layer or group.
|
||||
pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group";
|
||||
|
||||
/// The error of an object made in a Live Paint group, which would join the group's paths instead
|
||||
/// of staying in the group's own list.
|
||||
pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group";
|
||||
|
||||
/// Whether `id` is a Live Paint group, which takes no new objects from the object model.
|
||||
pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool {
|
||||
st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint)
|
||||
}
|
||||
|
||||
/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the
|
||||
/// selection and the current layer kept. With a layer or group `container`, the container's layer
|
||||
/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made
|
||||
/// outside the container then moves on top of its contents in the same step; a container that is
|
||||
/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]
|
||||
/// before anything is made, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → the new path.
|
||||
fn make_in(
|
||||
h: &super::Host,
|
||||
doc: Doc,
|
||||
container: Option<NodeId>,
|
||||
make: impl FnOnce(&super::Host) -> std::result::Result<NodeId, HostError>,
|
||||
) -> Answer {
|
||||
if let Some(c) = container {
|
||||
let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c)));
|
||||
if !open {
|
||||
return Err(HostError::Error(CONTAINER_LOCKED.into()));
|
||||
}
|
||||
if live {
|
||||
return Err(HostError::Error(LIVE_PAINT_CONTAINER.into()));
|
||||
}
|
||||
}
|
||||
let made = match container {
|
||||
// Making a path can take more than one command (a stroke, a reversal): a failure of a later
|
||||
// one undoes the path too.
|
||||
None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?,
|
||||
Some(c) => super::atomically(h, |h| {
|
||||
let id = on_doc(h, doc.uid, true, |h| {
|
||||
command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?;
|
||||
make(h)
|
||||
})?;
|
||||
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
|
||||
Ok(id)
|
||||
})?,
|
||||
};
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s
|
||||
/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path.
|
||||
/// Selecting the new path and putting the selection back load the selected objects' paint and
|
||||
/// stroke width into new art, so new art's paint from before, the defaults a script set included,
|
||||
/// is put back.
|
||||
fn make(h: &super::Host, doc: Doc, container: Option<NodeId>, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
keeping_paint(h, || {
|
||||
make_in(h, doc, container, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
@@ -699,10 +892,7 @@ fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) ->
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
})
|
||||
}
|
||||
|
||||
/// Argument `i`, or `default` when it is left out.
|
||||
@@ -743,13 +933,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result
|
||||
|
||||
/// `rectangle(top, left, width, height, reversed?)`.
|
||||
fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = coordinate(arg(a, 1), "top")?;
|
||||
let left = coordinate(arg(a, 2), "left")?;
|
||||
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
|
||||
let reversed = flag(a, 5, "reversed")?;
|
||||
let p = corner(h, doc, left, top)?;
|
||||
make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
}
|
||||
|
||||
/// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the
|
||||
@@ -789,7 +979,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec<Anchor> {
|
||||
/// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20,
|
||||
/// reversed = false)`: a closed path with `path.create`.
|
||||
fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = coordinate(arg(a, 1), "top")?;
|
||||
let left = coordinate(arg(a, 2), "left")?;
|
||||
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
|
||||
@@ -797,12 +987,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let reversed = flag(a, 7, "reversed")?;
|
||||
let p = corner(h, doc, left, top)?;
|
||||
let anchors: Vec<Value> = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect();
|
||||
make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
|
||||
make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
|
||||
}
|
||||
|
||||
/// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`.
|
||||
fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?;
|
||||
let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?;
|
||||
let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?);
|
||||
@@ -811,7 +1001,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("ellipse with inscribed true is not available yet".into()));
|
||||
}
|
||||
let p = corner(h, doc, left, top)?;
|
||||
make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
}
|
||||
|
||||
/// The center of a polygon or star, in document coordinates.
|
||||
@@ -823,37 +1013,38 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result<Point, H
|
||||
|
||||
/// `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed = false)`.
|
||||
fn items_polygon(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let c = center(h, doc, a)?;
|
||||
let r = size(a, 3, Some(50.0), "radius")?;
|
||||
let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?;
|
||||
let reversed = flag(a, 5, "reversed")?;
|
||||
make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
|
||||
make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
|
||||
}
|
||||
|
||||
/// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed =
|
||||
/// false)`.
|
||||
fn items_star(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let c = center(h, doc, a)?;
|
||||
let r1 = size(a, 3, Some(50.0), "radius")?;
|
||||
let r2 = size(a, 4, Some(20.0), "innerRadius")?;
|
||||
let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?;
|
||||
let reversed = flag(a, 6, "reversed")?;
|
||||
make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
|
||||
make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
|
||||
}
|
||||
|
||||
/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with
|
||||
/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open
|
||||
/// path is set back to none in the same step, and new art keeps the paint it had before.
|
||||
/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or
|
||||
/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art.
|
||||
/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set
|
||||
/// back to none in the same step, and new art keeps the paint it had before.
|
||||
fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
// New art's paint is read with the document active, since activating a document can load its
|
||||
// selection's appearance into new art. Selecting the new path loads its temporary stroke into
|
||||
// new art, and putting the selection back does not undo that, so new art's paint from before
|
||||
// the path is put back.
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
keeping_paint(h, || {
|
||||
make_in(h, doc, into, |h| {
|
||||
let unpainted = {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
@@ -865,10 +1056,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
})
|
||||
}
|
||||
|
||||
// ---- PathItem geometry ----
|
||||
@@ -879,21 +1067,27 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("PathPoints", &handle))
|
||||
}
|
||||
|
||||
/// Whether the path of `item` is closed: it has a subpath and every subpath is. Setting `closed` on
|
||||
/// a path with no subpath gives it an empty closed one ([`path_set_closed`]).
|
||||
fn is_closed(h: &super::Host, item: Item) -> std::result::Result<bool, HostError> {
|
||||
read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))
|
||||
}
|
||||
|
||||
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let item = this_path(h, a)?;
|
||||
read_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.iter().all(|sp| sp.closed)))
|
||||
Ok(Data::Bool(is_closed(h, item)?))
|
||||
}
|
||||
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let closed = boolean(arg(a, 1), "closed")?;
|
||||
let item = this_path(h, a)?;
|
||||
edit_points(h, item, |subs| {
|
||||
if subs.is_empty() && closed {
|
||||
subs.push(SubPath::new(Vec::new(), closed));
|
||||
} else {
|
||||
subs.iter_mut().for_each(|sp| sp.closed = closed);
|
||||
}
|
||||
})?;
|
||||
// A path with no subpath gets an empty closed one to keep the value in; any other change keeps
|
||||
// the number of points, so the kept starts of the waiting changes stay valid.
|
||||
if closed && read_points(h, item, |subs| subs.is_empty())? {
|
||||
edit_points(h, item, |subs| subs.push(SubPath::new(Vec::new(), closed)))?;
|
||||
} else {
|
||||
edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -997,7 +1191,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::<std::result::Result<_, _>>()?;
|
||||
let f = with_doc(h, item.doc, |_, st| frame(st))?;
|
||||
let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?;
|
||||
let closed = is_closed(h, item)?;
|
||||
let c = h.dom.coords.get();
|
||||
let anchors: Vec<Anchor> =
|
||||
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
|
||||
@@ -1067,7 +1261,7 @@ fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option<Color>) -> s
|
||||
Some(c) => json!({"color": colors::param(&c)}),
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
edit_path(h, item, id, params)?;
|
||||
edit_paint(h, item, id, params)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1130,7 +1324,7 @@ fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer {
|
||||
let now = if fill { !look.fill.is_none() } else { !look.stroke.is_none() };
|
||||
if now != on {
|
||||
let params = if on { new_art_params(h, item, fill)? } else { json!({"none": true}) };
|
||||
edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
|
||||
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -1144,14 +1338,37 @@ fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(colors::of_paint(&this_look(h, a)?.1.fill))
|
||||
let (item, look) = this_look(h, a)?;
|
||||
super::resources::paint_color(h, item.doc, &look.fill)
|
||||
}
|
||||
|
||||
fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(colors::of_paint(&this_look(h, a)?.1.stroke))
|
||||
let (item, look) = this_look(h, a)?;
|
||||
super::resources::paint_color(h, item.doc, &look.stroke)
|
||||
}
|
||||
|
||||
/// Links the fill (`fill`) or the stroke to the Spot `spot` at `tint` (0 to 100), unless it is
|
||||
/// linked to it at that tint already. A `SpotColor` without a `spot`, as a color linked to a global
|
||||
/// process swatch reads, throws: it does not name the swatch it was read from.
|
||||
fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer {
|
||||
if matches!(spot, Data::Undefined) {
|
||||
return Err(HostError::Error("SpotColor.spot must be a Spot; a color read from a global process swatch cannot be assigned yet".into()));
|
||||
}
|
||||
let (item, look) = this_look(h, a)?;
|
||||
let now = if fill { &look.fill } else { &look.stroke };
|
||||
let at_tint = |t: &f32| *t == colors::unit(tint, 100.0);
|
||||
let name = super::resources::assigned_spot(h, spot, item.doc)?;
|
||||
let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && at_tint(t));
|
||||
if !same {
|
||||
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer {
|
||||
if let Some((spot, tint)) = colors::spot_parts(arg(a, 1))? {
|
||||
return set_spot_color(h, a, fill, spot, tint);
|
||||
}
|
||||
let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?;
|
||||
let (item, look) = this_look(h, a)?;
|
||||
let now = if fill { &look.fill } else { &look.stroke };
|
||||
@@ -1172,7 +1389,7 @@ fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// Runs `stroke.set` with `params` on the path, unless `same`.
|
||||
fn set_stroke_option(h: &super::Host, item: Item, same: bool, params: Value) -> Answer {
|
||||
if !same {
|
||||
edit_path(h, item, "stroke.set", params)?;
|
||||
edit_paint(h, item, "stroke.set", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -1370,9 +1587,10 @@ pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id))
|
||||
}
|
||||
|
||||
/// Sets the stroke weight of the path `item` to `weight` points.
|
||||
/// Sets the stroke weight of the path `item` to `weight` points, on the object whose paint the
|
||||
/// path shows ([`edit_paint`]).
|
||||
pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> {
|
||||
edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
edit_paint(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
}
|
||||
|
||||
// ---- PathPoints ----
|
||||
@@ -1650,11 +1868,12 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Some(p) => p,
|
||||
None => origin?,
|
||||
};
|
||||
let closed = last.is_none() && is_closed(h, item)?;
|
||||
// The kept starts are dropped, so that `counted` is their only copy and grows in place.
|
||||
*h.dom.point_starts.borrow_mut() = None;
|
||||
edit_points(h, item, |subs| match subs.last_mut() {
|
||||
Some(sp) => sp.anchors.push(Anchor::corner(p)),
|
||||
None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)),
|
||||
None => subs.push(SubPath::new(vec![Anchor::corner(p)], closed)),
|
||||
})?;
|
||||
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
|
||||
let grown = Rc::make_mut(&mut counted);
|
||||
@@ -1902,18 +2121,17 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
|
||||
.flatten()
|
||||
.collect();
|
||||
let partial = sel.partial(item.id).filter(|_| !held);
|
||||
let mut picked = Vec::new();
|
||||
let mut offset = 0;
|
||||
for (s, sp) in pd.subpaths.iter().enumerate() {
|
||||
for j in 0..sp.anchors.len() {
|
||||
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
|
||||
picked.push(offset + j);
|
||||
}
|
||||
}
|
||||
offset += sp.anchors.len();
|
||||
let firsts = starts(&pd.subpaths);
|
||||
match sel.partial(item.id).filter(|_| !held) {
|
||||
// Direct-selected anchors that no selected segment ends at, in subpath and anchor
|
||||
// order, which is the order of `pathPoints`.
|
||||
Some(anchors) => anchors
|
||||
.iter()
|
||||
.filter(|&&(s, j)| pd.subpaths.get(s).is_some_and(|sp| j < sp.anchors.len()) && !ends.contains(&(s, j)))
|
||||
.filter_map(|(s, j)| firsts.get(*s).map(|first| first + j))
|
||||
.collect(),
|
||||
None => (0..firsts.last().copied().unwrap_or(0)).collect(),
|
||||
}
|
||||
picked
|
||||
})?;
|
||||
h.charge_call(picked.len() as u64)?;
|
||||
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
|
||||
@@ -2124,6 +2342,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])),
|
||||
("add", point_method(l, points_add), returns("PathPoint", &[])),
|
||||
("removeAll", point_method(l, points_remove_all), returns("undefined", &[])),
|
||||
("toString", class_text("PathPoints"), returns("string", &[])),
|
||||
]),
|
||||
Some(super::point_function(l, points_at)),
|
||||
),
|
||||
@@ -2143,6 +2362,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
typed("PathPointSelection"),
|
||||
),
|
||||
("remove", point_method(l, pt_remove), returns("undefined", &[])),
|
||||
("toString", class_text("PathPoint"), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
|
||||
@@ -279,6 +279,8 @@ fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,7 +13,8 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/> describe.
|
||||
//!
|
||||
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
|
||||
//! transaction. The file is a `File` object, and the method reads and writes only where that
|
||||
//! transaction and writes command warnings to the run's console.
|
||||
//! The file is a `File` object, and the method reads and writes only where that
|
||||
//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the
|
||||
//! command's own reads and writes leave out the files of the open documents that `vc.run`'s
|
||||
//! commands may use.
|
||||
@@ -26,6 +27,8 @@
|
||||
//! `exportFile` adds the format's extension unless the name already ends
|
||||
//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes
|
||||
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
|
||||
//! An SVG export writes a compressed file when `compressed` is true, which adds `.svgz`, and
|
||||
//! when the name ends with `.svgz`.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
@@ -75,6 +78,8 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
pub(super) mod screens;
|
||||
|
||||
use super::{
|
||||
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named,
|
||||
num, on_doc, property, returns, text, this_doc, typed, whole,
|
||||
@@ -642,6 +647,16 @@ fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
"compressed" => {
|
||||
p.insert("_svgz".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"cssProperties" => {
|
||||
let locations = ["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"];
|
||||
let styling = match member(d, "SVGCSSPropertyLocation", &locations, &what)? {
|
||||
"ENTITIES" => "entities",
|
||||
"PRESENTATIONATTRIBUTES" => "presentation",
|
||||
"STYLEELEMENTS" => "css",
|
||||
_ => "style",
|
||||
};
|
||||
p.insert("styling".into(), json!(styling));
|
||||
}
|
||||
"preserveEditability" => {
|
||||
p.insert("preserveEditing".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
@@ -655,7 +670,6 @@ fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
|
||||
const SVG_KEPT: &[(&str, Default)] = &[
|
||||
("artboardRange", Default::Text("")),
|
||||
("cssProperties", Default::Member("SVGCSSPropertyLocation", "STYLEATTRIBUTES")),
|
||||
("documentEncoding", Default::Member("SVGDocumentEncoding", "ASCII")),
|
||||
("DTD", Default::Member("SVGDTDVersion", "SVG1_1")),
|
||||
("fontSubsetting", Default::Member("SVGFontSubsetting", "ALLGLYPHS")),
|
||||
@@ -673,6 +687,7 @@ fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("compressed", Data::Bool(false)),
|
||||
("coordinatePrecision", num(3.0)),
|
||||
("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")),
|
||||
("embedRasterImages", Data::Bool(false)),
|
||||
("includeVariablesAndDatasets", Data::Bool(false)),
|
||||
("preserveEditability", Data::Bool(false)),
|
||||
@@ -1020,7 +1035,9 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
// An SVG export to a name that ends with `.svgz` writes a compressed file, whatever `compressed` holds.
|
||||
let svgz_name = path.rsplit(['/', '\\']).next().is_some_and(|n| n.to_lowercase().ends_with(".svgz"));
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false) || (kind.format == "svg" && svgz_name);
|
||||
let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0));
|
||||
if (hs - vs).abs() > 1e-9 {
|
||||
@@ -1303,6 +1320,9 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
("saved", property(l, doc_saved, doc_set_saved), typed("boolean")),
|
||||
("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])),
|
||||
])
|
||||
.into_iter()
|
||||
.chain(screens::document_members(l))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
|
||||
@@ -1317,5 +1337,6 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
});
|
||||
HostClass { construct: Some(f), ..class(c.name, None, Vec::new(), None) }
|
||||
})
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
//! `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)`
|
||||
//! with `ExportForScreensItemToExport`, the option classes `ExportForScreensOptionsJPEG`,
|
||||
//! `ExportForScreensOptionsPNG24`, `ExportForScreensOptionsPNG8`,
|
||||
//! `ExportForScreensOptionsWebOptimizedSVG` and `ExportForScreensPDFOptions`, and the enumerations
|
||||
//! they use, as the scripting reference pages
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/Document.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsJPEG.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG24.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG8.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsWebOptimizedSVG.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensPDFOptions.html> and
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html> describe.
|
||||
//!
|
||||
//! The method runs `document.exportForScreens` with one format row into the folder, which goes
|
||||
//! through the script's file grants as a `File` opened for writing there would, and the command
|
||||
//! writes only where the script's `File` objects may ([`super::exactly`]).
|
||||
//! With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. SVG raster images are
|
||||
//! embedded; `RasterImageLocation.LINK` returns an error.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference pages do not state:
|
||||
//! - `exportFolder` is a `Folder`, or a `File` read as the folder at its path. The files go into
|
||||
//! that folder, without sub-folders, each named `<fileNamePrefix><name><suffix>.<extension>` as
|
||||
//! `document.exportForScreens` names them (`@2x` after a raster file of twice the size), with
|
||||
//! the characters a file name may not hold in the prefix written as `-`. The export keeps its
|
||||
//! settings in the document, as an export from the dialog does.
|
||||
//! - `itemToExport` exports, in this order, the artboards of `artboards` (`all`, the default, or a
|
||||
//! range of artboard numbers such as `1-3, 5`; `""` for none), the assets of `assets` (their ids)
|
||||
//! and, with `document` true, the bounds of the whole document's art (a PDF of every artboard).
|
||||
//! One that names nothing throws. Each of the three is its own export: when a later one throws,
|
||||
//! the files of the earlier ones stay written.
|
||||
//! - `ExportForScreensType.SE_JPEG100`, `SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a
|
||||
//! quality of 100, 80, 50 and 20. A scale factor is from 0.01 to 64 and a resolution from 0.72
|
||||
//! to 4608 ppi.
|
||||
//! - `RasterImageLocation.PRESERVE`, the default, embeds raster images as `EMBED` does, and
|
||||
//! `SVGFontType.SVGFONT`, the default, writes text as SVG text elements.
|
||||
//! - Options are read as `Document.exportFile` reads them: a listed option that is not mapped is
|
||||
//! accepted at its default and throws at any other value, and a property the pages do not list
|
||||
//! throws an error that names it, unless it is `undefined`. The options object's class must be
|
||||
//! the one of `exportFormat`, and an omitted options object takes the defaults a new one holds.
|
||||
//! `null` in place of the options, `itemToExport` or `fileNamePrefix` throws a TypeError.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
Answer, Default, Described, Host, Link, MAX_TEXT_BYTES, OptionClass, arg, boolean, builtin_preset_name, current, exactly, fresh, given, member,
|
||||
method, named, num, on_doc, plain, refused, returns, text, this_doc, typename, warned, whole, whole_in, written_as_range,
|
||||
};
|
||||
|
||||
/// The enumerations these members use, as `dom`'s are made.
|
||||
pub(in crate::script::dom) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("ExportForScreensType", &["SE_JPEG100", "SE_JPEG20", "SE_JPEG50", "SE_JPEG80", "SE_PDF", "SE_PNG24", "SE_PNG8", "SE_SVG"]),
|
||||
("ExportForScreensScaleType", &["SCALEBYFACTOR", "SCALEBYHEIGHT", "SCALEBYRESOLUTION", "SCALEBYWIDTH"]),
|
||||
("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]),
|
||||
("JPEGCompressionMethodType", &["BASELINEOPTIMIZED", "BASELINESTANDARD", "PROGRESSIVE"]),
|
||||
("RasterImageLocation", &["EMBED", "LINK", "PRESERVE"]),
|
||||
("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]),
|
||||
("SVGFontType", &["OUTLINEFONT", "SVGFONT"]),
|
||||
("SVGIdType", &["SVGIDMINIMAL", "SVGIDREGULAR", "SVGIDUNIQUE"]),
|
||||
];
|
||||
|
||||
/// The members of `enumeration` in [`ENUMS`].
|
||||
fn members(enumeration: &str) -> &'static [&'static str] {
|
||||
ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m)
|
||||
}
|
||||
|
||||
/// The member of `enumeration` that `d` names.
|
||||
fn pick<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> {
|
||||
member(d, enumeration, members(enumeration), what)
|
||||
}
|
||||
|
||||
/// The least and most pixels per point a raster file of an export has.
|
||||
const SCALE_FACTORS: (f64, f64) = (0.01, 64.0);
|
||||
|
||||
// ---- Raster options ----
|
||||
|
||||
/// The options JPEG, PNG24 and PNG8 share: anti-aliasing and the size, the size kept under `_scale`
|
||||
/// and `_scaleValue` until [`size`] reads them together.
|
||||
fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("{class}.{name}");
|
||||
match name {
|
||||
"antiAliasing" => {
|
||||
let mode = match pick(d, "AntiAliasingMethod", &what)? {
|
||||
"ARTOPTIMIZED" => "art",
|
||||
"TYPEOPTIMIZED" => "type",
|
||||
_ => "none",
|
||||
};
|
||||
p.insert("antiAlias".into(), json!(mode));
|
||||
}
|
||||
"scaleType" => {
|
||||
p.insert("_scale".into(), json!(pick(d, "ExportForScreensScaleType", &what)?));
|
||||
}
|
||||
"scaleTypeValue" => match d {
|
||||
Data::Number(n) if n.is_finite() && *n > 0.0 => {
|
||||
p.insert("_scaleValue".into(), json!(n));
|
||||
}
|
||||
Data::Number(_) => return Err(HostError::Range(format!("{what} must be a number above 0"))),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a number"))),
|
||||
},
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The format row's size from `_scale` and `_scaleValue`: a factor (`scale`), a width or a height
|
||||
/// in pixels (`width`, `height`), or a resolution (`ppi`).
|
||||
fn size(p: &mut Map<String, Value>) -> std::result::Result<(), HostError> {
|
||||
let how = p.remove("_scale").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "SCALEBYFACTOR".into());
|
||||
let value = p.remove("_scaleValue").and_then(|v| v.as_f64()).unwrap_or(1.0);
|
||||
let (lo, hi) = SCALE_FACTORS;
|
||||
let (key, per_point) = match how.as_str() {
|
||||
"SCALEBYWIDTH" => ("width", None),
|
||||
"SCALEBYHEIGHT" => ("height", None),
|
||||
"SCALEBYRESOLUTION" => ("ppi", Some(value / 72.0)),
|
||||
_ => ("scale", Some(value)),
|
||||
};
|
||||
if per_point.is_some_and(|f| !(lo..=hi).contains(&f)) {
|
||||
let range = if key == "ppi" { "from 0.72 to 4608" } else { "from 0.01 to 64" };
|
||||
return Err(HostError::Range(format!("scaleTypeValue must be {range} with ExportForScreensScaleType.{how}")));
|
||||
}
|
||||
p.insert(key.into(), json!(value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn jpeg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
const CLASS: &str = "ExportForScreensOptionsJPEG";
|
||||
let what = format!("{CLASS}.{name}");
|
||||
match name {
|
||||
"compressionMethod" => {
|
||||
let method = match pick(d, "JPEGCompressionMethodType", &what)? {
|
||||
"BASELINEOPTIMIZED" => "optimized",
|
||||
"PROGRESSIVE" => "progressive",
|
||||
_ => "baseline",
|
||||
};
|
||||
p.insert("method".into(), json!(method));
|
||||
}
|
||||
"embedICCProfile" => {
|
||||
p.insert("embedIcc".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"progressiveScan" => {
|
||||
p.insert("scans".into(), json!(whole_in(d, &what, 3, 5)?));
|
||||
}
|
||||
_ => return raster_map(CLASS, name, d, p),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn jpeg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")),
|
||||
("compressionMethod", text("JPEGCompressionMethodType.BASELINESTANDARD")),
|
||||
("embedICCProfile", Data::Bool(false)),
|
||||
("progressiveScan", num(3.0)),
|
||||
("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")),
|
||||
("scaleTypeValue", num(1.0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// PNG24's background, kept under `_transparent` and `_black` until [`background`] reads them
|
||||
/// together.
|
||||
fn png24_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
const CLASS: &str = "ExportForScreensOptionsPNG24";
|
||||
let what = format!("{CLASS}.{name}");
|
||||
match name {
|
||||
"transparency" => {
|
||||
p.insert("_transparent".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"backgroundBlack" => {
|
||||
p.insert("_black".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"interlaced" => {
|
||||
p.insert("interlaced".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
_ => return raster_map(CLASS, name, d, p),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The PNG24 row's `background`: transparent with `transparency`, otherwise black with
|
||||
/// `backgroundBlack` and white without it.
|
||||
fn background(p: &mut Map<String, Value>) {
|
||||
let transparent = p.remove("_transparent").and_then(|v| v.as_bool()).unwrap_or(true);
|
||||
let black = p.remove("_black").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let background = if transparent {
|
||||
"transparent"
|
||||
} else if black {
|
||||
"black"
|
||||
} else {
|
||||
"white"
|
||||
};
|
||||
p.insert("background".into(), json!(background));
|
||||
}
|
||||
|
||||
fn png24_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")),
|
||||
("backgroundBlack", Data::Bool(false)),
|
||||
("interlaced", Data::Bool(false)),
|
||||
("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")),
|
||||
("scaleTypeValue", num(1.0)),
|
||||
("transparency", Data::Bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
fn png8_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
const CLASS: &str = "ExportForScreensOptionsPNG8";
|
||||
let what = format!("{CLASS}.{name}");
|
||||
match name {
|
||||
"colorCount" => {
|
||||
p.insert("colors".into(), json!(whole_in(d, &what, 2, 256)?));
|
||||
}
|
||||
"interlaced" => {
|
||||
p.insert("interlaced".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"transparency" => {
|
||||
p.insert("transparency".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
// Matted on white, the default `matteColor`, or not matted.
|
||||
"matte" => {
|
||||
p.insert("matte".into(), json!(if boolean(d, &what)? { "white" } else { "none" }));
|
||||
}
|
||||
_ => return raster_map(CLASS, name, d, p),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
const PNG8_KEPT: &[(&str, Default)] = &[("matteColor", Default::Unset)];
|
||||
|
||||
fn png8_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")),
|
||||
("colorCount", num(128.0)),
|
||||
("interlaced", Data::Bool(false)),
|
||||
("matte", Data::Bool(true)),
|
||||
("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")),
|
||||
("scaleTypeValue", num(1.0)),
|
||||
("transparency", Data::Bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
// ---- Vector options ----
|
||||
|
||||
fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportForScreensOptionsWebOptimizedSVG.{name}");
|
||||
let (key, value) = match name {
|
||||
"coordinatePrecision" => ("decimals", json!(whole_in(d, &what, 1, 7)?)),
|
||||
"cssProperties" => {
|
||||
let styling = match pick(d, "SVGCSSPropertyLocation", &what)? {
|
||||
"ENTITIES" => "entities",
|
||||
"PRESENTATIONATTRIBUTES" => "presentation",
|
||||
"STYLEELEMENTS" => "css",
|
||||
_ => "style",
|
||||
};
|
||||
("styling", json!(styling))
|
||||
}
|
||||
"fontType" => ("outlineText", json!(pick(d, "SVGFontType", &what)? == "OUTLINEFONT")),
|
||||
"rasterImageLocation" => {
|
||||
if pick(d, "RasterImageLocation", &what)? == "LINK" {
|
||||
return Err(HostError::Error(format!("{what}: RasterImageLocation.LINK is not available yet")));
|
||||
}
|
||||
("images", json!("embed"))
|
||||
}
|
||||
"svgId" => {
|
||||
let ids = match pick(d, "SVGIdType", &what)? {
|
||||
"SVGIDMINIMAL" => "minimal",
|
||||
"SVGIDUNIQUE" => "unique",
|
||||
_ => "layerNames",
|
||||
};
|
||||
("objectIds", json!(ids))
|
||||
}
|
||||
"svgMinify" => ("minify", json!(boolean(d, &what)?)),
|
||||
"svgResponsive" => ("responsive", json!(boolean(d, &what)?)),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
p.insert(key.into(), value);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("coordinatePrecision", num(3.0)),
|
||||
("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")),
|
||||
("fontType", text("SVGFontType.SVGFONT")),
|
||||
("rasterImageLocation", text("RasterImageLocation.PRESERVE")),
|
||||
("svgId", text("SVGIdType.SVGIDREGULAR")),
|
||||
("svgMinify", Data::Bool(false)),
|
||||
("svgResponsive", Data::Bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
/// The PDF preset's name, at most 255 bytes, as the reference page limits it.
|
||||
fn pdf_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
if name != "pdfPreset" {
|
||||
return Ok(false);
|
||||
}
|
||||
let what = "ExportForScreensPDFOptions.pdfPreset";
|
||||
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
|
||||
if s.len() > 255 {
|
||||
return Err(HostError::Range(format!("{what} is longer than 255 bytes")));
|
||||
}
|
||||
if !s.is_empty() {
|
||||
p.insert("preset".into(), json!(s));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn pdf_starts() -> Vec<(&'static str, Data)> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
// ---- What to export ----
|
||||
|
||||
/// `ExportForScreensItemToExport`'s properties, kept under `_artboards`, `_assets` and `_document`
|
||||
/// until [`exports`] reads them.
|
||||
fn item_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportForScreensItemToExport.{name}");
|
||||
match name {
|
||||
"artboards" => {
|
||||
let r = match d {
|
||||
Data::String(s) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range(format!("{what} is too long"))),
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Number(n) => {
|
||||
whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?;
|
||||
vectorcraft_js::number_to_string(*n)
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a string"))),
|
||||
};
|
||||
p.insert("_artboards".into(), json!(r));
|
||||
}
|
||||
"assets" => {
|
||||
let Data::Array(ids) = d else { return Err(HostError::Type(format!("{what} must be an array of asset ids"))) };
|
||||
let ids = ids
|
||||
.iter()
|
||||
.map(|id| match id {
|
||||
Data::Number(n) => whole(*n).ok_or_else(|| HostError::Range(format!("{what} holds {n}, not an asset id"))),
|
||||
_ => Err(HostError::Type(format!("{what} must be an array of asset ids"))),
|
||||
})
|
||||
.collect::<std::result::Result<Vec<u64>, HostError>>()?;
|
||||
p.insert("_assets".into(), json!(ids));
|
||||
}
|
||||
"document" => {
|
||||
p.insert("_document".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn item_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![("artboards", text("all")), ("assets", Data::Array(Vec::new())), ("document", Data::Bool(false))]
|
||||
}
|
||||
|
||||
const JPEG: OptionClass = OptionClass { name: "ExportForScreensOptionsJPEG", map: jpeg_map, kept: &[], starts: jpeg_starts };
|
||||
const PNG24: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG24", map: png24_map, kept: &[], starts: png24_starts };
|
||||
const PNG8: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG8", map: png8_map, kept: PNG8_KEPT, starts: png8_starts };
|
||||
const SVG: OptionClass = OptionClass { name: "ExportForScreensOptionsWebOptimizedSVG", map: svg_map, kept: &[], starts: svg_starts };
|
||||
const PDF: OptionClass = OptionClass { name: "ExportForScreensPDFOptions", map: pdf_map, kept: &[], starts: pdf_starts };
|
||||
const ITEM: OptionClass = OptionClass { name: "ExportForScreensItemToExport", map: item_map, kept: &[], starts: item_starts };
|
||||
|
||||
/// The params of `class` for `d` (a new object's when `d` is omitted), over a new object's, so a
|
||||
/// property a record leaves out keeps its default.
|
||||
fn params(class: &OptionClass, d: Option<&Data>) -> std::result::Result<Map<String, Value>, HostError> {
|
||||
let mut p = super::options_params(class, &fresh(class))?;
|
||||
if let Some(d) = d {
|
||||
p.extend(super::options_params(class, d)?);
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The format row `exportFormat` (`d`) asks for, with its option class.
|
||||
fn format(d: &Data) -> std::result::Result<(Map<String, Value>, &'static OptionClass), HostError> {
|
||||
let (format, quality, class) = match pick(d, "ExportForScreensType", "exportFormat")? {
|
||||
"SE_JPEG100" => ("jpg", Some(100), &JPEG),
|
||||
"SE_JPEG80" => ("jpg", Some(80), &JPEG),
|
||||
"SE_JPEG50" => ("jpg", Some(50), &JPEG),
|
||||
"SE_JPEG20" => ("jpg", Some(20), &JPEG),
|
||||
"SE_PNG24" => ("png", None, &PNG24),
|
||||
"SE_PNG8" => ("png8", None, &PNG8),
|
||||
"SE_SVG" => ("svg", None, &SVG),
|
||||
_ => ("pdf", None, &PDF),
|
||||
};
|
||||
let mut row = Map::new();
|
||||
row.insert("format".into(), json!(format));
|
||||
if let Some(q) = quality {
|
||||
row.insert("quality".into(), json!(q));
|
||||
}
|
||||
Ok((row, class))
|
||||
}
|
||||
|
||||
/// The exports `itemToExport` asks for, in order: the artboards, the assets and the whole
|
||||
/// document, each as the params that pick it.
|
||||
fn exports(d: Option<&Data>) -> std::result::Result<Vec<Map<String, Value>>, HostError> {
|
||||
if let Some(d) = d
|
||||
&& typename(d) != Some(ITEM.name)
|
||||
{
|
||||
return Err(HostError::Type("itemToExport must be an ExportForScreensItemToExport object".into()));
|
||||
}
|
||||
let mut p = params(&ITEM, d)?;
|
||||
let mut out = Vec::new();
|
||||
if let Some(Value::String(r)) = p.remove("_artboards") {
|
||||
let all = r.trim().eq_ignore_ascii_case("all");
|
||||
if !r.trim().is_empty() {
|
||||
if !all && !written_as_range(&r) {
|
||||
return Err(HostError::Range(format!("ExportForScreensItemToExport.artboards `{r}` is not a range of artboard numbers")));
|
||||
}
|
||||
out.push(Map::from_iter([("range".to_string(), json!(if all { "all" } else { r.as_str() }))]));
|
||||
}
|
||||
}
|
||||
if let Some(ids) = p.remove("_assets").filter(|v| v.as_array().is_some_and(|a| !a.is_empty())) {
|
||||
out.push(Map::from_iter([("assets".to_string(), ids)]));
|
||||
}
|
||||
if p.remove("_document").and_then(|v| v.as_bool()) == Some(true) {
|
||||
out.push(Map::from_iter([("fullDocument".to_string(), json!(true))]));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(HostError::Error(
|
||||
"exportForScreens has nothing to export: itemToExport names no artboards, no assets and not the document".into(),
|
||||
));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The path of the `Folder` (or `File`) argument `d`, or a `TypeError`.
|
||||
fn folder_path(d: &Data) -> std::result::Result<&str, HostError> {
|
||||
let wrong = || HostError::Type("exportForScreens needs a Folder".into());
|
||||
if let Some(p) = vectorcraft_js::file_ref_path(d) {
|
||||
return Ok(p);
|
||||
}
|
||||
let Data::Object(items) = d else { return Err(wrong()) };
|
||||
match items.as_slice() {
|
||||
[(k, Data::String(path))] if k == vectorcraft_js::FOLDER_REF_KEY => Ok(path),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?,
|
||||
/// fileNamePrefix?)`: `document.exportForScreens` of one format row into the folder, once for each
|
||||
/// of the artboards, the assets and the whole document that `itemToExport` names.
|
||||
fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let folder = folder_path(arg(a, 1))?;
|
||||
let (mut row, class) = format(arg(a, 2))?;
|
||||
let options = given(arg(a, 3));
|
||||
if matches!(options, Some(Data::Null)) {
|
||||
return Err(HostError::Type("the options must be an object".into()));
|
||||
}
|
||||
let mut q = params(class, options)?;
|
||||
if class.name == PNG24.name {
|
||||
background(&mut q);
|
||||
}
|
||||
if class.name == PDF.name {
|
||||
builtin_preset_name(h, &mut q);
|
||||
} else if class.name != SVG.name {
|
||||
size(&mut q)?;
|
||||
}
|
||||
row.extend(q);
|
||||
let exports = exports(given(arg(a, 4)))?;
|
||||
let prefix = match given(arg(a, 5)) {
|
||||
None => None,
|
||||
Some(Data::String(s)) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range("fileNamePrefix is too long".into())),
|
||||
Some(Data::String(s)) => Some(s.clone()),
|
||||
Some(_) => return Err(HostError::Type("fileNamePrefix must be a string".into())),
|
||||
};
|
||||
let real = h.disk.borrow().folder_target(folder).map_err(|m| refused(m, folder))?;
|
||||
let mut base = Map::new();
|
||||
base.insert("folder".into(), json!(plain(real)?));
|
||||
base.insert("folders".into(), json!("none"));
|
||||
base.insert("formats".into(), json!([Value::Object(row)]));
|
||||
if let Some(prefix) = prefix {
|
||||
base.insert("prefix".into(), json!(prefix));
|
||||
}
|
||||
// The artboards, the assets and the document are exported one after another into the folder:
|
||||
// a later export numbers a file whose name an earlier one took instead of writing over it.
|
||||
crate::cmd::fileio::sharing_screen_names(|| {
|
||||
for items in exports {
|
||||
let mut p = base.clone();
|
||||
p.extend(items);
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
}
|
||||
|
||||
/// The members these add to `Document`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![(
|
||||
"exportForScreens",
|
||||
method(l, doc_export_for_screens),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("exportFolder", "Folder"),
|
||||
("targetType", "ExportForScreensType"),
|
||||
("options", "*"),
|
||||
("itemToExport", "ExportForScreensItemToExport"),
|
||||
("fileNamePrefix", "string"),
|
||||
],
|
||||
),
|
||||
)])
|
||||
}
|
||||
|
||||
/// The classes: each `new Name()` gives a record with its `typename` and the defaults its reference
|
||||
/// page gives.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
[&ITEM, &JPEG, &PNG24, &PNG8, &SVG, &PDF]
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
Ok(fresh(c))
|
||||
});
|
||||
HostClass { name: c.name.into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: Some(f) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -203,15 +203,22 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
|
||||
}
|
||||
h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| {
|
||||
let mut ids = HashSet::new();
|
||||
group.walk(&mut |n| {
|
||||
if n.id != group.id {
|
||||
ids.insert(n.id);
|
||||
}
|
||||
});
|
||||
// Only children are recorded: an opacity mask is refused whatever its art, so the art of
|
||||
// one held now must not become an object the trace made if the mask is later undone.
|
||||
let mut todo: Vec<&Node> = group.children().into_iter().flatten().map(|c| &**c).collect();
|
||||
while let Some(n) = todo.pop() {
|
||||
ids.insert(n.id);
|
||||
todo.extend(n.children().into_iter().flatten().map(|c| &**c));
|
||||
}
|
||||
ids
|
||||
});
|
||||
}
|
||||
|
||||
/// The objects `n` holds: its children and the art of its opacity mask.
|
||||
fn members(n: &Node) -> impl Iterator<Item = &Node> {
|
||||
n.children().into_iter().flatten().map(|c| &**c).chain(n.extras().mask.as_deref().map(|m| &*m.art))
|
||||
}
|
||||
|
||||
/// Before each command a script runs: notes the active document ([`note_document`]).
|
||||
pub(super) fn before_command(h: &Host) {
|
||||
let s = h.session.borrow();
|
||||
@@ -357,6 +364,7 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<
|
||||
}
|
||||
|
||||
/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make,
|
||||
/// or has an opacity mask on it or on one of its objects other than the source image, whatever its art,
|
||||
/// and "Cannot edit page item" when it holds a locked object other than its source image, which
|
||||
/// the replacement would discard. The objects looked at are charged to the run either way.
|
||||
fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
@@ -380,14 +388,22 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
|
||||
let mut visited = 0u64;
|
||||
let mut locked = None;
|
||||
let mut todo: Vec<&Arc<Node>> = group.children().map(|c| c.iter().collect()).unwrap_or_default();
|
||||
// An opacity mask on the tracing or on an object other than the source image is added
|
||||
// artwork whatever the ids of its art: a mask made from traced objects keeps their ids.
|
||||
if group.extras().mask.is_some() {
|
||||
return Ok((visited, Err(HostError::Error(refusal.into()))));
|
||||
}
|
||||
// The tracing's own opacity mask goes with it too; the source image is kept whole.
|
||||
let mut todo: Vec<&Node> = members(group).collect();
|
||||
while let Some(n) = todo.pop() {
|
||||
visited += 1;
|
||||
let added = match (&made, ids) {
|
||||
(Some(m), _) => !m.contains(n.id),
|
||||
(None, Some(ids)) => !ids.contains(&n.id),
|
||||
(None, None) => false,
|
||||
} || newer.is_some_and(|m| n.id.0 >= m);
|
||||
let added = (Some(n.id) != source && n.extras().mask.is_some())
|
||||
|| match (&made, ids) {
|
||||
(Some(m), _) => !m.contains(n.id),
|
||||
(None, Some(ids)) => !ids.contains(&n.id),
|
||||
(None, None) => false,
|
||||
}
|
||||
|| newer.is_some_and(|m| n.id.0 >= m);
|
||||
// Added artwork is reported before a locked object, whichever comes first.
|
||||
if added {
|
||||
return Ok((visited, Err(HostError::Error(refusal.into()))));
|
||||
@@ -395,7 +411,9 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
if n.locked && Some(n.id) != source && locked.is_none() {
|
||||
locked = Some(n.id);
|
||||
}
|
||||
todo.extend(n.children().into_iter().flatten());
|
||||
if Some(n.id) != source {
|
||||
todo.extend(members(n));
|
||||
}
|
||||
}
|
||||
Ok((visited, locked.map_or(Ok(()), |id| Err(HostError::Error(format!("Cannot edit page item {}", id.0))))))
|
||||
})?;
|
||||
@@ -880,7 +898,11 @@ fn options_load(h: &Host, a: &[Data]) -> Answer {
|
||||
let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone()));
|
||||
let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?;
|
||||
let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms);
|
||||
if !(same && preset.eq_ignore_ascii_case(name)) {
|
||||
// A built-in preset answers to its name with or without brackets (`[Default]`).
|
||||
let key = |n: &str| {
|
||||
if vectorcraft_trace::preset(n).is_some() { n.trim().trim_start_matches('[').trim_end_matches(']').to_string() } else { n.to_string() }
|
||||
};
|
||||
if !(same && key(&preset).eq_ignore_ascii_case(&key(name))) {
|
||||
let mut p = Map::new();
|
||||
p.insert("preset".into(), json!(name));
|
||||
retrace(h, item, p)?;
|
||||
|
||||
@@ -127,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
|
||||
pub(crate) const READ_ONLY: &str = "Script file is read-only";
|
||||
pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing";
|
||||
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
|
||||
pub(crate) const NOT_FOLDER: &str = "Script folder is a file";
|
||||
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
|
||||
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
|
||||
#[cfg(not(unix))]
|
||||
@@ -720,6 +721,24 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The real path of the folder `path` that an export writes its files into, as a `File`
|
||||
/// opened for writing there would reach it ([`Disk::target`]), or why it may not: a file is
|
||||
/// not a folder. A root (`/`, `E:\`) has no name of its own: its real path must be inside a
|
||||
/// folder the script may write to and the automation write roots in force.
|
||||
pub(crate) fn folder_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
|
||||
let p = self.checked(path)?;
|
||||
if p.file_name().is_none() {
|
||||
let real = std::fs::canonicalize(p).map_err(|_| ACCESS_DENIED)?;
|
||||
let writable = crate::file_access::check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_ok();
|
||||
return if self.writes.allows(&real) && writable { Ok(real) } else { Err(ACCESS_DENIED) };
|
||||
}
|
||||
let real = self.target(path, true)?;
|
||||
match std::fs::metadata(&real) {
|
||||
Ok(m) if !m.is_dir() => Err(NOT_FOLDER),
|
||||
_ => Ok(real),
|
||||
}
|
||||
}
|
||||
|
||||
/// The real path of the file `path` that opening it as a document reads, as a `File` reads it
|
||||
/// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or
|
||||
/// the script may not read it.
|
||||
|
||||
@@ -1406,7 +1406,7 @@ fn note_ids(s: &mut Session) {
|
||||
/// it, for a result that cannot cross to the script.
|
||||
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
s.script_style_trail = StyleTrail::start(s, dom::holds_resources(host));
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A
|
||||
// query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard.
|
||||
@@ -1439,6 +1439,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
match r {
|
||||
Ok(v) => {
|
||||
note_ids(s);
|
||||
// A command that is not a batch, such as `edit.undo`, notes the resources it removed too.
|
||||
note_resources(s);
|
||||
let (mut objects, mut bytes) = (0, 0);
|
||||
for st in &s.docs {
|
||||
match before.iter().find(|(uid, ..)| *uid == st.uid) {
|
||||
@@ -1458,7 +1460,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
Ok((v, objects, bytes, save))
|
||||
}
|
||||
Err(e) => {
|
||||
s.script_style_trail = StyleTrail::default();
|
||||
s.script_style_trail = StyleTrail { resources_scanned: s.script_style_trail.resources_scanned, ..Default::default() };
|
||||
if let Some(save) = save
|
||||
&& !save.restore(s)
|
||||
{
|
||||
@@ -1483,7 +1485,9 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
command(host, &id, ¶ms)
|
||||
let r = command(host, &id, ¶ms);
|
||||
dom::forget_removed(host)?;
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs command `id` for the script as `vc.run` does, its call already charged: it joins the run's
|
||||
@@ -1515,6 +1519,12 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
let mut s = session.borrow_mut();
|
||||
(s.copies, step(&mut s, host, id, params))
|
||||
};
|
||||
// The resource names a failed command's steps compared are still charged, before its error is
|
||||
// given.
|
||||
if r.is_err() {
|
||||
dom::keep_scanned(host);
|
||||
dom::charge_scanned(host)?;
|
||||
}
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
@@ -1565,8 +1575,11 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
dom::after_kept_command(host);
|
||||
seen?;
|
||||
} else {
|
||||
dom::keep_scanned(host);
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
}
|
||||
// The resource names the command's steps compared are charged whoever ran it.
|
||||
dom::charge_scanned(host)?;
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
@@ -1577,19 +1590,28 @@ pub(crate) type StyleLists =
|
||||
/// What the steps of a command a script runs did to the documents' style lists
|
||||
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
|
||||
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
|
||||
/// documents a step reverted.
|
||||
#[derive(Default)]
|
||||
/// documents a step reverted. It also holds each open document as the last step left it, and the
|
||||
/// swatches, symbols, graphic styles and brushes a step removed or renamed.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct StyleTrail {
|
||||
lists: Vec<StyleLists>,
|
||||
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
|
||||
pub(crate) reverted: Vec<u64>,
|
||||
/// Whether the run holds resource objects, so that the steps note what they remove.
|
||||
watch_resources: bool,
|
||||
docs: Vec<(u64, Arc<crate::Document>)>,
|
||||
pub(in crate::script) resources_gone: std::collections::HashSet<(u64, dom::ResourceKind, String)>,
|
||||
/// The resource names the steps compared, charged to the run with the check that follows.
|
||||
pub(crate) resources_scanned: u64,
|
||||
}
|
||||
|
||||
impl StyleTrail {
|
||||
/// A trail that starts from the documents' style lists now.
|
||||
fn start(s: &Session) -> Self {
|
||||
/// A trail that starts from the documents' style lists now, and from the documents themselves
|
||||
/// when `watch_resources`.
|
||||
fn start(s: &Session, watch_resources: bool) -> Self {
|
||||
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
|
||||
StyleTrail { lists, ..Default::default() }
|
||||
let docs = if watch_resources { s.docs.iter().map(|st| (st.uid, st.doc.clone())).collect() } else { Vec::new() };
|
||||
StyleTrail { lists, docs, watch_resources, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1623,6 +1645,32 @@ pub(crate) fn note_style_lists(s: &mut Session) {
|
||||
}
|
||||
*last = (st.uid, st.reverts, c.clone(), p.clone());
|
||||
}
|
||||
note_resources(s);
|
||||
}
|
||||
|
||||
/// After a step of a batch a script runs, and after each command it runs: notes the swatches,
|
||||
/// symbols, styles and brushes the documents no longer have, when the run holds objects for them
|
||||
/// ([`dom::after_kept_command`]). A document the trail already compared is not compared again.
|
||||
fn note_resources(s: &mut Session) {
|
||||
let trail = &mut s.script_style_trail;
|
||||
if !trail.watch_resources {
|
||||
return;
|
||||
}
|
||||
trail.docs.retain(|(uid, _)| s.docs.iter().any(|d| d.uid == *uid));
|
||||
for st in &s.docs {
|
||||
let Some(last) = trail.docs.iter_mut().find(|(uid, _)| *uid == st.uid) else {
|
||||
trail.docs.push((st.uid, st.doc.clone()));
|
||||
continue;
|
||||
};
|
||||
if !Arc::ptr_eq(&last.1, &st.doc) {
|
||||
let (gone, scanned) = dom::resources_gone(&last.1, &st.doc);
|
||||
trail.resources_scanned = trail.resources_scanned.saturating_add(scanned);
|
||||
for (kind, name) in gone {
|
||||
trail.resources_gone.insert((st.uid, kind, name));
|
||||
}
|
||||
last.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
|
||||
@@ -2644,11 +2692,10 @@ impl Session {
|
||||
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// One more allowance may still leave the growth past it: the person is asked again
|
||||
// while they may be, and past that the run ends unkept.
|
||||
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
|
||||
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
// What the script added must fit the allowance the last answer gave: past it, the
|
||||
// person is asked again, as a running script is at its next charge.
|
||||
if let Err(e) = job.host.charge_growth(0, 0) {
|
||||
return Some(self.script_failed(job, &end_flush_error(e)));
|
||||
}
|
||||
if job.host.waiting.get() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
@@ -2682,14 +2729,24 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
// The point changes written as the script ended went past the growth allowance.
|
||||
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
// What the script added must fit the allowance the last answer gave, which one
|
||||
// answer can leave short of what the script had already added.
|
||||
if !job.host.waiting.get()
|
||||
&& let Err(e) = job.host.charge_growth(0, 0)
|
||||
{
|
||||
return Some(self.script_failed(job, &end_flush_error(e)));
|
||||
}
|
||||
// The point changes written as the script ended, or what it added before, went past
|
||||
// the growth allowance.
|
||||
if job.host.waiting.get() {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
Some(self.script_ended(job))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3188,6 +3245,11 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the swatch, symbol, style and brush objects a run may hold, in place of 100,000.
|
||||
pub(crate) static TEST_MAX_SLOTS: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: how many times the object model worked out where the points of each subpath of a
|
||||
/// path start.
|
||||
pub(crate) static LAYOUTS_BUILT: Cell<u64> = const { Cell::new(0) };
|
||||
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
|
||||
|
||||
@@ -236,6 +236,17 @@ impl Palettes {
|
||||
None
|
||||
}
|
||||
|
||||
/// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the
|
||||
/// line is empty or starts with an event that can still run.
|
||||
fn drop_stale(&mut self) {
|
||||
while let Some(q) = self.waiting.front() {
|
||||
if self.resolved(q.clone()).is_some() {
|
||||
break;
|
||||
}
|
||||
self.waiting.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other
|
||||
/// engines' palettes keep their places in line. Events whose file access scopes do not cover
|
||||
/// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest
|
||||
@@ -252,7 +263,13 @@ impl Palettes {
|
||||
|
||||
/// The taken event `q` given to its control in its palette, and that palette, or `None` when it
|
||||
/// is dropped ([`Palettes::next`]).
|
||||
fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
let (p, q) = self.resolved(q)?;
|
||||
Some((p.clone(), q))
|
||||
}
|
||||
|
||||
/// [`Palettes::checked`] without the copy of the palette.
|
||||
fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> {
|
||||
let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?;
|
||||
if let Some(c) = control_of(&mut q.event) {
|
||||
*c = p.dialog.index_of(q.element?)?;
|
||||
@@ -271,7 +288,7 @@ impl Palettes {
|
||||
} else {
|
||||
q.event = scriptui::check_event(&p.dialog, q.event).ok()?;
|
||||
}
|
||||
Some((p.clone(), q))
|
||||
Some((p, q))
|
||||
}
|
||||
|
||||
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
|
||||
@@ -414,6 +431,12 @@ impl Session {
|
||||
self.script_palettes.waiting.len()
|
||||
}
|
||||
|
||||
/// The number of the last palette event put in line, which an event added, or merged into a
|
||||
/// waiting one, changes.
|
||||
pub fn script_palette_last_ticket(&self) -> u64 {
|
||||
self.script_palettes.last_ticket
|
||||
}
|
||||
|
||||
/// The changes that wait for a run, as (palette id, the id of the control they change).
|
||||
pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> {
|
||||
self.script_palettes
|
||||
@@ -456,7 +479,12 @@ impl Session {
|
||||
/// run is going or no event waits; otherwise the run's name, or the error that ended it before
|
||||
/// it began. An open edit that cannot be settled gives its error, and the events keep waiting.
|
||||
pub fn script_palette_start(&mut self) -> Option<Result<String>> {
|
||||
if self.script_running() || self.script_palettes.waiting.is_empty() {
|
||||
if self.script_running() {
|
||||
return None;
|
||||
}
|
||||
// Events that can no longer run do not settle the open edit.
|
||||
self.script_palettes.drop_stale();
|
||||
if self.script_palettes.waiting.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// An event waits while a drag or an undo group is open, which a run cannot start in.
|
||||
@@ -507,6 +535,9 @@ impl Session {
|
||||
let want = self.script_palettes.last_ticket;
|
||||
let mut mine = None;
|
||||
loop {
|
||||
if !self.script_running() {
|
||||
self.script_palettes.drop_stale();
|
||||
}
|
||||
if !self.script_running()
|
||||
&& !self.script_palettes.waiting.is_empty()
|
||||
&& let Err(e) = self.settle_for_script()
|
||||
|
||||
@@ -14,3 +14,6 @@ mod documents;
|
||||
mod edit;
|
||||
mod execute;
|
||||
mod undo;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use edit::previews_run;
|
||||
@@ -165,6 +165,8 @@ impl Session {
|
||||
liquify_stroke: None,
|
||||
plane_widget_press: false,
|
||||
pointer_held: false,
|
||||
holds_previews: false,
|
||||
sampled_preview: None,
|
||||
press_options: None,
|
||||
press_options_stored: false,
|
||||
press_type_selection: None,
|
||||
|
||||
@@ -4,6 +4,18 @@ use super::{
|
||||
};
|
||||
use crate::doc_state::{kept_from, objects_only};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`Session::preview`] ran on this thread.
|
||||
static PREVIEWS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`Session::preview`] has run on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn previews_run() -> usize {
|
||||
PREVIEWS.get()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Takes committed swatch renames as (document uid, old name, new name) in execution order and leaves the record empty.
|
||||
/// The uid identifies the originating document through [`crate::DocState::uid`].
|
||||
@@ -583,6 +595,8 @@ impl Session {
|
||||
|
||||
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
|
||||
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
PREVIEWS.set(PREVIEWS.get() + 1);
|
||||
self.put_back_interaction();
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -189,6 +189,7 @@ mod script_dom_defaults;
|
||||
mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_resources;
|
||||
mod script_dom_tracing;
|
||||
mod script_dom_transform;
|
||||
mod script_engines;
|
||||
@@ -201,6 +202,7 @@ mod script_print;
|
||||
mod script_raster_capture;
|
||||
mod script_run;
|
||||
mod script_save_open;
|
||||
mod script_screens;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
mod script_tags;
|
||||
|
||||
@@ -320,6 +320,192 @@ fn pencil_continues_selected_open_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 100.0));
|
||||
}
|
||||
|
||||
/// The document without its creation time, the selection and the new-art paints.
|
||||
type Drawn = (vectorcraft_doc::Document, vectorcraft_doc::Selection, vectorcraft_tools::PaintDefaults);
|
||||
|
||||
fn drawn(s: &Session) -> Drawn {
|
||||
let st = s.doc().unwrap();
|
||||
let mut doc = (*st.doc).clone();
|
||||
// `file.new` stamps the time in seconds, which differs between two sessions made a second apart.
|
||||
doc.metadata.created = None;
|
||||
(doc, st.selection.clone(), s.paint.clone())
|
||||
}
|
||||
|
||||
/// Draws `pts` with the Pencil in a session that `setup` prepared, handing the drag's samples and the release to the
|
||||
/// session in groups of 4, the release in the last group: through [`Session::pointer_samples`] with `by_frame`, else
|
||||
/// one at a time through [`Session::pointer`]. What [`drawn`] gives after each group, the previews each group ran,
|
||||
/// and the previews a group runs when its drags preview once: one for its drags and one for its release.
|
||||
fn pencil_in_frames(setup: &dyn Fn(&mut Session), pts: &[(f64, f64)], by_frame: bool) -> (Vec<Drawn>, Vec<usize>, Vec<usize>) {
|
||||
let mut s = session();
|
||||
setup(&mut s);
|
||||
let v = view();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
|
||||
let mut samples: Vec<PointerEvent> = pts[1..].iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)).collect();
|
||||
let l = pts[pts.len() - 1];
|
||||
samples.push(PointerEvent::new(PointerKind::Up, l.0, l.1));
|
||||
let (mut states, mut previews, mut once) = (vec![], vec![], vec![]);
|
||||
for group in samples.rchunks(4).rev() {
|
||||
let has = |kind| usize::from(group.iter().any(|ev| ev.kind == kind));
|
||||
once.push(has(PointerKind::Drag) + has(PointerKind::Up));
|
||||
let before = crate::session::previews_run();
|
||||
if by_frame {
|
||||
let (fed, r) = s.pointer_samples(group, v);
|
||||
r.unwrap();
|
||||
assert_eq!(fed, group.len(), "every sample fed");
|
||||
} else {
|
||||
for ev in group {
|
||||
s.pointer(ev, v).unwrap();
|
||||
}
|
||||
}
|
||||
previews.push(crate::session::previews_run() - before);
|
||||
states.push(drawn(&s));
|
||||
}
|
||||
(states, previews, once)
|
||||
}
|
||||
|
||||
/// The drag samples of a frame of up to 4 Pencil samples run one preview, the last sample's, before the release when
|
||||
/// the frame ends with it, and leave the document, the selection and the new-art paints as handing the samples over one
|
||||
/// by one does, after every frame: for a new stroke, for strokes that continue a selected path at its end and at its
|
||||
/// start, and with New Art Has Basic Appearance off and an empty starting selection. Every sample is previewed when
|
||||
/// inheriting a selected gradient, with two selected paths in a group, during a Global Edit, or with Objects on Path selected.
|
||||
#[test]
|
||||
fn pencil_samples_of_one_frame_run_one_preview() {
|
||||
let none = |_: &mut Session| {};
|
||||
let selected_line = |s: &mut Session| {
|
||||
line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
};
|
||||
let not_basic = |s: &mut Session| {
|
||||
rect(s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
};
|
||||
let selected_gradient = |s: &mut Session| {
|
||||
rect(s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.select_tool("pencil", view()).unwrap();
|
||||
s.set_tool_option("fill", &json!(true));
|
||||
s.set_tool_option("keepSelected", &json!(true));
|
||||
};
|
||||
let grouped_paths = |s: &mut Session| {
|
||||
let a = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
let b = line(s, 400.0, 200.0, 420.0, 200.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
};
|
||||
let new_stroke = wave(100.0, 180.0, 300.0);
|
||||
let wavy =
|
||||
|x0: f64, step: f64| -> Vec<(f64, f64)> { (0..=40).map(|i| (x0 + step * f64::from(i), 101.0 + 10.0 * (f64::from(i) / 6.0).sin())).collect() };
|
||||
let (past_end, before_start) = (wavy(202.0, 2.0), wavy(99.0, -2.0));
|
||||
// A Global Edit preview also changes the other members, which the tool reads for its next sample.
|
||||
let global_edit = |s: &mut Session| {
|
||||
let a = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
line(s, 100.0, 140.0, 200.0, 140.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.execute("select.globalEdit", &json!({})).unwrap()["active"], true);
|
||||
};
|
||||
// Continuing the spine of an Objects on Path group moves the attached art, so every sample is previewed.
|
||||
let objects_on_path = |s: &mut Session| {
|
||||
let spine = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
let attached = line(s, 400.0, 200.0, 420.0, 200.0);
|
||||
s.execute("object.objectsOnPath.attach", &json!({"path": spine.0, "ids": [attached.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [spine.0]})).unwrap();
|
||||
};
|
||||
// The name, the setup, the stroke, the paths after the release, and whether a frame previews once.
|
||||
type Case<'a> = (&'a str, &'a dyn Fn(&mut Session), &'a [(f64, f64)], usize, bool);
|
||||
let cases: [Case; 8] = [
|
||||
("new stroke", &none, &new_stroke, 1, true),
|
||||
("continues the end", &selected_line, &past_end, 1, true),
|
||||
("continues the start", &selected_line, &before_start, 1, true),
|
||||
("basic appearance off", ¬_basic, &new_stroke, 2, true),
|
||||
(
|
||||
"inherits a selected gradient",
|
||||
&selected_gradient,
|
||||
&[(100.0, 180.0), (120.0, 180.0), (140.0, 180.0), (160.0, 200.0), (180.0, 220.0), (200.0, 230.0)],
|
||||
2,
|
||||
false,
|
||||
),
|
||||
("two selected paths in a group", &grouped_paths, &past_end, 2, false),
|
||||
("global edit", &global_edit, &past_end, 2, false),
|
||||
("objects on path", &objects_on_path, &past_end, 2, false),
|
||||
];
|
||||
for (name, setup, pts, path_count, once) in cases {
|
||||
let (one_by_one, each, _) = pencil_in_frames(setup, pts, false);
|
||||
let (by_frames, previews, expected) = pencil_in_frames(setup, pts, true);
|
||||
if once {
|
||||
assert_eq!(previews, expected, "{name}: one preview for the drags of a frame, and one for its release");
|
||||
} else {
|
||||
assert_eq!(previews, each, "{name}: a preview per sample");
|
||||
}
|
||||
assert_eq!(by_frames.len(), one_by_one.len(), "{name}");
|
||||
for (k, (a, b)) in by_frames.iter().zip(&one_by_one).enumerate() {
|
||||
assert!(a == b, "{name}: state {k} differs from handing the samples over one by one");
|
||||
}
|
||||
let mut paths = 0;
|
||||
by_frames[by_frames.len() - 1].0.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(paths, path_count, "{name}: paths after the release");
|
||||
}
|
||||
}
|
||||
|
||||
/// One call that carries a Pencil release and the next stroke's press and drags previews every drag of the second
|
||||
/// stroke when that stroke begins with the first one selected and New Art Has Basic Appearance off, and leaves the
|
||||
/// document, the selection and the new-art paints as handing the events over one by one does.
|
||||
#[test]
|
||||
fn pencil_samples_spanning_two_strokes_decide_again_after_the_press() {
|
||||
let v = view();
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
rect(&mut s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
s.set_tool_option("fill", &json!(true));
|
||||
s.set_tool_option("keepSelected", &json!(true));
|
||||
assert!(s.doc().unwrap().selection.is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
for (x, y) in [(120.0, 100.0), (140.0, 120.0), (160.0, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut batched = setup();
|
||||
let mut individual = setup();
|
||||
let mut samples = vec![PointerEvent::new(PointerKind::Up, 160.0, 130.0), PointerEvent::new(PointerKind::Down, 100.0, 220.0)];
|
||||
let drags = [
|
||||
(120.0, 220.0),
|
||||
(140.0, 220.0),
|
||||
(160.0, 220.0),
|
||||
(180.0, 220.0),
|
||||
(200.0, 220.0),
|
||||
(220.0, 240.0),
|
||||
(240.0, 260.0),
|
||||
(260.0, 280.0),
|
||||
(280.0, 290.0),
|
||||
(300.0, 300.0),
|
||||
];
|
||||
samples.extend(drags.iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)));
|
||||
let before = crate::session::previews_run();
|
||||
let (fed, result) = batched.pointer_samples(&samples, v);
|
||||
result.unwrap();
|
||||
let batched_previews = crate::session::previews_run() - before;
|
||||
assert_eq!(fed, samples.len(), "every sample fed");
|
||||
let before = crate::session::previews_run();
|
||||
individual.pointer(&samples[0], v).unwrap();
|
||||
let release_previews = crate::session::previews_run() - before;
|
||||
assert!(!individual.doc().unwrap().selection.is_empty());
|
||||
for ev in &samples[1..] {
|
||||
individual.pointer(ev, v).unwrap();
|
||||
}
|
||||
let individual_previews = crate::session::previews_run() - before;
|
||||
assert_eq!(individual_previews, drags.len() + release_previews, "each drag runs a preview");
|
||||
assert_eq!(batched_previews, individual_previews, "the batch runs every preview");
|
||||
assert!(drawn(&batched) == drawn(&individual), "document, selection and new-art paints match");
|
||||
}
|
||||
|
||||
/// Connect two paths: with two open paths selected, a Pencil stroke from an end of one to an end
|
||||
/// of the other joins them into one path, the first one's, in one undo step. A path that is not
|
||||
/// selected is not joined.
|
||||
|
||||
@@ -526,6 +526,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() {
|
||||
("addon.arrange.sort", json!({"by": "area", "apply": "x"}), both),
|
||||
("addon.cleanup.simplify", json!({}), rect),
|
||||
("addon.cleanup.deepUngroup", json!({}), rect),
|
||||
("addon.cleanup.releaseAll", json!({}), rect),
|
||||
("addon.cleanup.rejoin", json!({}), rect),
|
||||
("addon.color.nearestSwatch", json!({}), rect),
|
||||
("addon.color.randomFill", json!({"seed": 1}), rect),
|
||||
|
||||
@@ -443,6 +443,55 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() {
|
||||
undo_gives_back(&mut s, &before);
|
||||
}
|
||||
|
||||
/// A Pencil stroke of 100 moves over 20,000 squares previews the path at every move. Each preview
|
||||
/// starts again from the document as it was at the press, whose lookup cache does not hold the new
|
||||
/// path; the first preview finds the path by walking the tree, and the later ones find it at the
|
||||
/// place that walk found. The release leaves one new path, selected, as one undo step; Group puts it
|
||||
/// in a group, and Undo puts it back and then removes it. A stroke canceled part way leaves no path.
|
||||
#[test]
|
||||
fn pencil_previews_find_the_new_path_without_walking_the_tree() {
|
||||
let mut s = session(20_000, square);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let first = before.peek_next_id();
|
||||
let v = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
let at = |kind, i: usize| PointerEvent::new(kind, 10.0 + 3.0 * i as f64, 50.0 + 20.0 * (i as f64 / 10.0).sin());
|
||||
s.pointer(&at(PointerKind::Down, 0), v).unwrap();
|
||||
s.pointer(&at(PointerKind::Drag, 1), v).unwrap();
|
||||
let (walks, revision) = (vectorcraft_doc::tree_walks(), s.doc().unwrap().revision);
|
||||
for i in 2..=100 {
|
||||
s.pointer(&at(PointerKind::Drag, i), v).unwrap();
|
||||
}
|
||||
let (walks, previews) = (vectorcraft_doc::tree_walks() - walks, (s.doc().unwrap().revision - revision) / 2);
|
||||
assert!(previews >= 99, "{previews} previews for 99 moves");
|
||||
assert!(walks <= 2, "{previews} previews walked the tree {walks} times");
|
||||
s.pointer(&at(PointerKind::Up, 100), v).unwrap();
|
||||
let path = NodeId(first);
|
||||
assert_eq!(layer(&s, 0).len(), 20_001);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert!(selected(&s, &[path]));
|
||||
let layer_id = before.layers[0].id;
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.ancestry(path), Some(vec![layer_id, group, path]));
|
||||
assert_eq!(children(&s, group), [path]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.ancestry(path), Some(vec![layer_id, path]));
|
||||
assert!(s.doc().unwrap().doc.node(group).is_none());
|
||||
undo_gives_back(&mut s, &before);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none());
|
||||
|
||||
// The same stroke, canceled after 50 moves.
|
||||
s.pointer(&at(PointerKind::Down, 0), v).unwrap();
|
||||
for i in 1..=50 {
|
||||
s.pointer(&at(PointerKind::Drag, i), v).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(path).is_some(), "the preview holds the path");
|
||||
s.cancel_interaction().unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before, "Cancel gives back the document");
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none() && s.doc().unwrap().doc.index_path(path).is_none());
|
||||
}
|
||||
|
||||
/// The ids under `n`: a child that can hold children is a list of its id and theirs.
|
||||
fn outline(n: &Node) -> Value {
|
||||
let ids = n.children().into_iter().flatten().map(|c| match c.children() {
|
||||
|
||||
@@ -76,6 +76,27 @@ fn missing_link_markers_follow_files_relink_update_and_embed() {
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
|
||||
/// A caller confined to other folders sees a linked file outside them as missing, but its answer
|
||||
/// does not replace the markers drawn on the canvas.
|
||||
#[test]
|
||||
fn a_confined_marked_query_leaves_the_canvas_markers_alone() {
|
||||
let dir = Folder::new("marker-confined");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(40, 40, RED));
|
||||
let other = dir.0.join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
let roots = crate::file_access::AutomationRoots::new(&[other.as_path()], &[]).unwrap();
|
||||
assert_eq!(crate::file_access::confine(roots.as_ref(), || marked(&mut s)), vec![id.0], "the caller cannot read the file");
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty(), "the canvas keeps no marker for a file that is there");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() {
|
||||
for mode in ["automatically", "askWhenModified", "manually"] {
|
||||
|
||||
@@ -558,6 +558,22 @@ fn align_new_objects_to_pixel_grid_follows_the_preset() {
|
||||
assert!(!align(&old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_rows_past_the_limit_read_as_the_limit_and_others_stay() {
|
||||
let mut s = Session::new();
|
||||
let saved = json!({"newDocPresets": [
|
||||
{"name": "Many", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 1001},
|
||||
{"name": "Four", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 4},
|
||||
]});
|
||||
s.apply_prefs(serde_json::from_value(saved).unwrap());
|
||||
for (name, rows) in [("Many", 1000), ("Four", 4)] {
|
||||
let layout = presets(&mut s, "Saved").iter().find(|p| p["name"] == name).unwrap()["artboardLayout"].clone();
|
||||
assert_eq!(layout["rows"], json!(rows), "{name}");
|
||||
// `file.new` takes the layout `file.newPresets` lists.
|
||||
s.execute("file.new", &json!({"preset": name, "artboardLayout": layout})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rearrange_keeps_its_grid() {
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
|
||||
|
||||
@@ -1136,6 +1136,30 @@ fn new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it() {
|
||||
batches_and_isolation_keep_new_art_protected(&mut s, pasted);
|
||||
}
|
||||
|
||||
/// A compound path pasted onto a locked artboard takes a path through node.move while it is still
|
||||
/// selected, and is refused as a destination once the selection leaves it out.
|
||||
#[test]
|
||||
fn node_move_into_new_compound_path_on_a_locked_artboard() {
|
||||
let mut s = session();
|
||||
let p = rect(&mut s);
|
||||
let q = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let e = NodeId(s.execute("shape.rectangle", &json!({"x": 340, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
let pasted = ids(&s.execute("edit.paste", &json!({"center": [1200, 200]})).unwrap()["ids"]);
|
||||
assert_eq!(pasted.len(), 2);
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), [compound], "the new compound path is selected");
|
||||
s.execute("node.move", &json!({"id": p.0, "parent": compound, "index": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(p), Some(NodeId(compound)), "new art takes the path");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("node.move", &json!({"id": q.0, "parent": compound, "index": 0})).is_err(), "no longer new art");
|
||||
assert_ne!(s.doc().unwrap().doc.parent_of(q), Some(NodeId(compound)));
|
||||
}
|
||||
|
||||
/// The batch, isolation and group cases of [`new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it`],
|
||||
/// with the pasted art `pasted` selected.
|
||||
fn batches_and_isolation_keep_new_art_protected(s: &mut Session, pasted: Vec<u64>) {
|
||||
|
||||
@@ -329,6 +329,45 @@ fn a_path_with_live_corners_snaps_its_inner_edges() {
|
||||
assert!(pts.iter().all(|p| (p.1 - 20.3).abs() > 1e-6), "{pts:?}");
|
||||
}
|
||||
|
||||
/// With relative radii, a move that bends a straightened corner and that the snap takes back
|
||||
/// leaves the path, its stored radius and the undo history as they were, and the corner rounds at
|
||||
/// its radius when a later move bends it.
|
||||
#[test]
|
||||
fn a_snap_that_takes_back_a_move_keeps_a_straightened_corners_relative_radius() {
|
||||
let mut s = new_doc();
|
||||
let id = path(&mut s, "M10 10 L40 20 L70 10 L70 40 L10 40 Z", 2.0);
|
||||
s.execute("object.setLiveShape", &json!({"id": id, "corners": [1], "radius": 4})).unwrap();
|
||||
// The corner's two anchors as drawn are 1 and 2: straighten it.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 2]], "mode": "add"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": -10.0})).unwrap();
|
||||
s.execute("object.setLiveShape", &json!({"id": id, "relativeRadii": true})).unwrap();
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id]})).unwrap();
|
||||
let live = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("no Live Corners") };
|
||||
(path.clone(), live.clone())
|
||||
};
|
||||
let (path_before, live_before) = live(&s);
|
||||
assert_eq!(points(&s, id), [(10.0, 10.0), (40.0, 10.0), (70.0, 10.0), (70.0, 40.0), (10.0, 40.0)]);
|
||||
let undo = undo_len(&s);
|
||||
// The straight corner and the anchor after it: the move bends the corner, the snap undoes it.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 2]], "mode": "add"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": 0.3})).unwrap();
|
||||
let (path_after, live_after) = live(&s);
|
||||
assert_eq!(path_after, path_before);
|
||||
assert_eq!(live_after, live_before, "the stored radius is unchanged");
|
||||
assert_eq!(undo_len(&s), undo, "no undo step for a move the snap took back");
|
||||
// Bend it again: it rounds at 4 points.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": 10.0})).unwrap();
|
||||
let (path, live) = live(&s);
|
||||
let c = vectorcraft_doc::LiveCorners::new(&path, Some(&*live)).unwrap();
|
||||
assert!((c.drawn_radius(1) - 4.0).abs() < 1e-6, "{live:?}");
|
||||
}
|
||||
|
||||
/// `path.setAnchors` and `object.setLiveShape` snap a pixel-aligned path again after they replace
|
||||
/// its geometry.
|
||||
#[test]
|
||||
|
||||
@@ -731,6 +731,68 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
|
||||
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_of_a_file_with_editing_data_keep_an_explicit_crop_box() {
|
||||
let dir = Folder::new("open-pdf-link-pages-explicit-crop");
|
||||
let src = dir.file("editable.ai");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"file.saveAs",
|
||||
&json!({"path": src, "format": "ai", "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&src).unwrap(), None));
|
||||
let board = |s: &Session| {
|
||||
let r = s.doc().unwrap().doc.artboards[0].rect;
|
||||
(r.width(), r.height())
|
||||
};
|
||||
// No box named: the trim box, as the file opens as art.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
// An explicit crop box is the crop box, which takes in the bleed.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "crop"})).unwrap();
|
||||
let (w, h) = board(&s);
|
||||
assert!(w > 100.0 && h > 50.0, "{w} x {h}");
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "crop": "crop"})).unwrap();
|
||||
assert_eq!(board(&s), (w, h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_with_only_a_native_attachment_default_to_crop_boxes() {
|
||||
let dir = Folder::new("open-pdf-link-pages-native-crop");
|
||||
let src = dir.file("editable.pdf");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"document.exportPdf",
|
||||
&json!({"path": src, "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
let bytes = std::fs::read(&src).unwrap();
|
||||
assert!(vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact));
|
||||
assert!(!vectorcraft_pdf::has_illustrator_data(&bytes, None));
|
||||
let board = |s: &Session| {
|
||||
let r = s.doc().unwrap().doc.artboards[0].rect;
|
||||
(r.width(), r.height())
|
||||
};
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
let (w, h) = board(&s);
|
||||
assert!(w > 100.0 && h > 50.0, "{w} x {h}");
|
||||
for key in ["cropTo", "crop"] {
|
||||
let mut params = json!({"path": src, "linkPages": true});
|
||||
params[key] = json!("crop");
|
||||
s.execute("document.open", ¶ms).unwrap();
|
||||
assert_eq!(board(&s), (w, h), "{key}");
|
||||
}
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
|
||||
@@ -177,6 +177,8 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
@@ -343,3 +345,103 @@ fn a_dialog_in_a_callback_throws_in_the_app() {
|
||||
assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0);
|
||||
}
|
||||
|
||||
/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns.
|
||||
const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());";
|
||||
|
||||
#[test]
|
||||
fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() {
|
||||
let mut s = one_doc();
|
||||
let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());");
|
||||
let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})]))
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}");
|
||||
let dialogs = r["dialogs"].as_array().unwrap();
|
||||
assert_eq!(dialogs.len(), 2);
|
||||
assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}");
|
||||
assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null");
|
||||
let cmyk = headless(
|
||||
&mut s,
|
||||
"var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);",
|
||||
answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_ends_the_run_when_no_answer_is_left() {
|
||||
let mut s = one_doc();
|
||||
let before = art(&s);
|
||||
let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
|
||||
for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] {
|
||||
let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}");
|
||||
let e = headless(&mut s, &source, given).unwrap_err().to_string();
|
||||
assert!(e.contains("showColorPicker") && e.contains(says), "{e}");
|
||||
assert_eq!(art(&s), before, "the run's edit goes back");
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["log"], json!([]), "a missing answer cannot be caught");
|
||||
assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}");
|
||||
}
|
||||
let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string();
|
||||
assert!(a.contains("is for colorPicker, not alert"), "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_refuses_what_is_not_a_solid_color() {
|
||||
let mut s = one_doc();
|
||||
let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\
|
||||
try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\
|
||||
try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());";
|
||||
let r = headless(&mut s, source, json!([])).unwrap();
|
||||
assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0, "no picker opened");
|
||||
for bad in [
|
||||
json!("not a color"),
|
||||
json!([255, 0, 0]),
|
||||
json!({"model": "lab", "l": 120, "a": 0, "b": 0}),
|
||||
json!(true),
|
||||
json!("rgb 300 0 0"),
|
||||
json!("cmyk 0 0 0 101"),
|
||||
json!("gray -1"),
|
||||
json!("lab 50 200 0"),
|
||||
json!("rgb 255.000001 0 0"),
|
||||
json!([1.00000001, 0, 0]),
|
||||
json!({"c": 100.000001, "m": 0, "y": 0, "k": 0}),
|
||||
json!({"gray": 100.000001}),
|
||||
json!({"l": 100.000001, "a": 0, "b": 0}),
|
||||
json!({"model": "rgb", "r": 1.00000001, "g": 0, "b": 0}),
|
||||
json!({"model": "lab", "l": 50, "a": -128.000001, "b": 0}),
|
||||
] {
|
||||
let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string();
|
||||
assert!(e.contains("color picker's answer"), "{bad}: {e}");
|
||||
}
|
||||
for good in [
|
||||
json!("rgb 255 0 0"),
|
||||
json!("cmyk 0 100 100 0"),
|
||||
json!("gray 100"),
|
||||
json!("lab 50 -128 128"),
|
||||
json!([1, 0, 0]),
|
||||
json!({"c": 0, "m": 100, "y": 100, "k": 0}),
|
||||
json!({"gray": 100}),
|
||||
json!({"l": 100, "a": -128, "b": 128}),
|
||||
json!({"model": "rgb", "r": 1, "g": 0, "b": 0}),
|
||||
] {
|
||||
assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_framed_run_waits_at_the_color_picker() {
|
||||
let mut s = one_doc();
|
||||
framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);"));
|
||||
let d = s.script_dialog().unwrap();
|
||||
assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)))));
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given");
|
||||
assert!(s.script_answer(DialogAnswer::ColorPicker(None)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}");
|
||||
}
|
||||
@@ -741,8 +741,9 @@ fn assigning_the_reported_opacity_changes_nothing() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap();
|
||||
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
|
||||
let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;");
|
||||
assert_eq!(out, vec![json!(33.3333)]);
|
||||
let r = run(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;").unwrap();
|
||||
assert_eq!(r["log"], json!([33.3333]));
|
||||
assert_eq!(r["slowestCommands"], json!([]), "no command runs for the opacity the item has");
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
|
||||
@@ -842,8 +843,14 @@ fn a_layer_opacity_close_to_the_current_one_is_set() {
|
||||
fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
|
||||
let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];");
|
||||
assert!(e.contains("Cannot select PathItem"), "{e}");
|
||||
// The script catches the error and reads the selection before the run ends.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, e = '';\
|
||||
try { d.selection = [p[0], p[1]]; } catch (x) { e = String(x); } vc.log(e); vc.log(d.selection.length);",
|
||||
);
|
||||
assert!(out[0].as_str().is_some_and(|e| e.contains("Cannot select PathItem")), "{out:?}");
|
||||
assert_eq!(out[1], json!(0));
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
// In either order, the refused assignment leaves nothing selected while the script runs.
|
||||
let out = log(
|
||||
@@ -875,6 +882,9 @@ fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]);
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
|
||||
// A list with an item repeated thousands of times selects it once.
|
||||
log(&mut s, "var d = app.activeDocument, p = d.pageItems, l = []; for (var i = 0; i < 5000; i++) l.push(p[0], p[1]); d.selection = l;");
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![b, a]);
|
||||
// An item of another document cannot be selected here.
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];");
|
||||
@@ -1541,6 +1551,22 @@ fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4);
|
||||
}
|
||||
|
||||
/// A layout that replaces the rows keeps the columns the rows gave the artboards there are now,
|
||||
/// whether or not the change of artboards came with a layout of its own.
|
||||
#[test]
|
||||
fn replacing_rows_keeps_the_columns_of_the_artboards_there_are_now() {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, DocSettings};
|
||||
let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() };
|
||||
let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap();
|
||||
for change in [json!({"artboards": 9}), json!({"artboards": 9, "artboardLayout": {"spacing": 20}})] {
|
||||
let more = settings.clone().with_params(&change, "file.new").unwrap();
|
||||
for layout in [json!("gridByRow"), json!({"layout": "gridByRow"})] {
|
||||
let by_row = more.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap();
|
||||
assert_eq!(by_row.grid_columns(), 3, "{change} then {layout}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_documents_throw_on_every_member() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1812,7 +1838,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
] {
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
assert!(failure(&mut s, "app.activeDocument.swatches = 1;").contains("Document.swatches is not available yet"));
|
||||
assert!(failure(&mut s, "app.activeDocument.gradients = 1;").contains("Document.gradients is not available yet"));
|
||||
// A deleted item or an earlier run's document is stale first.
|
||||
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;");
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
@@ -1862,6 +1888,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() {
|
||||
assert!(s.active().unwrap().doc.node(a).is_none());
|
||||
}
|
||||
|
||||
/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round.
|
||||
#[test]
|
||||
fn a_path_made_with_a_large_id_keeps_its_id() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);");
|
||||
assert_eq!(out, vec![json!("big")]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big"));
|
||||
}
|
||||
|
||||
/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and
|
||||
/// leaves the selection as it was; `null` still clears it.
|
||||
#[test]
|
||||
fn assigning_undefined_to_the_selection_throws() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];");
|
||||
assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}");
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
|
||||
log(&mut s, "app.activeDocument.selection = null;");
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_class_constructors_construct() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -2007,14 +2059,41 @@ fn note_is_the_attributes_note() {
|
||||
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "colorMode": "rgb"})).unwrap();
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
|
||||
assert_eq!(out[0], json!([612, 792, "DocumentColorSpace.CMYK"]));
|
||||
// Recent keeps the built-in preset's name, as it does when no saved preset has it.
|
||||
assert_eq!(s.prefs.recent_new_docs[0].name, "Letter");
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var e = app.documents.addDocument('Print', p); vc.log([e.width, e.height]);");
|
||||
assert_eq!(out[0], json!([300, 792]));
|
||||
assert_eq!(s.prefs.recent_new_docs[0].name, "Custom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
|
||||
s.execute(
|
||||
"file.newPresets.save",
|
||||
&json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb", "artboardLayout": "row"}),
|
||||
)
|
||||
.unwrap();
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
|
||||
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
|
||||
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
|
||||
// Several artboards are laid out as the built-in preset lays them out when no saved preset
|
||||
// has its name, and the title is kept.
|
||||
let three = "var p = new DocumentPreset(); p.numArtboards = 3; p.title = 'Three';\
|
||||
p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; p.artboardSpacing = undefined; var d = app.documents.addDocument('Print', p);\
|
||||
var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); vc.log([d.name, r]);";
|
||||
let out = log(&mut s, three);
|
||||
let unshadowed = log(&mut Session::new(), three);
|
||||
assert_eq!(out[0][0], json!("Three"));
|
||||
assert_eq!(out[0][1].as_array().map(Vec::len), Some(3), "{out:?}");
|
||||
assert_eq!(out, unshadowed, "the saved preset changes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2495,6 +2574,57 @@ fn wrappers_go_stale_after_revert() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's collections read before File › Revert do not list the loaded document's art, even
|
||||
/// where the loaded layer has the same id.
|
||||
#[test]
|
||||
fn a_layers_collections_read_before_a_revert_are_stale() {
|
||||
let (mut s, ..) = doc();
|
||||
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-lists");
|
||||
let path = folder.join("saved.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
for list in ["pathItems", "pageItems", "groupItems", "compoundPathItems", "layers"] {
|
||||
let source = format!(
|
||||
"var d = app.activeDocument, c = d.layers[0].{list}; vc.log(c.length >= 0); d.pageItems[0].name = 'changed'; vc.run('file.revert');\
|
||||
try {{ c.length; vc.log('ran'); }} catch (e) {{ vc.log('stale'); }} vc.log(d.layers[0].{list}.length >= 0);"
|
||||
);
|
||||
assert_eq!(log(&mut s, &source), vec![json!(true), json!("stale"), json!(true)], "{list}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard read before File › Revert is stale, even though the loaded artboard has the same
|
||||
/// id; the document's `artboards` read before it lists the loaded ones.
|
||||
#[test]
|
||||
fn an_artboard_read_before_a_revert_is_stale() {
|
||||
let (mut s, ..) = doc();
|
||||
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-artboard");
|
||||
let path = folder.join("saved.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, bs = d.artboards, b = bs[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\
|
||||
try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(bs[0].name == saved);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Stale artboard"), json!(true)]);
|
||||
}
|
||||
|
||||
/// A key that is the text of a number but not an array index reaches an indexer as a number, and
|
||||
/// a layer's collections and `artboards` look it up as a name, as the document's `pageItems` does.
|
||||
/// `index()` still takes a number as a position.
|
||||
#[test]
|
||||
fn scoped_collections_find_names_that_are_numbers() {
|
||||
let (mut s, ..) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, l = d.layers[0], i = l.pageItems[0]; i.name = '-1'; l.layers.add().name = '1.5';\
|
||||
d.artboards[0].name = '-1';\
|
||||
vc.log(l.pageItems['-1'] === i); vc.log(l.pathItems['-1'] === i); vc.log(l.layers['1.5'].name);\
|
||||
vc.log(d.artboards['-1'].name); vc.log(l.pageItems['-2'] === undefined); vc.log(l.pageItems.index(0) === i);\
|
||||
try { l.pageItems.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }\
|
||||
try { d.artboards.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!("1.5"), json!("-1"), json!(true), json!(true), json!("Not found"), json!("Not found")]);
|
||||
}
|
||||
|
||||
/// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does.
|
||||
#[test]
|
||||
fn a_layers_page_items_read_names_as_the_documents_do() {
|
||||
@@ -2681,6 +2811,9 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
"app.activeDocument.groupItems.getByName('locked').pageItems",
|
||||
"app.activeDocument.layers[0].compoundPathItems",
|
||||
"app.activeDocument.compoundPathItems",
|
||||
"app.activeDocument.pathItems",
|
||||
"app.activeDocument.groupItems.getByName('locked').pathItems",
|
||||
"app.activeDocument.compoundPathItems[0].pathItems",
|
||||
] {
|
||||
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
|
||||
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
|
||||
@@ -3005,6 +3138,18 @@ fn an_unknown_menu_command_throws_and_names_it() {
|
||||
assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu"));
|
||||
}
|
||||
|
||||
/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a
|
||||
/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`.
|
||||
#[test]
|
||||
fn get_is_file_open_compares_paths_by_the_platform_s_rules() {
|
||||
use crate::script::dom::path_key_on;
|
||||
assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false));
|
||||
assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false));
|
||||
assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false));
|
||||
assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true));
|
||||
assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_dom_values_do_not_reenter_or_exceed_limits() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -3073,7 +3218,7 @@ fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
|
||||
#[test]
|
||||
fn unsupported_members_say_so() {
|
||||
let (mut s, _, _) = doc();
|
||||
assert!(failure(&mut s, "app.activeDocument.swatches;").contains("Document.swatches is not available yet"));
|
||||
assert!(failure(&mut s, "app.activeDocument.gradients;").contains("Document.gradients is not available yet"));
|
||||
}
|
||||
|
||||
fn layer_names(s: &Session) -> Vec<String> {
|
||||
@@ -3296,6 +3441,202 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() {
|
||||
assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() {
|
||||
let (mut s, _, b) = doc();
|
||||
let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the
|
||||
// document's list holds all three, the layer's only `a`, and a sublayer's path is its own.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\
|
||||
vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\
|
||||
vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\
|
||||
var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\
|
||||
sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\
|
||||
vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); vc.log(P[1] === undefined);",
|
||||
);
|
||||
let expected =
|
||||
[json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)];
|
||||
assert_eq!(out[..11], expected);
|
||||
// With the sublayer's path above the group, the layer's own path and both of the group's paths
|
||||
// named `B`, each collection's named lookups give its own topmost path.
|
||||
assert_eq!(out[11..], [json!(true), json!(true), json!(true), json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_over_a_groups_path_items_builds_the_list_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let ids: Vec<u64> = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
// Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list
|
||||
// of 1,000 paths is not built again for each read.
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19)));
|
||||
let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
assert_eq!(r.unwrap()["log"], json!([1000]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layers_path_items_make_their_paths_on_top_of_that_layer() {
|
||||
let (mut s, ..) = doc();
|
||||
let bottom = s.active().unwrap().doc.layers[0].id;
|
||||
let selected = s.active().unwrap().selection.clone();
|
||||
let steps = undo_steps(&s);
|
||||
// A new layer becomes the current one; each creator of the first layer's `pathItems` still
|
||||
// puts its path on top of that layer.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\
|
||||
var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\
|
||||
function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\
|
||||
for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\
|
||||
vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);",
|
||||
);
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..6 {
|
||||
expected.extend([json!(true), json!(format!("m{i}"))]);
|
||||
}
|
||||
expected.extend([json!(true), json!(0), json!(8)]);
|
||||
assert_eq!(out, expected);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let st = s.active().unwrap();
|
||||
let kids = st.doc.node(bottom).unwrap().children().unwrap();
|
||||
assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5"));
|
||||
assert!(st.selection == selected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_path_items_add_puts_the_path_in_the_group() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\
|
||||
vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\
|
||||
var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);",
|
||||
);
|
||||
assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let top: Vec<Option<&str>> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect();
|
||||
assert_eq!(top, [Some("R"), Some("N")]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() {
|
||||
const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group";
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let lid = s.active().unwrap().doc.layers[0].id;
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap();
|
||||
let locked = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] {
|
||||
assert!(failure(&mut s, src).contains(REFUSED), "{src}");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked);
|
||||
}
|
||||
// Caught inside the script, each refusal leaves both collections as they were, and the group,
|
||||
// shown and unlocked itself, is refused for its locked layer.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\
|
||||
var n = [L.pathItems.length, g.pathItems.length];\
|
||||
try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);",
|
||||
);
|
||||
let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(refused.len(), 3, "{out:?}");
|
||||
assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}");
|
||||
assert_eq!(out[1], out[2], "the collections are unchanged inside the script");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked);
|
||||
s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap();
|
||||
let hidden = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED));
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden);
|
||||
s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap();
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
// A group's `pathItems` read after the group is gone throw.
|
||||
let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;");
|
||||
assert!(msg.contains("Stale page item"), "{msg}");
|
||||
}
|
||||
|
||||
/// A collection read with a name gives what its `getByName` gives, in a layer's or a group's
|
||||
/// collections as in the document's, and a name nothing has is not `in` it.
|
||||
#[test]
|
||||
fn collections_read_with_a_name_give_the_named_object() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.groupItems[0], r = g.pageItems[0]; r.name = 'Logo'; g.name = 'G';\
|
||||
vc.log([g.pageItems['Logo'] === r, g.pathItems['Logo'] === r, d.pathItems['Logo'] === r, d.groupItems['G'] === g,\
|
||||
d.layers[0].groupItems['G'] === g, d.layers['Layer 1'] === d.layers[0], d.artboards[d.artboards[0].name] === d.artboards[0]]);\
|
||||
vc.log(['Logo' in g.pageItems, 'missing' in g.pageItems, 'missing' in g.pathItems, 'missing' in d.layers, 'missing' in d.artboards]);\
|
||||
var m = ''; try { g.pageItems['missing']; } catch (e) { m = e.message; } vc.log(m);",
|
||||
);
|
||||
assert_eq!(out[0], json!([true, true, true, true, true, true, true]), "{out:?}");
|
||||
assert_eq!(out[1], json!([true, false, false, false, false]), "{out:?}");
|
||||
assert_eq!(out[2], json!("Not found"), "{out:?}");
|
||||
}
|
||||
|
||||
/// A compound path's `pathItems.removeAll()` leaves it, empty, as `remove()` of its last path
|
||||
/// does.
|
||||
#[test]
|
||||
fn clearing_the_paths_of_a_compound_path_keeps_the_compound_path() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = layer_order(&s)[0];
|
||||
let out = log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length]);");
|
||||
assert_eq!(out, vec![json!(["CompoundPathItem", 0])]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty");
|
||||
}
|
||||
|
||||
/// A Live Paint group's collections make nothing in it: what they made would join the group's
|
||||
/// paths instead of being one of its objects.
|
||||
#[test]
|
||||
fn collections_of_a_live_paint_group_make_nothing() {
|
||||
const REFUSED: &str = "Cannot add an object to a Live Paint group";
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("livePaint.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.pageItems[0], m = [];\
|
||||
try { g.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.groupItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.compoundPathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(refused.len(), 4, "{out:?}");
|
||||
assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -3337,9 +3678,48 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() {
|
||||
assert!(failure(&mut s, src).contains("only paths"), "{src}");
|
||||
}
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
// Caught inside the run, the refused move leaves the object where it was and the compound
|
||||
// path's members as they were.
|
||||
for (make, to) in
|
||||
[("d.groupItems.add()", "C"), ("d.groupItems.add()", "C.pathItems[0], ElementPlacement.PLACEBEFORE"), ("d.compoundPathItems.add()", "C")]
|
||||
{
|
||||
let src = format!(
|
||||
"var d = app.activeDocument, C = d.compoundPathItems.getByName('C'), o = {make};\
|
||||
try {{ o.move({to}); vc.log('moved'); }} catch (e) {{ vc.log(String(e).indexOf('only paths') >= 0); }}\
|
||||
vc.log(o.parent.typename); vc.log(C.pathItems.length); vc.log(C.pathItems[0].parent.typename);"
|
||||
);
|
||||
assert_eq!(log(&mut s, &src), [json!(true), json!("Layer"), json!(2), json!("CompoundPathItem")], "{src}");
|
||||
}
|
||||
assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false"));
|
||||
}
|
||||
|
||||
/// A Shaper group rebuilds its contents from the source art it holds first, so `object.newGroup`
|
||||
/// refuses it as a parent: at index 0 the empty group would take the sources' place and the
|
||||
/// Shaper group would be deleted.
|
||||
#[test]
|
||||
fn new_group_refuses_a_shaper_group_as_its_parent() {
|
||||
let (mut s, a, _) = doc();
|
||||
let b = rect(&mut s, 30.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 40], [50, 40]]})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = s.active().unwrap().doc.node(shaper).cloned().unwrap();
|
||||
for index in [json!(0), json!(1), Value::Null] {
|
||||
let mut p = json!({"parent": shaper.0});
|
||||
if !index.is_null() {
|
||||
p["index"] = index;
|
||||
}
|
||||
let err = s.execute("object.newGroup", &p).unwrap_err().to_string();
|
||||
assert!(err.contains("Shaper group"), "{p}: {err}");
|
||||
assert_eq!(s.active().unwrap().doc.node(shaper), Some(&before), "{p}");
|
||||
}
|
||||
// Making a clipping mask moves the topmost object to index 0 the same way.
|
||||
let err = s.execute("layer.clippingMask.toggle", &json!({"id": shaper.0})).unwrap_err().to_string();
|
||||
assert!(err.contains("Shaper group"), "{err}");
|
||||
let src = "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('clipped'); } catch (e) { vc.log(String(e).indexOf('Shaper group') >= 0); }";
|
||||
assert_eq!(log(&mut s, src), [json!(true)]);
|
||||
assert_eq!(s.active().unwrap().doc.node(shaper), Some(&before));
|
||||
}
|
||||
|
||||
/// The paint of a compound path's only path is the compound path's: moved into an empty compound
|
||||
/// path, the path gives it that paint, not its own default one.
|
||||
#[test]
|
||||
@@ -4127,6 +4507,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() {
|
||||
assert!(!d.node(a).unwrap().extras().pixel_aligned);
|
||||
}
|
||||
|
||||
/// A pixel-aligned compound path snaps a path that was not aligned when it takes it in.
|
||||
#[test]
|
||||
fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
let loose = rect(&mut s, 200.25, 20.5, 30.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!s.active().unwrap().doc.node(loose).unwrap().extras().pixel_aligned);
|
||||
s.execute("node.move", &json!({"id": loose.0, "parent": cid.0, "index": 0})).unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(loose), Some(cid));
|
||||
// Both paths have a 1 pt stroke, so the grid puts their edges where it put the aligned path's.
|
||||
let (b, at) = (d.node(loose).unwrap().geometric_bounds().unwrap(), d.node(a).unwrap().geometric_bounds().unwrap());
|
||||
assert_ne!(b.x0, 200.25);
|
||||
for (v, w) in [(b.x0, at.x0), (b.y0, at.y0), (b.x1, at.x1), (b.y1, at.y1)] {
|
||||
assert_eq!(v.fract(), w.fract(), "{b:?} is on the pixel grid as {at:?} is");
|
||||
}
|
||||
}
|
||||
|
||||
/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid
|
||||
/// with the compound path's other paths.
|
||||
#[test]
|
||||
@@ -4170,18 +4573,39 @@ fn a_compound_paths_path_items_are_page_items() {
|
||||
out,
|
||||
[json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)]
|
||||
);
|
||||
for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] {
|
||||
// The path creation methods make the new path inside the compound path.
|
||||
for (made, call) in
|
||||
["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let source = format!(
|
||||
"var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);"
|
||||
);
|
||||
let out = log(&mut s, &source);
|
||||
assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(out, [json!("made"), json!(made + 3)], "{call}");
|
||||
}
|
||||
run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap();
|
||||
assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_paths_path_items_add_makes_the_path_inside_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var c = app.activeDocument.layers[0].compoundPathItems.add(); var p = c.pathItems.add(); p.setEntirePath([[0, 0], [10, 0], [10, 10]]);\
|
||||
var r = c.pathItems.rectangle(50, 20, 10, 10); vc.log(c.pathItems.length); vc.log(p.parent.typename); vc.log(r.parent.typename);\
|
||||
vc.log(c.pathItems[0].width);",
|
||||
);
|
||||
assert_eq!(out, [json!(2), json!("CompoundPathItem"), json!("CompoundPathItem"), json!(10)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap();
|
||||
assert_eq!(compound.children().unwrap().len(), 2);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_collections_follow_edits_between_reads() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -4327,6 +4751,18 @@ fn has_selected_artwork_keeps_selected_objects_in_other_layers() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_lists_follow_edits_between_reads() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var L = app.activeDocument.layers, n = L.length; for (var i = 0; i < L.length; i++) L[i];\
|
||||
var made = L.add(); made.name = 'Top'; vc.log(L.length - n); vc.log(L[0].name); vc.log(L.getByName('Top').name);\
|
||||
made.remove(); vc.log(L.length - n);",
|
||||
);
|
||||
assert_eq!(out, [json!(1), json!("Top"), json!("Top"), json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_items_remove_all_refuses_locked_groups() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -4500,6 +4936,20 @@ fn a_stale_containers_list_throws_its_stale_error_for_any_index() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stale `layers` or `artboards` collection's `index(n)` throws the stale error for every
|
||||
/// number, a negative or fractional one included, as the art collections do.
|
||||
#[test]
|
||||
fn stale_layers_and_artboards_throw_their_stale_error_for_any_index() {
|
||||
let (mut s, ..) = doc();
|
||||
run(&mut s, "#targetengine keep\nvar d = app.activeDocument, L = d.layers, A = d.artboards;").unwrap();
|
||||
for list in ["L", "A"] {
|
||||
for n in ["-1", "1.5", "0"] {
|
||||
let e = failure(&mut s, &format!("#targetengine keep\n{list}.index({n});"));
|
||||
assert!(e.contains("Stale document"), "{list}.index({n}): {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is
|
||||
/// not its clipping path; the run's one undo step puts everything back.
|
||||
#[test]
|
||||
@@ -4989,7 +5439,7 @@ fn page_items_report_their_available_members_as_their_own() {
|
||||
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
|
||||
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
|
||||
app.hasOwnProperty('activeDocument')]);\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('gradients'),\
|
||||
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_geom::path::AnchorKind;
|
||||
|
||||
use crate::*;
|
||||
@@ -281,6 +282,43 @@ fn path_items_remove_all_refuses_paths_on_a_locked_artboard() {
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
/// A clipping group's `pathItems` lists only its clipping path when its other art is a group:
|
||||
/// `removeAll()` throws and deletes nothing, as `pageItems.removeAll()` does, so the group does not
|
||||
/// become the clipping path.
|
||||
#[test]
|
||||
fn path_items_remove_all_refuses_a_clipping_path_whose_group_keeps_other_objects() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.group", &json!({"ids": [b.0]})).unwrap();
|
||||
let inner = s.active().unwrap().doc.parent_of(b).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, inner.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let clip = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [clip.0], "name": "clip"})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.groupItems.getByName('clip').pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete a clipping path") && e.contains(&a.0.to_string()), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// The document's `pathItems.removeAll()` deletes a compound path whose paths it all lists, so a
|
||||
/// clipping group that holds only its clipping path and that compound path is left with nothing
|
||||
/// and is not refused.
|
||||
#[test]
|
||||
fn path_items_remove_all_counts_compound_paths_it_empties() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().doc.parent_of(b).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, compound.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none() && d.node(compound).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_creators_use_documented_defaults_and_y_up() {
|
||||
let mut s = Session::new();
|
||||
@@ -338,6 +376,76 @@ fn shape_creators_reject_bad_sizes_without_change() {
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_point_deselects_a_path_with_direct_selected_anchors() {
|
||||
// `pathItems[1]` is `b`.
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [a.0]})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3));
|
||||
let sel = &st.selection;
|
||||
// A removal renumbers the direct selection: the selected anchor after the removed one moves
|
||||
// down one place.
|
||||
assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::<Vec<_>>()), Some(vec![(0, 0)]), "{sel:?}");
|
||||
assert!(sel.objects.contains(&a));
|
||||
// Moving a point keeps the anchors selected.
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];");
|
||||
assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1);
|
||||
}
|
||||
|
||||
/// Points are found by their index across subpaths, through changes that wait to be written and
|
||||
/// removals that change how many points a subpath has or remove a subpath.
|
||||
#[test]
|
||||
fn points_are_found_across_subpaths_as_their_counts_change() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false});
|
||||
let subs = json!([
|
||||
{"anchors": [pt(0.0), pt(1.0)], "closed": false},
|
||||
{"anchors": [pt(2.0)], "closed": false},
|
||||
{"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false},
|
||||
]);
|
||||
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\
|
||||
for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\
|
||||
vc.log(q[2].anchor); vc.log(q[5].anchor);\
|
||||
q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\
|
||||
q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);",
|
||||
);
|
||||
let want =
|
||||
[json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)];
|
||||
assert_eq!(out, want);
|
||||
let n = node(&s, a);
|
||||
let counts: Vec<usize> = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect();
|
||||
assert_eq!(counts, vec![1, 3]);
|
||||
}
|
||||
|
||||
/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points
|
||||
/// start: the index is built again only when a change adds or removes points.
|
||||
#[test]
|
||||
fn moving_each_point_keeps_the_index_of_the_subpaths() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let subs: Vec<Value> =
|
||||
(0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect();
|
||||
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap();
|
||||
let before = crate::script::dom::index_builds();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([49, 7])]);
|
||||
let built = crate::script::dom::index_builds() - before;
|
||||
assert!(built <= 3, "the index was built {built} times");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_entire_path_replaces_points_and_keeps_closed() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -357,6 +465,34 @@ fn set_entire_path_replaces_points_and_keeps_closed() {
|
||||
assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_bounds_take_in_direction_handles() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\
|
||||
var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\
|
||||
n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);",
|
||||
);
|
||||
assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds");
|
||||
let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::<Vec<_>>();
|
||||
let (control, visible) = (edges(&out[2]), edges(&out[3]));
|
||||
assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}");
|
||||
assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}");
|
||||
assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}");
|
||||
}
|
||||
|
||||
/// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as
|
||||
/// it is from the visible bounds.
|
||||
#[test]
|
||||
fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);");
|
||||
assert_eq!(out[0], out[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_set_entire_path_input_is_bounded() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -420,6 +556,9 @@ fn path_point_setters_edit_one_anchor() {
|
||||
for i in [0, 2, 3] {
|
||||
assert_eq!(anchors[i], anchors_before[i], "point {i} did not change");
|
||||
}
|
||||
// The 300 pt tall document's y runs down, so script y 285 is document y 15.
|
||||
let edited = &anchors[1];
|
||||
assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0)));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite"));
|
||||
@@ -1021,17 +1160,174 @@ fn compound_path_members_read_the_paint_they_are_given() {
|
||||
assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_in_a_group_in_a_compound_shape_read_and_set_the_compound_shapes_paint() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group, b.0]})).unwrap();
|
||||
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = node(&s, a).appearance.clone();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = null, all = app.activeDocument.pathItems; for (var i = 0; i < all.length; i++) if (all[i].geometricBounds[0] < 50) p = all[i];\
|
||||
vc.log(p.parent.parent.typename); var c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4; vc.log([p.fillColor.red, p.strokeWidth]);",
|
||||
);
|
||||
assert_ne!(out[0], json!("Layer"), "the path is inside a group inside the compound shape");
|
||||
assert_eq!(rounded(&out[1]), json!([200, 4]));
|
||||
let Paint::Solid { color: Color::Rgb { r, .. }, .. } = node(&s, shape).appearance.fill_paint() else {
|
||||
panic!("the compound shape has an RGB fill")
|
||||
};
|
||||
assert!((r - 200.0 / 255.0).abs() < 1e-3, "the compound shape takes the fill, got {r}");
|
||||
assert_eq!(node(&s, a).appearance, before, "the nested path's own paint is left as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_set_on_an_empty_path_holds_until_it_has_points() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems.add(); vc.log(p.closed); p.closed = true; vc.log(p.closed);\
|
||||
p.setEntirePath([[0, 300], [40, 300], [40, 240]]); vc.log(p.closed);\
|
||||
var q = app.activeDocument.pathItems.add(); q.closed = true; q.closed = false; q.setEntirePath([[0, 0], [1, 1]]); vc.log(q.closed);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(false), json!(true), json!(true), json!(false)]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems.add(); p.closed = true; p.pathPoints.add(); vc.log(p.closed);\
|
||||
p.closed = false; p.pathPoints.removeAll(); vc.log(p.closed);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(false)], "pathPoints.add keeps the state, and an opened path does not reopen closed");
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.lock", &json!({"ids": [id.0]})).unwrap();
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints.length); p.closed = false; vc.log(p.closed);");
|
||||
assert_eq!(out, vec![json!(0), json!(false)], "an unchanged assignment on a locked empty path is allowed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap();
|
||||
let before = node(&s, a).appearance.fill_paint();
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.tint]);");
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", 40]));
|
||||
assert!(failure(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").contains("SpotColor is not available yet"));
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint]);");
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 40]));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;");
|
||||
assert_eq!(undo_steps(&s), steps, "assigning the spot color the fill has records no step");
|
||||
assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_paints_its_spot_at_its_tint() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink'); c.tint = 50;\
|
||||
p.fillColor = c; p.strokeColor = c; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint, p.strokeColor.tint]);",
|
||||
);
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 50, 50]));
|
||||
let n = node(&s, a);
|
||||
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
|
||||
match paint {
|
||||
Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - 0.5).abs() < 1e-6, "{name} at {tint}"),
|
||||
p => panic!("the paint is {p:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_left_without_a_tint_paints_at_its_default() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink');\
|
||||
p.fillColor = c; vc.log([p.fillColor.spot.name, p.fillColor.tint]);\
|
||||
p.strokeColor = {typename: 'SpotColor', spot: d.spots.getByName('Ink')}; vc.log([p.strokeColor.spot.name, p.strokeColor.tint]);",
|
||||
);
|
||||
assert_eq!(rounded(&Value::Array(out)), json!([["Ink", 100], ["Ink", 0]]), "new SpotColor() starts at 100, a color without a tint is 0");
|
||||
let n = node(&s, a);
|
||||
for (paint, want) in [(n.appearance.fill_paint(), 1.0), (n.appearance.stroke_paint(), 0.0)] {
|
||||
match paint {
|
||||
Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - want).abs() < 1e-6, "{name} at {tint}"),
|
||||
p => panic!("the paint is {p:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_process_link_read_as_a_spot_color_is_not_assigned() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#3a9a40", "global": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Moss", "color": "#405a20", "global": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Leaf", "tint": 60})).unwrap();
|
||||
let b = rect(&mut s, 30.0, 30.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [b.0], "swatch": "Moss", "tint": 60})).unwrap();
|
||||
let c = rect(&mut s, 60.0, 60.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap();
|
||||
let paints = |s: &Session| [a, b, c].map(|id| node(s, id).appearance.fill_paint());
|
||||
let before = paints(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems; vc.log([q[2].fillColor.typename, q[2].fillColor.spot === undefined, q[1].fillColor.typename, q[0].fillColor.typename]);",
|
||||
);
|
||||
// `pathItems` lists c (unlinked), b (Moss), a (Leaf) and the document's first rectangle.
|
||||
assert_eq!(out, vec![json!(["SpotColor", true, "SpotColor", "RGBColor"])]);
|
||||
for script in [
|
||||
"var q = app.activeDocument.pathItems; q[2].fillColor = q[2].fillColor;",
|
||||
"var q = app.activeDocument.pathItems; q[1].fillColor = q[2].fillColor;",
|
||||
"var q = app.activeDocument.pathItems; q[0].fillColor = q[2].fillColor;",
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains("global process swatch cannot be assigned yet"), "{script}: {e}");
|
||||
assert_eq!(paints(&s), before, "{script}");
|
||||
assert_eq!(undo_steps(&s), steps, "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_painted_with_registration_reads_and_takes_its_spot() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('[Registration]'); c.tint = 100;\
|
||||
p.strokeColor = c; vc.log([p.strokeColor.typename, p.strokeColor.spot.name, p.strokeColor.tint]);",
|
||||
);
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", "[Registration]", 100]));
|
||||
assert!(node(&s, a).appearance.stroke_paint().is_registration(), "the stroke is linked to Registration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_without_a_spot_of_the_document_is_refused() {
|
||||
let (mut s, _) = doc_with_paints();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let layers = |s: &Session| s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect::<Vec<_>>();
|
||||
let before = layers(&s);
|
||||
let steps = undo_steps(&s);
|
||||
for (source, part) in [
|
||||
("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"),
|
||||
("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"),
|
||||
// `app.documents` lists the active document, the new one, first: the document with `Ink` is
|
||||
// `documents[1]`.
|
||||
("var a = app.documents[1], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"),
|
||||
(
|
||||
"var a = app.documents[1], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;",
|
||||
"SpotColor.tint",
|
||||
),
|
||||
(
|
||||
"var a = app.documents[1], b = app.documents[0], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); b.pathItems[0].fillColor = c;",
|
||||
"Cross-document",
|
||||
),
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
}
|
||||
assert_eq!(layers(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filled_true_on_a_filled_path_runs_no_command() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1064,6 +1360,29 @@ fn identity_transforms_of_an_empty_path_do_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_or_scaling_an_empty_path_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);");
|
||||
assert_eq!(undo_steps(&s), 1, "only the path is added");
|
||||
}
|
||||
|
||||
/// Scaling stroke weights and effects by the scale itself without moving the object is refused for
|
||||
/// a path with no anchors as it is for one with bounds, and the stroke weight stays.
|
||||
#[test]
|
||||
fn scaling_line_widths_alone_is_refused_for_an_empty_path() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;");
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(50, 50, false, false, false, false, 50);");
|
||||
assert!(e.contains("changeLineWidths other than 100 with changePositions false"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(4)]);
|
||||
}
|
||||
|
||||
/// The paint of the fill (`fill`) or stroke of `id`.
|
||||
fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint {
|
||||
let n = node(s, id);
|
||||
@@ -1187,6 +1506,145 @@ fn looking_for_changed_points_after_each_command_is_charged() {
|
||||
assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_and_point_edits_keep_the_list_of_paths() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
for i in 0..50 {
|
||||
rect(&mut s, f64::from(i % 10) * 10.0, f64::from(i / 10) * 10.0, 5.0, 5.0);
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let start = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get());
|
||||
log(
|
||||
&mut s,
|
||||
"var ps = app.activeDocument.pathItems;\
|
||||
for (var i = 0; i < ps.length; i++) { var c = new RGBColor(); c.red = i; ps[i].fillColor = c; ps[i].strokeWidth = 2;\
|
||||
ps[i].fillOverprint = true; var q = ps[i].pathPoints[0]; q.anchor = [q.anchor[0] + 1, q.anchor[1]]; }",
|
||||
);
|
||||
let built = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get()) - start;
|
||||
assert_eq!(built, 1, "the paths are listed once for 50 paint and point edits");
|
||||
let out = log(&mut s, "var ps = app.activeDocument.pathItems; var n = ps.length; ps.rectangle(0, 0, 1, 1); vc.log([n, ps.length]);");
|
||||
assert_eq!(out, vec![json!([50, 51])], "a new path is listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_regenerates_shaper_art_lists_the_paths_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap();
|
||||
for x in [0.0, 50.0] {
|
||||
rect(&mut s, x, 50.0, 100.0, 100.0);
|
||||
}
|
||||
s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let sources = vectorcraft_doc::shaper::SOURCES;
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var ps = app.activeDocument.pathItems, n = ps.length, src = null;\
|
||||
for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src = ps[i];\
|
||||
var q = src.pathPoints[0]; q.anchor = [q.anchor[0] + 200, q.anchor[1]]; src.fillColor = new GrayColor(); vc.log(ps.length);"
|
||||
),
|
||||
);
|
||||
let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
|
||||
assert_eq!(out, fresh, "the list after the edit matches a fresh run's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_drops_a_shaper_path_lists_the_paths_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap();
|
||||
for x in [0.0, 50.0] {
|
||||
rect(&mut s, x, 50.0, 100.0, 100.0);
|
||||
}
|
||||
s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let sources = vectorcraft_doc::shaper::SOURCES;
|
||||
let before = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
|
||||
// The paths are listed again after the first edit. The second edit takes the generated fill
|
||||
// away, and a regeneration that makes no path makes no new id.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var ps = app.activeDocument.pathItems, n = ps.length, src = [];\
|
||||
for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src.push(ps[i]);\
|
||||
for (var i = 0; i < src.length; i++) {{ src[i].fillColor = new NoColor(); var m = ps.length; }} vc.log(ps.length);"
|
||||
),
|
||||
);
|
||||
let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
|
||||
assert_ne!(before, fresh, "the edit changes how many paths the document has");
|
||||
assert_eq!(out, fresh, "the list after the edit matches a fresh run's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_setting_on_an_empty_path_ends_once_a_command_gives_it_points() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
|
||||
vc.run('path.setAnchors', {{id: {}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\
|
||||
p.pathPoints.removeAll(); vc.log(p.closed);",
|
||||
id.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(false)], "the open points the command gave end the setting");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
|
||||
vc.run('path.setAnchors', {{id: {0}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\
|
||||
vc.run('path.setAnchors', {{id: {0}, subpaths: []}}); vc.log(p.closed);",
|
||||
id.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(false)], "clearing the points through a command does not restore the setting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_batch_ends_the_empty_path_closed_setting_even_when_it_removes_its_points() {
|
||||
for fail in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap();
|
||||
let failure = if fail { ", {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}" } else { "" };
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true; var failed = false;\
|
||||
try {{ vc.run('command.batch', {{commands: [\
|
||||
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\
|
||||
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: []}}}}{failure}]}}); }} catch (e) {{ failed = true; }}\
|
||||
vc.log(failed); vc.log(p.pathPoints.length); vc.log(p.closed);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(fail), json!(0), json!(fail)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_failed_dataset_row_keeps_the_empty_path_closed_setting() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
|
||||
var r = vc.run('action.batch', {{source: 'datasets', commands: [\
|
||||
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\
|
||||
{{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\
|
||||
vc.log(r.failed); vc.log(p.pathPoints.length); vc.log(p.closed);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!(0), json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_edits_are_written_before_the_next_other_member_reads() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -1788,6 +2246,39 @@ fn filled_and_stroked_true_give_the_new_art_paint() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern of a path with no anchors turns and scales about the origin, as a path without
|
||||
/// points takes any transformation; each call is one undo step.
|
||||
#[test]
|
||||
fn transforming_the_pattern_of_an_empty_path_turns_it() {
|
||||
for source in [
|
||||
"app.activeDocument.pathItems[0].rotate(90, true, true, true, true);",
|
||||
"app.activeDocument.pathItems[0].resize(50, 50, true, true, true, true);",
|
||||
"app.activeDocument.pathItems[0].resize(50, 50, false, true, false, true);",
|
||||
] {
|
||||
let (mut s, _) = doc_with_paints();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].fillColor.typename);"), vec![json!("PatternColor")]);
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
log(&mut s, source);
|
||||
assert_ne!(art(&s), before, "{source}: the pattern transforms");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "{source}: one undo step");
|
||||
}
|
||||
}
|
||||
|
||||
/// Scaling a path with no anchors with its stroke weights scales its own stroke weight.
|
||||
#[test]
|
||||
fn scaling_an_empty_path_with_line_widths_scales_its_stroke() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 10; n.strokeDashes = [3, 4];");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "app.activeDocument.pathItems[0].resize(200, 200, true, false, true, false, 200);");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(20)]);
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeDashes);"), vec![json!([6, 8])], "the dashes scale too");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() {
|
||||
let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) };
|
||||
@@ -1854,7 +2345,7 @@ fn bad_color_components_throw_and_change_nothing() {
|
||||
("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"),
|
||||
("app.activeDocument.pathItems[0].fillColor = 5;", "color object"),
|
||||
("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"),
|
||||
("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "not available yet"),
|
||||
("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"),
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
@@ -2305,6 +2796,23 @@ fn path_changes_refuse_paths_on_a_locked_artboard() {
|
||||
assert_ne!(art(&s), before);
|
||||
}
|
||||
|
||||
/// An empty path in a group on a locked artboard refuses `closed = true`, and keeps allowing an
|
||||
/// assignment of the value it has.
|
||||
#[test]
|
||||
fn closing_an_empty_path_refuses_one_on_a_locked_artboard() {
|
||||
let (mut s, a, _) = doc();
|
||||
let empty = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.group", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let pick = "var d = app.activeDocument, p; for (var i = 0; i < d.pathItems.length; i++) { if (d.pathItems[i].pathPoints.length == 0) p = d.pathItems[i]; }";
|
||||
log(&mut s, &format!("{pick} p.closed = false;"));
|
||||
let e = failure(&mut s, &format!("{pick} p.closed = true;"));
|
||||
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", empty.0)), "{e}");
|
||||
assert_eq!(log(&mut s, &format!("{pick} vc.log(p.closed);")), vec![json!(false)]);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
|
||||
assert_eq!(log(&mut s, &format!("{pick} p.closed = true; vc.log(p.closed);")), vec![json!(true)]);
|
||||
}
|
||||
|
||||
fn is_guide(s: &Session, id: NodeId) -> bool {
|
||||
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
@@ -2385,6 +2893,95 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() {
|
||||
assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command");
|
||||
}
|
||||
|
||||
/// Reading and moving each point of a path with many subpaths works out where the subpaths' points
|
||||
/// start a few times for the whole loop, not once or more for each point.
|
||||
#[test]
|
||||
fn reading_and_moving_points_counts_the_subpaths_a_few_times() {
|
||||
let (mut s, _, _) = doc();
|
||||
let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(0));
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var pp = app.activeDocument.pathItems[0].pathPoints;\
|
||||
for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\
|
||||
vc.log(pp.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1000)]);
|
||||
let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get);
|
||||
assert!(built < 10, "{built} layouts for 1000 points");
|
||||
let n = node(&s, id);
|
||||
let ys: Vec<f64> = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect();
|
||||
assert_eq!(ys.len(), 1000);
|
||||
assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up");
|
||||
}
|
||||
|
||||
/// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the
|
||||
/// order of `pathPoints`, whatever order they were selected in.
|
||||
#[test]
|
||||
fn selected_path_points_follow_the_order_of_path_points_across_subpaths() {
|
||||
let (mut s, _, _) = doc();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\
|
||||
for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([0, 10, 30])]);
|
||||
}
|
||||
|
||||
/// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a
|
||||
/// key that nothing has reads as `undefined`.
|
||||
#[test]
|
||||
fn collections_find_names_that_read_as_numbers() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\
|
||||
vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\
|
||||
vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]);
|
||||
}
|
||||
|
||||
/// `typename` of a point or a point list throws for one that is stale, as the other members do.
|
||||
#[test]
|
||||
fn stale_points_throw_on_typename() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\
|
||||
try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\
|
||||
var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\
|
||||
try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]);
|
||||
}
|
||||
|
||||
/// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose
|
||||
/// id a double rounds to.
|
||||
#[test]
|
||||
fn made_paths_keep_ids_past_two_to_the_53() {
|
||||
let (mut s, _, _) = doc();
|
||||
let big = 1u64 << 53;
|
||||
s.edit("Raise Ids", |d, _| {
|
||||
d.raise_next_id(big);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
assert_eq!(old.0, big);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';");
|
||||
assert_eq!(node(&s, old).name, None);
|
||||
assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made"));
|
||||
assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed"));
|
||||
}
|
||||
|
||||
/// A point change made before a call that fails and is put back, here a new document whose
|
||||
/// profile cannot be read, is kept.
|
||||
#[test]
|
||||
|
||||
@@ -104,6 +104,8 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
|
||||
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user