mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/dwg-listed-without-decoder
This commit is contained in:
commit
348b561d3c
128 files changed
+10626
-1055
No files matched your search
Generated
+93
-91
@@ -1255,7 +1255,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1297,7 +1297,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1318,7 +1318,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1330,7 +1330,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1338,7 +1338,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1363,7 +1363,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1381,7 +1381,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1399,7 +1399,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1408,7 +1408,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1416,7 +1416,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1425,12 +1425,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1450,7 +1450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
@@ -1466,7 +1466,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1476,7 +1476,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1484,7 +1484,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1510,7 +1510,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1526,7 +1526,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1534,7 +1534,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1553,7 +1553,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
@@ -1562,7 +1562,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1574,7 +1574,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1584,12 +1584,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
@@ -1599,7 +1599,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1614,7 +1614,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1633,7 +1633,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1642,7 +1642,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1665,12 +1665,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1678,7 +1678,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1686,7 +1686,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1699,7 +1699,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -1729,7 +1729,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1756,7 +1756,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1774,7 +1774,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1782,7 +1782,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1793,7 +1793,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1808,7 +1808,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1822,7 +1822,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1840,7 +1840,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1852,7 +1852,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1863,7 +1863,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1873,7 +1873,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1882,7 +1882,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1898,7 +1898,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-texture",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1907,7 +1907,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1918,7 +1918,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1930,7 +1930,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1963,7 +1963,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1972,7 +1972,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1996,7 +1996,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -2007,7 +2007,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -2021,7 +2021,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -2032,7 +2032,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -2045,7 +2045,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2054,7 +2054,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2073,7 +2073,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2090,7 +2090,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2101,7 +2101,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2122,7 +2122,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2134,7 +2134,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2159,7 +2159,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -2167,7 +2167,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2182,7 +2182,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2197,7 +2197,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2207,7 +2207,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2216,7 +2216,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2231,12 +2231,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2250,7 +2250,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2267,7 +2267,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2305,7 +2305,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2316,7 +2316,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2334,7 +2334,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2355,7 +2355,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2376,7 +2376,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2395,7 +2395,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2427,7 +2427,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2438,7 +2438,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2448,7 +2448,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2459,7 +2459,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2467,7 +2467,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2499,7 +2499,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -3859,7 +3859,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3868,7 +3868,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3886,7 +3886,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3904,12 +3904,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4892,7 +4892,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -5049,7 +5049,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -9271,6 +9271,8 @@ dependencies = [
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
"bytemuck",
|
||||
"chrono",
|
||||
"craft",
|
||||
|
||||
+41
-41
@@ -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 = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# 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 = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# 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 = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# 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 = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# 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 = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -200,13 +200,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 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 = "37d0532f42eb3421769c8a454e3e25a20fbcff97", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", 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");
|
||||
|
||||
@@ -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
|
||||
|
||||
+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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
@@ -144,6 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(artboard_guides::specs())
|
||||
.chain(marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -145,9 +155,15 @@ pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)
|
||||
visit(&mut font.family);
|
||||
}
|
||||
}
|
||||
// A live dimension makes its label again from its options.
|
||||
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_deref_mut()) {
|
||||
visit(&mut dimension.options.font_family);
|
||||
// A dimension redraws its label from its own options, so they follow the label's family.
|
||||
// A spelling that already names the same font, or one too long for the options, is kept.
|
||||
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);
|
||||
}
|
||||
@@ -170,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())
|
||||
@@ -189,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")));
|
||||
}
|
||||
@@ -230,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(),
|
||||
|
||||
@@ -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,
|
||||
@@ -183,7 +183,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_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer,
|
||||
plugin_formats, read_extensions, readable_format, readable_format_for_name, titled_for_export, writable_format,
|
||||
plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
|
||||
};
|
||||
pub(crate) use formats::{is_own_title, reads};
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -113,14 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
|
||||
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
|
||||
}
|
||||
|
||||
/// Formats VectorCraft opens but doesn't write, with what to export instead.
|
||||
const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")];
|
||||
/// 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 {
|
||||
|
||||
@@ -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",
|
||||
@@ -775,15 +803,15 @@ pub(crate) fn reads(f: &Format) -> bool {
|
||||
|
||||
/// Whether format `f` reads in a build that decodes DWG drawings when `dwg`.
|
||||
fn reads_in(f: &Format, dwg: bool) -> bool {
|
||||
f.read && (dwg || f.id != "dwg")
|
||||
f.read && (dwg || !reads_as_dwg(f.id))
|
||||
}
|
||||
|
||||
/// `exts` less `.dwg` in a build without a DWG decoder (`dwg` false).
|
||||
/// `exts` less `.dwg`, `.dws` and `.dwt` in a build without a DWG decoder (`dwg` false).
|
||||
fn listed_in(exts: &[&'static str], dwg: bool) -> Vec<&'static str> {
|
||||
exts.iter().copied().filter(|e| dwg || *e != "dwg").collect()
|
||||
exts.iter().copied().filter(|e| dwg || !matches!(*e, "dwg" | "dws" | "dwt")).collect()
|
||||
}
|
||||
|
||||
/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg` where
|
||||
/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg`, `.dws` and `.dwt` where
|
||||
/// no DWG decoder is built in ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn open_exts() -> &'static [&'static str] {
|
||||
static EXTS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| listed_in(OPEN_EXTS, vectorcraft_cad::dwg::DECODES));
|
||||
@@ -1192,13 +1220,16 @@ mod dwg_listing_tests {
|
||||
assert_eq!(listed_in(OPEN_EXTS, true), OPEN_EXTS);
|
||||
assert_eq!(listed_in(PLACE_EXTS, true), PLACE_EXTS);
|
||||
assert!(format_filters_in(true).any(|(_, exts)| exts.contains(&"dwg")));
|
||||
// Without a decoder, nothing offers DWG drawings.
|
||||
assert!(readable_format_in("dwg", false).is_none(), "DWG is not readable");
|
||||
// Without a decoder, nothing offers DWG drawings, standards files or templates.
|
||||
for e in ["dwg", "dws", "dwt"] {
|
||||
assert!(readable_format_in(e, false).is_none(), ".{e} is not readable");
|
||||
assert!(!listed_in(OPEN_EXTS, false).contains(&e), "File › Open does not list .{e}");
|
||||
assert!(!listed_in(PLACE_EXTS, false).contains(&e), "File › Place does not list .{e}");
|
||||
assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&e)), "no filter lists .{e}");
|
||||
}
|
||||
assert!(readable_format_in("dxf", false).is_some(), "DXF still is");
|
||||
assert!(!listed_in(OPEN_EXTS, false).contains(&"dwg"), "File › Open does not list .dwg");
|
||||
assert!(!listed_in(PLACE_EXTS, false).contains(&"dwg"), "File › Place does not list .dwg");
|
||||
assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - 1, "every other extension stays");
|
||||
assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&"dwg")), "no DWG filter");
|
||||
let drawing_exts = OPEN_EXTS.iter().filter(|e| matches!(**e, "dwg" | "dws" | "dwt")).count();
|
||||
assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - drawing_exts, "every other extension stays");
|
||||
// This build lists DWG exactly when it decodes it.
|
||||
let dwg = vectorcraft_cad::dwg::DECODES;
|
||||
assert_eq!(open_exts().contains(&"dwg"), dwg);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
@@ -1051,7 +1051,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 +1062,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}))
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -598,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;
|
||||
}
|
||||
|
||||
@@ -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 { .. })) {
|
||||
|
||||
@@ -360,7 +360,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() };
|
||||
@@ -383,7 +383,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.
|
||||
|
||||
@@ -545,16 +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], composites: bool) -> (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 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);
|
||||
@@ -585,18 +591,18 @@ fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (U
|
||||
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 composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty();
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes, composites);
|
||||
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.
|
||||
@@ -604,7 +610,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd:
|
||||
.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() && !undefined_clash { 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",
|
||||
|
||||
@@ -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]| {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+185
-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;
|
||||
@@ -119,17 +121,35 @@ 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);
|
||||
@@ -143,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.
|
||||
@@ -200,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>)>>,
|
||||
@@ -228,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.
|
||||
@@ -300,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();
|
||||
@@ -317,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>);
|
||||
@@ -624,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)?;
|
||||
@@ -692,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,
|
||||
}
|
||||
@@ -867,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| {
|
||||
@@ -1056,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`]).
|
||||
@@ -1167,8 +1224,14 @@ fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer {
|
||||
/// 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() }
|
||||
}
|
||||
|
||||
@@ -1622,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) {
|
||||
@@ -1643,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));
|
||||
@@ -2230,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)?;
|
||||
@@ -2239,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)?;
|
||||
@@ -2247,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]"));
|
||||
}
|
||||
@@ -2256,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)?;
|
||||
@@ -2269,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),
|
||||
}
|
||||
@@ -2304,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)?;
|
||||
@@ -2323,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) {
|
||||
@@ -2343,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)?;
|
||||
@@ -2675,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, .. }) {
|
||||
@@ -2686,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);
|
||||
@@ -2848,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| {
|
||||
@@ -2860,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()));
|
||||
@@ -3086,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.
|
||||
@@ -3289,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}]")))))
|
||||
}
|
||||
|
||||
@@ -3356,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);
|
||||
@@ -3368,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.
|
||||
@@ -3481,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));
|
||||
@@ -3640,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,14 +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. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
//! 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;
|
||||
|
||||
@@ -27,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.
|
||||
@@ -121,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
@@ -853,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() {
|
||||
@@ -893,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()));
|
||||
@@ -909,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 {
|
||||
@@ -977,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)
|
||||
@@ -987,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
|
||||
@@ -1040,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)
|
||||
}
|
||||
@@ -1052,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)
|
||||
}
|
||||
@@ -1127,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(),
|
||||
}
|
||||
}
|
||||
@@ -1196,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)> {
|
||||
@@ -1435,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))))
|
||||
}
|
||||
|
||||
@@ -1458,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),
|
||||
@@ -1543,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 {
|
||||
@@ -1601,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")),
|
||||
@@ -1617,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(
|
||||
@@ -1680,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,6 +170,12 @@ 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)]
|
||||
@@ -208,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);
|
||||
@@ -219,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)
|
||||
@@ -229,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() {
|
||||
@@ -267,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)
|
||||
{
|
||||
@@ -308,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))
|
||||
{
|
||||
@@ -374,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)
|
||||
@@ -390,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
|
||||
@@ -431,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)))
|
||||
@@ -441,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 {
|
||||
@@ -454,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)
|
||||
}
|
||||
|
||||
@@ -475,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,
|
||||
},
|
||||
@@ -532,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()))
|
||||
@@ -556,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),
|
||||
}
|
||||
@@ -572,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, .. })))
|
||||
@@ -625,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))
|
||||
{
|
||||
@@ -659,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(", ");
|
||||
@@ -669,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)
|
||||
}
|
||||
@@ -687,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 {
|
||||
@@ -701,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.
|
||||
@@ -745,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
|
||||
@@ -791,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")?);
|
||||
@@ -799,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")?);
|
||||
@@ -813,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.
|
||||
@@ -825,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()
|
||||
@@ -867,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 ----
|
||||
@@ -881,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)
|
||||
}
|
||||
|
||||
@@ -999,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<_, _>>()?;
|
||||
@@ -1069,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(())
|
||||
}
|
||||
|
||||
@@ -1132,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)
|
||||
}
|
||||
@@ -1146,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 };
|
||||
@@ -1174,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)
|
||||
}
|
||||
@@ -1372,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 ----
|
||||
@@ -1652,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);
|
||||
@@ -2125,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)),
|
||||
),
|
||||
@@ -2144,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,
|
||||
),
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -880,7 +880,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,8 @@ 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) };
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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];");
|
||||
@@ -1828,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}");
|
||||
@@ -1878,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();
|
||||
@@ -2023,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]
|
||||
@@ -2511,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() {
|
||||
@@ -2697,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);"));
|
||||
@@ -3021,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();
|
||||
@@ -3089,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> {
|
||||
@@ -3312,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();
|
||||
@@ -3353,6 +3678,18 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() {
|
||||
assert!(failure(&mut s, src).contains("only paths"), "{src}");
|
||||
}
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
// Caught inside the run, the refused move leaves the object where it was and the compound
|
||||
// path's members as they were.
|
||||
for (make, to) in
|
||||
[("d.groupItems.add()", "C"), ("d.groupItems.add()", "C.pathItems[0], ElementPlacement.PLACEBEFORE"), ("d.compoundPathItems.add()", "C")]
|
||||
{
|
||||
let src = format!(
|
||||
"var d = app.activeDocument, C = d.compoundPathItems.getByName('C'), o = {make};\
|
||||
try {{ o.move({to}); vc.log('moved'); }} catch (e) {{ vc.log(String(e).indexOf('only paths') >= 0); }}\
|
||||
vc.log(o.parent.typename); vc.log(C.pathItems.length); vc.log(C.pathItems[0].parent.typename);"
|
||||
);
|
||||
assert_eq!(log(&mut s, &src), [json!(true), json!("Layer"), json!(2), json!("CompoundPathItem")], "{src}");
|
||||
}
|
||||
assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false"));
|
||||
}
|
||||
|
||||
@@ -4143,6 +4480,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]
|
||||
@@ -4186,18 +4546,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();
|
||||
@@ -4343,6 +4724,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();
|
||||
@@ -4516,6 +4909,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]
|
||||
@@ -5005,7 +5412,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')]);",
|
||||
);
|
||||
|
||||
@@ -282,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();
|
||||
@@ -339,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();
|
||||
@@ -358,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();
|
||||
@@ -1025,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();
|
||||
@@ -1068,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);
|
||||
@@ -1191,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();
|
||||
@@ -1792,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) };
|
||||
@@ -1858,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}");
|
||||
@@ -2309,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, .. })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,842 @@
|
||||
//! The script object model's swatches, color groups, spots, symbols, graphic styles and brushes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt RGB document with one rectangle.
|
||||
fn doc() -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(s, a)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn swatch_names(s: &mut Session) -> Vec<String> {
|
||||
let l = s.execute("swatch.list", &json!({})).unwrap();
|
||||
l["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
/// The document's resources, to show that a failed call changed nothing.
|
||||
fn resources(s: &Session) -> String {
|
||||
let d = &s.active().unwrap().doc;
|
||||
format!("{:?}{:?}{:?}{:?}{:?}", *d.swatches, *d.swatch_groups, *d.graphic_styles, d.symbols, d.layers)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatches_are_live_and_keep_reserved_entries() {
|
||||
let (mut s, _) = doc();
|
||||
let names = swatch_names(&mut s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var w = app.activeDocument.swatches; vc.log(w.length); vc.log(w.typename); vc.log(w.parent.typename);\
|
||||
vc.log(w[0].name); vc.log(w[1].name); vc.log(w[1].typename); vc.log(w[w.length] === undefined);\
|
||||
vc.log(w.getByName('Black').color.typename); try { w.getSelected(); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(names.len()),
|
||||
json!("Swatches"),
|
||||
json!("Document"),
|
||||
json!(names[0]),
|
||||
json!("[Registration]"),
|
||||
json!("Swatch"),
|
||||
json!(true),
|
||||
json!("RGBColor"),
|
||||
json!("Swatches.getSelected is not available yet")
|
||||
]
|
||||
);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var w = app.activeDocument.swatches, n = w.add(); n.name = 'Script Ink';\
|
||||
var c = new RGBColor(); c.red = 10; c.green = 20; c.blue = 30; n.color = c;\
|
||||
vc.log(w.getByName('Script Ink').color.green); vc.log(n.name);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(20), json!("Script Ink")]);
|
||||
assert!(swatch_names(&mut s).contains(&"Script Ink".to_string()));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "app.activeDocument.swatches.removeAll();");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let left = swatch_names(&mut s);
|
||||
assert_eq!(left, vec![names[0].clone(), "[Registration]".to_string()]);
|
||||
for script in ["app.activeDocument.swatches[1].name = 'R';", "app.activeDocument.swatches[0].remove();"] {
|
||||
assert!(failure(&mut s, script).contains("is built in"), "{script}");
|
||||
}
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "app.activeDocument.swatches.removeAll();");
|
||||
assert_eq!(undo_steps(&s), steps, "a removeAll with nothing to remove records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatches_add_saves_a_gradient_fill_as_a_gradient() {
|
||||
let (mut s, _) = doc();
|
||||
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": ramp})).unwrap();
|
||||
let out = log(&mut s, "vc.log(app.activeDocument.swatches.add().color.typename);");
|
||||
assert_eq!(out, vec![json!("GradientColor")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_objects_go_stale_after_remove_and_follow_renames() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var w = app.activeDocument.swatches.getByName('Black'); w.name = 'Ink'; vc.log(w.name);\
|
||||
var again = app.activeDocument.swatches.getByName('Ink'); vc.log(again.name);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Ink"), json!("Ink")]);
|
||||
let cases = [
|
||||
("var w = app.activeDocument.swatches.getByName('Ink'); w.remove(); w.name;", "Stale Swatch"),
|
||||
("var w = app.activeDocument.swatches.getByName('White'); w.remove(); w.typename;", "Stale Swatch"),
|
||||
("var w = app.activeDocument.swatches.getByName('White'); vc.run('swatch.delete', {name: 'White'}); w.color;", "Stale Swatch"),
|
||||
(
|
||||
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('graphicStyle.rename', {name: g.name, to: 'X'}); g.name;",
|
||||
"Stale GraphicStyle",
|
||||
),
|
||||
("var w = app.activeDocument.swatches.getByName('Red'); w.remove(); app.activeDocument.swatches.add().name = 'Red'; w.name;", "Stale Swatch"),
|
||||
(
|
||||
"var w = app.activeDocument.swatches.getByName('Lime'); vc.run('swatch.delete', {name: 'Lime'}); vc.run('swatch.new', {name: 'Lime', color: '#00ff00'}); w.name;",
|
||||
"Stale Swatch",
|
||||
),
|
||||
(
|
||||
"var w = app.activeDocument.swatches.getByName('Yellow'); vc.run('command.batch', {commands: [\
|
||||
{command: 'swatch.delete', params: {name: 'Yellow'}}, {command: 'swatch.new', params: {name: 'Yellow', color: '#ffff00'}}]}); w.name;",
|
||||
"Stale Swatch",
|
||||
),
|
||||
(
|
||||
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('command.batch', {commands: [\
|
||||
{command: 'graphicStyle.rename', params: {name: g.name, to: 'X'}}, {command: 'graphicStyle.rename', params: {name: 'X', to: g.name}}]}); g.name;",
|
||||
"Stale GraphicStyle",
|
||||
),
|
||||
];
|
||||
for (script, message) in cases {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_object_goes_stale_when_a_batch_makes_its_swatch_process_and_back() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
|
||||
let toggle = "vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'Ink', spot: false}},\
|
||||
{command: 'swatch.edit', params: {name: 'Ink', spot: true}}]});";
|
||||
let e = failure(&mut s, &format!("var p = app.activeDocument.spots.getByName('Ink'); {toggle} p.name;"));
|
||||
assert!(e.contains("Stale Spot"), "{e}");
|
||||
let out = log(&mut s, &format!("var w = app.activeDocument.swatches.getByName('Ink'); {toggle} vc.log(w.name);"));
|
||||
assert_eq!(out, vec![json!("Ink")], "the swatch object stays live");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn action_steps_finalize_resource_removals_before_the_next_step() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
let actions = json!([{"set": "Set", "name": "Replace", "steps": [
|
||||
{"command": "action.batch", "params": {"source": "datasets", "commands": [
|
||||
{"command": "swatch.delete", "params": {"name": "Yellow"}},
|
||||
{"command": "swatch.new", "params": {"name": "Yellow", "color": "#ffff00"}}
|
||||
]}},
|
||||
{"command": "select.none"}
|
||||
]}]);
|
||||
let source = "var w = app.activeDocument.swatches.getByName('Yellow'); app.doScript('Replace', 'Set');\
|
||||
try { vc.log(w.name); } catch (e) { vc.log(e.message); }\
|
||||
vc.log(app.activeDocument.swatches.getByName('Yellow').name);";
|
||||
let r = s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})).unwrap();
|
||||
let out = r["log"].as_array().unwrap();
|
||||
assert!(out[0].as_str().unwrap().contains("Stale Swatch"), "{r}");
|
||||
assert_eq!(out[1], json!("Yellow"));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_failed_dataset_row_keeps_restored_resource_handles_live() {
|
||||
for change in ["{command: 'swatch.delete', params: {name: 'Yellow'}}", "{command: 'swatch.edit', params: {name: 'Yellow', newName: 'Ink'}}"] {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var w = app.activeDocument.swatches.getByName('Yellow');\
|
||||
var r = vc.run('action.batch', {{source: 'datasets', commands: [{change},\
|
||||
{{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\
|
||||
vc.log(r.failed); vc.log(w.name);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!("Yellow")], "{change}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_spots_is_charged_for_every_swatch_it_looks_at() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..300 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.length;";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("100 listings of 300 process swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_that_fails_is_charged_for_the_swatches_its_steps_compared() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var d = app.activeDocument, w = d.swatches.getByName('P0'); for (var i = 0; i < 30; i++) {\
|
||||
try { vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: i % 2 ? '#112233' : '#445566'}},\
|
||||
{command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]}); } catch (e) {} }";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("30 failed batches over 1000 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
let source = "var w = app.activeDocument.swatches.getByName('P0');\
|
||||
vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: '#112233'}},\
|
||||
{command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]});";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("a failed batch over 1000 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "the scan budget error takes precedence over the missing swatch: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_artwork_symbol_class_leaves_the_built_in_symbol() {
|
||||
let (mut s, _) = doc();
|
||||
// A `.js` file runs as ECMAScript 2015, which has the built-in `Symbol`.
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-symbol-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("t.js");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"var d = app.activeDocument, m = d.symbols.add(d.pathItems[0]);\
|
||||
vc.log(typeof Symbol()); vc.log(typeof Symbol.iterator); vc.log(m.typename); vc.log(d.symbols.getByName(m.name).typename);",
|
||||
)
|
||||
.unwrap();
|
||||
let r = s.execute("script.run", &json!({"path": path.to_string_lossy()}));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(r.unwrap()["log"], json!(["symbol", "symbol", "Symbol", "Symbol"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_and_values_are_refused_without_change() {
|
||||
let (mut s, _) = doc();
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let long = "x".repeat(1025);
|
||||
let cases = [
|
||||
("app.activeDocument.swatches.getByName('Black').name = 'a\\u0007b';".to_string(), "control characters"),
|
||||
("app.activeDocument.swatches.getByName('Black').name = ' ';".to_string(), "cannot be empty"),
|
||||
(format!("app.activeDocument.swatches.getByName('Black').name = '{long}';"), "longer than 1024 bytes"),
|
||||
("app.activeDocument.swatches.getByName('Black').name = 7;".to_string(), "must be a string"),
|
||||
("app.activeDocument.swatches.getByName('Black').name = 'White';".to_string(), "already exists"),
|
||||
("var d = app.activeDocument, p = d.spots.add(); p.name = 'Black';".to_string(), "a swatch or color group named Black already exists"),
|
||||
(
|
||||
"var d = app.activeDocument; d.swatchGroups.add().name = 'Mine'; d.swatches.getByName('White').name = 'Mine';".to_string(),
|
||||
"a swatch or color group named Mine already exists",
|
||||
),
|
||||
("app.activeDocument.swatches.getByName('Black').color = new NoColor();".to_string(), "cannot be NoColor"),
|
||||
("app.activeDocument.swatches.getByName('Black').color = {typename: 'RGBColor', red: 300};".to_string(), "from 0 to 255"),
|
||||
("app.activeDocument.swatches.getByName('nope');".to_string(), "Not found"),
|
||||
("app.activeDocument.swatches.index({});".to_string(), "name or an index"),
|
||||
("app.activeDocument.symbols.add(app.activeDocument);".to_string(), "not a page item"),
|
||||
("app.activeDocument.symbols.add(app.activeDocument.pageItems[0], 'SymbolRegistrationPoint.NOPE');".to_string(), "SymbolRegistrationPoint"),
|
||||
("app.activeDocument.symbolItems.add(app.activeDocument.swatches[2]);".to_string(), "not a Symbol"),
|
||||
("app.activeDocument.graphicStyles[0].applyTo([app.activeDocument.pageItems[0]]);".to_string(), "one page item"),
|
||||
];
|
||||
for (script, message) in &cases {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_keep_their_kind_and_their_color_space() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.spots.add(); p.name = 'Pea'; p.colorType = ColorModel.SPOT;\
|
||||
var c = new RGBColor(); c.red = 90; c.green = 200; c.blue = 30; p.color = c;\
|
||||
vc.log(d.spots.length); vc.log(p.typename); vc.log(p.colorType); vc.log(p.spotKind); vc.log(p.getInternalColor());\
|
||||
var w = d.swatches.getByName('Pea').color; vc.log(w.typename); vc.log(w.spot.name); vc.log(w.tint);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(2),
|
||||
json!("Spot"),
|
||||
json!("ColorModel.SPOT"),
|
||||
json!("SpotColorKind.SPOTRGB"),
|
||||
json!([90, 200, 30]),
|
||||
json!("SpotColor"),
|
||||
json!("Pea"),
|
||||
json!(100)
|
||||
]
|
||||
);
|
||||
let before = resources(&s);
|
||||
for (script, message) in [
|
||||
("var p = app.activeDocument.spots.getByName('Pea'); p.color = new GrayColor();", "must be an RGBColor, a CMYKColor or a LabColor"),
|
||||
("app.activeDocument.spots.getByName('Pea').colorType = ColorModel.PROCESS;", "stays a spot color"),
|
||||
("app.activeDocument.spots.getByName('Pea').colorType = 3;", "ColorModel value"),
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); var l = new LabColor(); l.l = 50; p.color = l;");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.getByName('Pea').spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]);
|
||||
log(&mut s, "app.activeDocument.spots.removeAll();");
|
||||
assert!(!swatch_names(&mut s).contains(&"Pea".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_takes_a_cmyk_color_in_an_rgb_document() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.spots.add(); p.name = 'Pea'; var c = new CMYKColor(); c.cyan = 35; c.yellow = 50; p.color = c;\
|
||||
var q = app.activeDocument.spots.getByName('Pea'); vc.log(q.color.typename); vc.log([q.color.cyan, q.color.yellow]); vc.log(q.spotKind);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("CMYKColor"), json!([35, 50]), json!("SpotColorKind.SPOTCMYK")]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let cmyk =
|
||||
matches!(d.swatch("Pea").map(|w| &w.paint), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. }));
|
||||
assert!(cmyk, "the spot keeps its CMYK color in the RGB document");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); p.color = p.color;");
|
||||
assert_eq!(undo_steps(&s), steps, "assigning the color the spot has records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_keeps_an_rgb_color_in_a_cmyk_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 80, "m": 40, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": {"c": 60, "m": 0, "y": 90, "k": 10}})).unwrap();
|
||||
let rgb = |s: &Session, name: &str| {
|
||||
matches!(
|
||||
s.active().unwrap().doc.swatch(name).map(|w| &w.paint),
|
||||
Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. })
|
||||
)
|
||||
};
|
||||
let assign = |what: &str| format!("var c = new RGBColor(); c.red = 200; c.green = 60; c.blue = 20; {what}.color = c;");
|
||||
for (what, name) in [("app.activeDocument.spots.getByName('Pea')", "Pea"), ("app.activeDocument.swatches.getByName('Ink')", "Ink")] {
|
||||
if name == "Pea" {
|
||||
log(&mut s, "app.activeDocument.spots.add().name = 'Pea';");
|
||||
}
|
||||
let out = log(&mut s, &format!("{} var q = app.activeDocument.spots.getByName('{name}').color; vc.log([q.typename, q.red]);", assign(what)));
|
||||
assert_eq!(out, vec![json!(["RGBColor", 200])], "{what}");
|
||||
assert!(rgb(&s, name), "{name} keeps its RGB color in the CMYK document");
|
||||
let kind = log(&mut s, &format!("vc.log(app.activeDocument.spots.getByName('{name}').spotKind);"));
|
||||
assert_eq!(kind, vec![json!("SpotColorKind.SPOTRGB")], "{name}");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &assign(what));
|
||||
assert_eq!(undo_steps(&s), steps, "assigning {name} the color it has records no step");
|
||||
}
|
||||
let what = "app.activeDocument.swatches.getByName('Leaf')";
|
||||
let paint = |s: &Session| s.active().unwrap().doc.swatch("Leaf").map(|w| w.paint.clone());
|
||||
let before = paint(&s);
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &assign(what));
|
||||
assert!(!rgb(&s, "Leaf"), "a process swatch stores the RGB color as CMYK in the CMYK document");
|
||||
assert_ne!(paint(&s), before, "the first assignment changes Leaf");
|
||||
assert!(
|
||||
matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. })),
|
||||
"Leaf holds a CMYK color"
|
||||
);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the first assignment records one step");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &assign(what));
|
||||
assert_eq!(undo_steps(&s), steps, "assigning Leaf the RGB color it was given records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_swatch_that_kept_an_rgb_color_takes_it_back_without_a_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Sky", "color": "#3080c0", "keepModel": true})).unwrap();
|
||||
let paint = |s: &Session| s.active().unwrap().doc.swatch("Sky").map(|w| w.paint.clone());
|
||||
let rgb = matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }));
|
||||
assert!(rgb, "the process swatch holds an RGB color in the CMYK document");
|
||||
let before = paint(&s);
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var w = app.activeDocument.swatches.getByName('Sky'); w.color = w.color;");
|
||||
assert_eq!(paint(&s), before, "the swatch keeps its RGB color");
|
||||
assert_eq!(undo_steps(&s), steps, "assigning the swatch its own color records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_list_registration_and_keep_it() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, r = d.spots.getByName('[Registration]'); vc.log(r.typename); vc.log(r.colorType);\
|
||||
vc.log(d.spots[0].name); vc.log(d.spots.length); r.colorType = ColorModel.REGISTRATION;\
|
||||
vc.log(d.swatches.getByName('[Registration]').color.spot.name);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Spot"), json!("ColorModel.REGISTRATION"), json!("[Registration]"), json!(1), json!("[Registration]")]);
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
for script in [
|
||||
"app.activeDocument.spots.getByName('[Registration]').name = 'R';",
|
||||
"app.activeDocument.spots.getByName('[Registration]').remove();",
|
||||
"app.activeDocument.spots.getByName('[Registration]').color = new CMYKColor();",
|
||||
"app.activeDocument.spots.getByName('[Registration]').colorType = ColorModel.SPOT;",
|
||||
] {
|
||||
assert!(failure(&mut s, script).contains("is built in"), "{script}");
|
||||
}
|
||||
log(&mut s, "app.activeDocument.spots.removeAll();");
|
||||
assert_eq!(resources(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps, "removeAll with only Registration left records no step");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.length);"), vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_of_a_spot_reads_as_that_spot_at_the_tint() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
let tint = s.execute("swatch.new", &json!({"tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("var c = app.activeDocument.swatches.getByName('{tint}').color; vc.log(c.typename); vc.log(c.spot.name); vc.log(c.tint);"),
|
||||
);
|
||||
assert_eq!(out, vec![json!("SpotColor"), json!("Ink"), json!(40)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_add_converts_the_fill_to_the_document_color_space() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000", "keepModel": true})).unwrap();
|
||||
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
|
||||
assert!(rgb, "the current fill is RGB in a CMYK document");
|
||||
let out = log(&mut s, "var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename);");
|
||||
assert_eq!(out, vec![json!("SpotColorKind.SPOTCMYK"), json!("CMYKColor")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_add_converts_a_cmyk_or_gray_fill_in_an_rgb_document() {
|
||||
for fill in [json!({"c": 0, "m": 100, "y": 100, "k": 0}), json!({"gray": 40})] {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("paint.setFill", &json!({"color": fill})).unwrap();
|
||||
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
|
||||
assert!(!rgb, "the current fill {fill} is not RGB in an RGB document");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename); p.color = p.color; vc.log(p.name == '');",
|
||||
);
|
||||
assert_eq!(out, vec![json!("SpotColorKind.SPOTRGB"), json!("RGBColor"), json!(false)], "{fill}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_groups_hold_solid_swatches_only() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute(
|
||||
"swatch.new",
|
||||
&json!({"name": "Ramp", "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.swatchGroups.add(); g.name = 'Script Group';\
|
||||
g.addSwatch(d.swatches.getByName('Black')); g.addSwatch(d.swatches.getByName('Black'));\
|
||||
var all = g.getAllSwatches(); vc.log(all.length); vc.log(all[0].name); vc.log(d.swatchGroups.getByName('Script Group').typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!("Black"), json!("SwatchGroup")]);
|
||||
let before = resources(&s);
|
||||
for (script, message) in [
|
||||
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches.getByName('Ramp'));", "solid colors only"),
|
||||
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches[0]);", "is built in"),
|
||||
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSpot(d.swatches.getByName('Black'));", "not a Spot"),
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.swatchGroups.getByName('Script Group'), b = g.getAllSwatches()[0];\
|
||||
g.removeAll(); vc.log(g.getAllSwatches().length); try { b.name; } catch (e) { vc.log(String(e.message)); }\
|
||||
g.remove(); try { g.name; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(0), json!("Stale Swatch"), json!("Stale SwatchGroup")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_add_keeps_the_source_and_instances_follow_their_symbol() {
|
||||
let (mut s, a) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, n = d.pageItems.length, sym = d.symbols.add(d.pageItems[0], SymbolRegistrationPoint.SYMBOLTOPLEFTPOINT);\
|
||||
vc.log(d.pageItems.length === n); vc.log(sym.typename); vc.log(d.symbols.length);\
|
||||
sym.name = 'Mark'; var copy = sym.duplicate(); vc.log(copy.name);\
|
||||
var inst = d.symbolItems.add(sym); vc.log(inst.typename); vc.log(inst.symbol.name); vc.log(d.symbolItems.length);\
|
||||
inst.symbol = copy; vc.log(inst.symbol.name); vc.log(d.selection.length === 0);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(true),
|
||||
json!("Symbol"),
|
||||
json!(1),
|
||||
json!("Mark copy"),
|
||||
json!("SymbolItem"),
|
||||
json!("Mark"),
|
||||
json!(1),
|
||||
json!("Mark copy"),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
assert!(s.active().unwrap().doc.node(a).is_some(), "the source art stays");
|
||||
let l = s.execute("symbol.list", &json!({})).unwrap();
|
||||
assert_eq!(l["symbols"][0]["registration"], json!(0));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var d = app.activeDocument; d.symbolItems.removeAll(); vc.log(d.symbols.length);");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, sym = d.symbols[0]; d.symbols.removeAll(); vc.log(d.symbols.length); try { sym.name; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(0), json!("Stale Symbol")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resources_refuse_objects_of_another_document() {
|
||||
let (mut s, _) = doc();
|
||||
log(&mut s, "var d = app.activeDocument; d.symbols.add(d.pageItems[0]);");
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let before = resources(&s);
|
||||
// `app.documents` lists the active document, the new one, first: the document with the symbol
|
||||
// is `documents[1]`.
|
||||
for script in [
|
||||
"var a = app.documents[1], b = app.documents[0]; b.symbolItems.add(a.symbols[0]);",
|
||||
"var a = app.documents[1], b = app.documents[0]; a.graphicStyles[0].applyTo(b.pageItems[0]);",
|
||||
"var a = app.documents[1], b = app.documents[0]; b.swatchGroups.add().addSwatch(a.swatches.getByName('Black'));",
|
||||
"var a = app.documents[1], b = app.documents[0]; a.symbols.add(b.pageItems[0]);",
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains("Cross-document"), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphic_styles_apply_replaces_and_merge_adds() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Red"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.graphicStyles.getByName('Red'); vc.log(g.typename); vc.log(d.graphicStyles.typename);\
|
||||
g.applyTo(d.pageItems[0]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("GraphicStyle"), json!("GraphicStyles")]);
|
||||
let id = s.active().unwrap().doc.graphic_style("Red").unwrap().id;
|
||||
let n = s.active().unwrap().doc.node(b).unwrap().clone();
|
||||
assert_eq!(n.extras().graphic_style, Some(id));
|
||||
let fills = n.appearance.items.len();
|
||||
log(&mut s, "var d = app.activeDocument; d.graphicStyles.getByName('Red').mergeTo(d.pageItems[0]);");
|
||||
let n = s.active().unwrap().doc.node(b).unwrap().clone();
|
||||
assert!(n.appearance.items.len() > fills, "merge adds the style's rows");
|
||||
assert_eq!(n.extras().graphic_style, None);
|
||||
let before = resources(&s);
|
||||
for script in [
|
||||
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').name = 'Plain';",
|
||||
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').remove();",
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains("is built in"), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
log(&mut s, "app.activeDocument.graphicStyles.removeAll();");
|
||||
let left: Vec<String> = s.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect();
|
||||
assert_eq!(left, vec![crate::doc::DEFAULT_GRAPHIC_STYLE.to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_apply_to_paths_only_and_once() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let first = s.execute("brush.list", &json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var b = app.activeDocument.brushes; vc.log(b.typename); vc.log(b[0].typename); vc.log(b[0].name); vc.log(b.removeAll === undefined);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Brushes"), json!("Brush"), json!(first), json!(true)]);
|
||||
let before = resources(&s);
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pageItems[0]);");
|
||||
assert!(e.contains("PathItem only"), "{e}");
|
||||
assert_eq!(resources(&s), before);
|
||||
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
|
||||
let st = s.active().unwrap().doc.node(a).unwrap().appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.brush.as_deref(), Some(first.as_str()));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
|
||||
assert_eq!(undo_steps(&s), steps, "applying the brush a path already draws runs no command");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_refuse_guides_clipping_paths_and_compound_members() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
let (m1, m2) = (rect(&mut s, 100.0, 20.0, 30.0, 40.0), rect(&mut s, 150.0, 20.0, 30.0, 40.0));
|
||||
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let (c1, c2) = (rect(&mut s, 200.0, 20.0, 30.0, 40.0), rect(&mut s, 210.0, 30.0, 10.0, 10.0));
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let pick = |test: &str| {
|
||||
format!(
|
||||
"var d = app.activeDocument, p = null; for (var i = 0; i < d.pathItems.length; i++) {{ var q = d.pathItems[i]; if ({test}) p = q; }}\
|
||||
d.brushes[0].applyTo(p);"
|
||||
)
|
||||
};
|
||||
for test in ["q.guides", "q.clipping", "q.parent.typename == 'CompoundPathItem'"] {
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, &pick(test));
|
||||
assert!(e.contains("does not apply to a guide"), "{test}: {e}");
|
||||
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "{test}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_resource_edits_are_one_undo_step_and_a_failure_puts_them_back() {
|
||||
let (mut s, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'One'; d.spots.add().name = 'Two'; d.swatchGroups.add().name = 'Three';");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let before = resources(&s);
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'Four'; d.swatches.removeAll(); throw new Error('stop');");
|
||||
assert!(e.contains("stop"), "{e}");
|
||||
assert_eq!(resources(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_that_undo_removed_stays_stale_when_a_new_swatch_takes_its_name() {
|
||||
for make in ["vc.run('swatch.new', {name: n, color: '#ff0000'}); vc.log(true);", "vc.log(d.swatches.add().name == n);"] {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var d = app.activeDocument, k = d.swatches.length, w = d.swatches.add(), n = w.name; app.undo();\
|
||||
vc.log(d.swatches.length == k); {make}\
|
||||
try {{ vc.log(w.name); }} catch (e) {{ vc.log(e.message); }}"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[..2], [json!(true), json!(true)], "{make}: undo removes the swatch, and the new one takes its name");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{make}: {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_objects_made_before_a_revert_are_stale() {
|
||||
let (mut s, _) = doc();
|
||||
let path = std::env::temp_dir().join(format!("vc-resources-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, w = d.swatches.getByName('Black');\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
try { vc.log(w.name); } catch (e) { vc.log(e.message); }\
|
||||
var again = app.activeDocument.swatches.getByName('Black'); vc.log(again.name); vc.log(again === w);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{out:?}");
|
||||
assert_eq!(out[1..], [json!("Black"), json!(false)], "a swatch object made after the revert names the reverted swatch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_refuse_paths_in_a_compound_shape_at_any_depth() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
|
||||
let (m1, m2, m3) = (rect(&mut s, 10.0, 20.0, 30.0, 40.0), rect(&mut s, 30.0, 30.0, 30.0, 40.0), rect(&mut s, 50.0, 40.0, 30.0, 40.0));
|
||||
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g, m3.0]})).unwrap();
|
||||
s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, n = d.pathItems.length, e = [];\
|
||||
for (var i = 0; i < n; i++) { try { d.brushes[0].applyTo(d.pathItems[i]); e.push('applied'); }\
|
||||
catch (x) { e.push(x.message.indexOf('compound shape') >= 0); } }\
|
||||
vc.log(n); vc.log(e);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(3), json!([true, true, true])], "the grouped members and the direct member are refused");
|
||||
assert_eq!((resources(&s), undo_steps(&s)), (before, steps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_every_swatch_by_index_lists_the_swatches_once() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source =
|
||||
"var w = app.activeDocument.swatches, n = w.length, read = 0; for (var i = 0; i < n; i++) if (w[i]) read++; vc.log(read == n && n > 1000);";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap_or_else(|e| panic!("reading 1000 swatches by index: {e}"));
|
||||
assert_eq!(r["log"], json!([true]));
|
||||
let source = "var w = app.activeDocument.swatches, n = w.length; for (var i = 0; i < n; i++) { w[i]; app.activeDocument.swatches.add(); }";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("reading after each change listed the swatches once: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "a read after a change lists the swatches again and is charged: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_all_is_charged_for_the_records_it_looks_at() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.removeAll();";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("100 removeAll() calls over 1000 process swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
let colors: Vec<String> = (0..500).map(|i| format!("#{:06x}", i * 31)).collect();
|
||||
s.execute("swatch.newGroup", &json!({"name": "Many", "colors": colors})).unwrap();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000)));
|
||||
let r = run(&mut s, "app.activeDocument.swatchGroups.removeAll();");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("removing a group of 500 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "the group's swatches are charged: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_resource_past_the_object_limit_is_not_kept() {
|
||||
let (mut s, a) = doc();
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1)));
|
||||
let out = run(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], k = d.swatches[0], out = [];\
|
||||
var calls = [function () { d.swatches.add(); }, function () { d.spots.add(); }, function () { d.swatchGroups.add(); },\
|
||||
function () { d.symbols.add(p); }];\
|
||||
for (var i = 0; i < calls.length; i++) { try { calls[i](); out.push('made'); } catch (e) { out.push(e.message.indexOf('at most 1 ') >= 0); } }\
|
||||
vc.log(out);",
|
||||
);
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(None));
|
||||
assert_eq!(out.unwrap()["log"], json!([[true, true, true, true]]));
|
||||
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "no new resource is kept");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1)));
|
||||
let out = run(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, m = d.symbols.getByName('Mark');\
|
||||
try { m.duplicate(); vc.log('made'); } catch (e) { vc.log(e.message.indexOf('at most 1 ') >= 0); } vc.log(d.symbols.length);",
|
||||
);
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(None));
|
||||
assert_eq!(out.unwrap()["log"], json!([true, 1]), "the duplicate is not kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_symbol_instance_with_a_large_id_keeps_its_id() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).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 d = app.activeDocument, i = d.symbolItems.add(d.symbols.getByName('Mark')); i.name = 'big'; vc.log(i.name);");
|
||||
assert_eq!(out, vec![json!("big")]);
|
||||
assert_eq!(s.active().unwrap().doc.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_swatch_colors_is_charged_for_the_swatches_each_change_compares() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var w = app.activeDocument.swatches.getByName('P0'), a = new RGBColor(), b = new RGBColor(); b.red = 200;\
|
||||
for (var i = 0; i < 30; i++) w.color = i % 2 ? a : b;";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("30 swatch color edits over 1000 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_color_converts_through_the_profiles_of_its_own_document() {
|
||||
use vectorcraft_color::{Color, cms};
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("edit.assignProfile", &json!({"cmyk": cms::FOGRA51_CMYK})).unwrap();
|
||||
let rgb = Color::rgb(51.0 / 255.0, 128.0 / 255.0, 204.0 / 255.0);
|
||||
let own = {
|
||||
let c = crate::cmd::colormgmt::doc_cms(&s.active().unwrap().doc);
|
||||
c.convert(&rgb, cms::Model::Cmyk, c.settings().intent)
|
||||
};
|
||||
let working = {
|
||||
let c = cms::working();
|
||||
c.convert(&rgb, cms::Model::Cmyk, c.settings().intent)
|
||||
};
|
||||
assert_ne!(own, working, "the assigned profile converts the color differently");
|
||||
s.execute("swatch.new", &json!({"name": "Sky", "color": serde_json::to_value(working).unwrap()})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
log(
|
||||
&mut s,
|
||||
"var w = null; for (var i = 0; i < app.documents.length; i++) { try { w = app.documents[i].swatches.getByName('Sky'); } catch (e) {} }\
|
||||
var c = new RGBColor(); c.red = 51; c.green = 128; c.blue = 204; w.color = c;",
|
||||
);
|
||||
let sky = s.documents().iter().find_map(|st| st.doc.swatch("Sky").map(|w| w.paint.clone()));
|
||||
let Some(vectorcraft_color::Paint::Solid { color, .. }) = sky else { panic!("Sky is a solid color: {sky:?}") };
|
||||
assert_ne!(color, working, "the swatch takes the color its own document's profile gives");
|
||||
assert_eq!(color, own);
|
||||
}
|
||||
@@ -1164,6 +1164,28 @@ fn the_source_image_cannot_leave_its_tracing() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A tracing's shown source image cannot be removed, which would leave the tracing without it, and
|
||||
/// the refused remove leaves the document as it was.
|
||||
#[test]
|
||||
fn a_shown_source_image_cannot_be_removed() {
|
||||
let base = folder("source-removed");
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;");
|
||||
let saved = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, p = d.pageItems[0], m = 'none';\
|
||||
try { p.tracing.sourceArt.remove(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(p.isTracing);",
|
||||
);
|
||||
assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]);
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_source_art_is_not_listed_with_the_images() {
|
||||
let base = folder("lists");
|
||||
@@ -1504,3 +1526,28 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() {
|
||||
assert_eq!(out, vec![json!(true); 5]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_the_same_preset_in_bracket_form_does_not_trace_again() {
|
||||
let base = folder("retrace-bracket-preset");
|
||||
// Silhouettes then [Default] leaves the tracing with the stored name `[Default]`.
|
||||
for (first, second) in [("Default", "[Default]"), ("Silhouettes', '[Default]", "Default"), ("Silhouettes", "[silhouettes]")] {
|
||||
let (mut s, _) = session(&base, false);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var o = app.activeDocument.rasterItems[0].trace().tracing.tracingOptions, names = ['{first}'];\
|
||||
for (var i = 0; i < names.length; i++) o.loadFromPreset(names[i]); vc.log(o.preset);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!(first.rsplit('\'').next().unwrap())], "{first}");
|
||||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, &base, &format!("vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('{second}'));"));
|
||||
assert_eq!(out, [json!(true)], "{first} then {second}");
|
||||
assert!(vectorcraft_format::save(&s.active().unwrap().doc, false) == before, "{first} then {second}: the document changed");
|
||||
assert_eq!(undo_steps(&s), steps, "{first} then {second}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -1493,6 +1493,93 @@ fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() {
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
/// A script that ends past the allowance the person's last answer gave is asked again before its
|
||||
/// changes are kept.
|
||||
#[test]
|
||||
fn a_finished_run_past_its_last_allowance_asks_again() {
|
||||
let draw = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('shape.rectangle', {x:2,y:1,width:1,height:1});";
|
||||
let point = "var P = app.activeDocument.pathItems, q = P[0];\
|
||||
for (var k = 1; k < P.length; k++) if (P[k].pathPoints.length > q.pathPoints.length) q = P[k];\
|
||||
var p = q.pathPoints; for (var i = 0; i < p.length; i++) p[i].anchor = [i * 3, -4 - i];";
|
||||
// The path the script moves has 600 anchors, so its point changes weigh more than the
|
||||
// rectangles do.
|
||||
let two_docs = || {
|
||||
let mut s = two_docs();
|
||||
let id = s.documents()[1].doc.layers[0].children().unwrap()[0].id;
|
||||
let anchors: Vec<Value> = (0..600)
|
||||
.map(|i| json!({"x": f64::from(i), "y": f64::from(i % 7), "in": [f64::from(i), 0.0], "out": [f64::from(i), 0.0], "smooth": false}))
|
||||
.collect();
|
||||
s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap();
|
||||
s
|
||||
};
|
||||
let added = |source: &str| {
|
||||
let mut s = two_docs();
|
||||
let start = s.documents()[1].doc.clone();
|
||||
assert_eq!(run(&mut s, source).unwrap()["ok"], true);
|
||||
start.retained_bytes_each(&s.documents()[1].doc).1 as u64
|
||||
};
|
||||
let whole = format!("{draw} {point}");
|
||||
let (m, p) = (added(draw), added(&whole) - added(draw));
|
||||
// The rectangles go past one object, which asks once, and stay within twice the bytes; the
|
||||
// point changes, written as the script ends, then go past the second allowance and also past
|
||||
// the third.
|
||||
let b = (m + p - 1) / 3;
|
||||
assert!(m <= 2 * b && 3 * b < m + p && m + p <= 4 * b, "m {m}, p {p}, b {b}");
|
||||
TEST_GROWTH.with(|g| g.set(Some(1)));
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(Some(b)));
|
||||
let mut s = two_docs();
|
||||
s.script_frames = true;
|
||||
run(&mut s, &whole).unwrap();
|
||||
let mut questions = 0;
|
||||
let done = loop {
|
||||
assert!(questions < 10);
|
||||
if s.script_waiting() {
|
||||
questions += 1;
|
||||
s.script_continue();
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
break r;
|
||||
}
|
||||
};
|
||||
TEST_GROWTH.with(|g| g.set(None));
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(None));
|
||||
assert_eq!(done.unwrap()["ok"], true);
|
||||
assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance");
|
||||
}
|
||||
|
||||
/// A script that ends with nothing left to write, past the allowance the person's last answer
|
||||
/// gave, is asked again before its changes are kept.
|
||||
#[test]
|
||||
fn a_run_that_ends_past_its_last_allowance_with_nothing_to_write_asks_again() {
|
||||
TEST_GROWTH.with(|g| g.set(Some(20)));
|
||||
// 21 rectangles go past the first allowance, and the 45 the document opens go past the
|
||||
// second and stay within twice it, which leaves them past the third.
|
||||
let rects: String = (0..45).map(|i| format!(r#"<rect x="{i}" y="0" width="1" height="1"/>"#)).collect();
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">{rects}</svg>"#);
|
||||
let data = vectorcraft_format::base64_encode(svg.as_bytes());
|
||||
let source = format!(
|
||||
"for (var i = 0; i < 21; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\
|
||||
vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}});"
|
||||
);
|
||||
let mut s = two_docs();
|
||||
s.script_frames = true;
|
||||
run(&mut s, &source).unwrap();
|
||||
let mut questions = 0;
|
||||
let done = loop {
|
||||
assert!(questions < 10);
|
||||
if s.script_waiting() {
|
||||
questions += 1;
|
||||
s.script_continue();
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
break r;
|
||||
}
|
||||
};
|
||||
TEST_GROWTH.with(|g| g.set(None));
|
||||
assert_eq!(done.unwrap()["ok"], true);
|
||||
assert_eq!(questions, 3, "asked for the rectangles, for the document, and again as the script ended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
|
||||
TEST_GROWTH.with(|g| g.set(Some(20)));
|
||||
|
||||
@@ -10,6 +10,34 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn file_wrappers_report_encoder_warnings_without_changing_their_return_values() {
|
||||
for method in ["exportFile", "saveAs", "exportForScreens"] {
|
||||
let base = folder(&format!("encoder-warnings-{method}"));
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 80, "height": 40})).unwrap();
|
||||
crate::tests_menucmds::place_undecodable_png(&mut s);
|
||||
let format = if method == "saveAs" { "pdf" } else { "png" };
|
||||
let expected = s.execute("document.export", &json!({"format": format})).unwrap()["warnings"].clone();
|
||||
let warnings = expected.as_array().unwrap();
|
||||
assert!(!warnings.is_empty(), "the fixture must produce an encoder warning");
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = quoted(&dir.join("output.png"));
|
||||
let call = match method {
|
||||
"exportFile" => format!("d.exportFile(new File({path}), ExportType.PNG24)"),
|
||||
"saveAs" => format!("d.saveAs(new File({}))", quoted(&dir.join("output.pdf"))),
|
||||
_ => format!("d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG24)", quoted(&dir.join("screens"))),
|
||||
};
|
||||
let report =
|
||||
run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument; var answer = {call}; vc.log(answer === undefined);")).unwrap();
|
||||
assert_eq!(report["log"], json!([true]), "{method}: {report}");
|
||||
let lines = report["console"]["lines"].as_array().unwrap();
|
||||
for warning in warnings.iter().filter_map(Value::as_str) {
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|line| line.contains(warning)), "{method}: {warning}: {lines:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_uses_the_scripts_extension_before_following_a_link() {
|
||||
@@ -221,7 +249,6 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
assert!(dir.join("e.JPG").is_file() && !dir.join("e.JPG.jpg").exists(), "a name that ends with the extension keeps it");
|
||||
assert!(std::fs::read(dir.join("f.svgz")).unwrap().starts_with(&[0x1f, 0x8b]));
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -380,7 +407,7 @@ fn save_as_uses_the_link_name_extension_for_the_encoder() {
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -403,7 +430,7 @@ fn save_as_template_preserves_the_document_file_and_saved_state() {
|
||||
assert_eq!(out, json!([[true, true], [true, false]]));
|
||||
assert!(dir.join("clean.vctemplate").is_file());
|
||||
assert!(dir.join("dirty.vctemplate").is_file());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -419,7 +446,7 @@ fn open_uses_the_requested_symlink_filename() {
|
||||
let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link)));
|
||||
assert_eq!(out, json!([["drawing.svg", "drawing.svg"]]));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// Without options, a save or export writes what an untouched new options object of its class gives.
|
||||
@@ -456,7 +483,6 @@ fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
let pdf = std::fs::read(dir.join(name)).unwrap();
|
||||
assert!(pdf.starts_with(b"%PDF-1.4"), "{name}: PDFCompatibility.ACROBAT5 is PDF 1.4, {:?}", String::from_utf8_lossy(&pdf[..8]));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// White, the default `matteColor` of `ExportOptionsPNG24` and `ExportOptionsJPEG`, is accepted, and
|
||||
@@ -531,7 +557,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() {
|
||||
let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec()));
|
||||
// A file system that refuses such a name has nothing to refuse.
|
||||
if std::fs::write(&target, &bytes).is_err() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
return;
|
||||
}
|
||||
let link = dir.join("alias.vectorcraft");
|
||||
@@ -553,7 +579,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() {
|
||||
assert_eq!(std::fs::read(&target).unwrap(), bytes);
|
||||
assert_eq!(std::fs::read(&lossy).unwrap(), bytes);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// Every enumeration an option keeps its default in is defined: the default member is accepted, and
|
||||
@@ -578,7 +604,6 @@ fn kept_enum_options_accept_their_default_member() {
|
||||
("PDFSaveOptions", "pDFChangesAllowed", "PDFChangesAllowedEnum.CHANGE128ANYCHANGES", "PDFChangesAllowedEnum.CHANGE40NONE"),
|
||||
("PDFSaveOptions", "pDFXStandard", "PDFXStandard.PDFXNONE", "PDFXStandard.PDFX42007"),
|
||||
("PDFSaveOptions", "trimMarkWeight", "PDFTrimMarkWeight.TRIMMARKWEIGHT0125", "PDFTrimMarkWeight.TRIMMARKWEIGHT05"),
|
||||
("ExportOptionsSVG", "cssProperties", "SVGCSSPropertyLocation.STYLEATTRIBUTES", "SVGCSSPropertyLocation.ENTITIES"),
|
||||
("ExportOptionsSVG", "documentEncoding", "SVGDocumentEncoding.ASCII", "SVGDocumentEncoding.UTF8"),
|
||||
("ExportOptionsSVG", "DTD", "SVGDTDVersion.SVG1_1", "SVGDTDVersion.SVGTINY1_2"),
|
||||
("ExportOptionsSVG", "fontSubsetting", "SVGFontSubsetting.ALLGLYPHS", "SVGFontSubsetting.GLYPHSUSED"),
|
||||
@@ -597,7 +622,7 @@ fn kept_enum_options_accept_their_default_member() {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; {}", call(other, format!("no{i}"))));
|
||||
assert!(e.contains("is not available yet"), "{class}.{key} = {other}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A raster export at 100% has one pixel per point, whatever the document's raster effects
|
||||
@@ -624,7 +649,6 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() {
|
||||
let image = image::open(dir.join(name)).unwrap();
|
||||
assert_eq!((image.width(), image.height()), (200, 100), "{name}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The value of the DXF header variable `name` (the group after its name).
|
||||
@@ -757,7 +781,6 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() {
|
||||
let pdf = std::fs::read(dir.join(name)).unwrap();
|
||||
assert!(pdf.starts_with(version), "{name}: {:?}", String::from_utf8_lossy(&pdf[..8]));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A save that writes several files, such as an EPS with a file per artboard, writes none of them
|
||||
@@ -792,7 +815,6 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() {
|
||||
let e = failure(&mut s, &base, &save);
|
||||
assert!(e.contains("not a file"), "{e}");
|
||||
assert!(!central.exists(), "the central file is not written when a folder is where an artboard's file goes");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An export that writes several files writes none of them when a folder is where one of them goes.
|
||||
@@ -863,7 +885,6 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&refused, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Every path goes through the script's file grants, as a `File` opened for reading or writing.
|
||||
@@ -897,8 +918,8 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() {
|
||||
}
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({kept}));"));
|
||||
assert!(e.contains("Script file is read-only"), "{e}");
|
||||
let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir)));
|
||||
assert!(e.contains("Script file") && !e.contains("ran"), "a folder is not saved over: {e}");
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir)));
|
||||
assert!(e.contains("Script file is not a regular file"), "a folder is not saved over: {e}");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("kept.svg")).unwrap(), "kept");
|
||||
assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), "{}");
|
||||
assert!(!base.join("outside/x.svg").exists() && !base.join("outside/x.svg.png").exists());
|
||||
@@ -909,7 +930,6 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The file of an open document is not written or read through a script method unless the
|
||||
@@ -927,7 +947,6 @@ fn an_open_documents_file_is_not_saved_over_without_a_grant() {
|
||||
let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path)));
|
||||
assert!(e.contains(DENIED), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A save or export to a file a `File` object holds open for writing throws, so the object's bytes
|
||||
@@ -953,7 +972,6 @@ fn a_file_open_for_writing_is_not_saved_over() {
|
||||
assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes");
|
||||
assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file `open` reads besides the one it names, here an SVG's linked image, is read only where
|
||||
@@ -994,7 +1012,6 @@ fn open_reads_linked_files_only_where_the_script_may() {
|
||||
std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap();
|
||||
s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap();
|
||||
assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file an open document links to is read by `open` only where the script may read, too.
|
||||
@@ -1053,7 +1070,6 @@ fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&image, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An export does not write a file it writes besides the one named, here an SVG's image, while a
|
||||
@@ -1085,7 +1101,6 @@ fn an_svg_export_does_not_write_an_image_a_file_holds_open() {
|
||||
assert!(log[0].as_str().unwrap().contains(DENIED), "{log}");
|
||||
assert!(!svg.exists(), "the SVG is not written when its image may not be");
|
||||
assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link inside a granted folder that leads out of it is followed and refused.
|
||||
@@ -1108,7 +1123,6 @@ fn a_link_out_of_the_granted_folder_is_refused() {
|
||||
assert!(e.contains(DENIED), "{e}");
|
||||
assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without options, `saveAs` takes the format from the path the script names, not from the file a
|
||||
@@ -1126,7 +1140,6 @@ fn save_as_takes_the_format_of_the_named_path_through_a_link() {
|
||||
let written = std::fs::read(dir.join("target.pdf")).unwrap();
|
||||
assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF");
|
||||
assert!(String::from_utf8_lossy(&written).contains("<svg"), "an SVG file");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad arguments throw before anything is written or opened.
|
||||
@@ -1252,7 +1265,6 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(s.active().unwrap().path, None);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a
|
||||
@@ -1289,7 +1301,6 @@ fn a_forged_file_is_refused() {
|
||||
assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1);
|
||||
assert_eq!(s.documents().len(), 1, "nothing is opened");
|
||||
assert_eq!(s.active().unwrap().path, None);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document from an earlier run is stale, and saving it throws.
|
||||
@@ -1303,7 +1314,6 @@ fn a_stale_document_is_not_saved() {
|
||||
let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg"))));
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
assert!(!dir.join("x.svg").exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `open` applies the page and crop box of its options to a PDF.
|
||||
@@ -1312,9 +1322,13 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
let base = folder("pdf");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap();
|
||||
// Page 2 is 200 × 400 pt with a 180 × 380 pt crop box, unlike page 1's 100 × 100 pt.
|
||||
let mut second = vectorcraft_testkit::pdf::PdfPage::new(200.0, 400.0, "0 0 1 rg 20 30 40 50 re f");
|
||||
second.crop = Some([10.0, 10.0, 190.0, 390.0]);
|
||||
let pages = [vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), second];
|
||||
let pdf = dir.join("two.pdf");
|
||||
s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
|
||||
std::fs::write(&pdf, vectorcraft_testkit::pdf::pdf(&pages, None)).unwrap();
|
||||
let size = |s: &Session| s.active().map(|st| st.doc.artboards.iter().map(|a| (a.rect.width(), a.rect.height())).collect::<Vec<_>>());
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
@@ -1325,6 +1339,9 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!(["DocumentColorSpace.CMYK"]));
|
||||
assert_eq!(size(&s), Some(vec![(200.0, 400.0)]), "page 2 on its media box");
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 2}});", quoted(&pdf)));
|
||||
assert_eq!(size(&s), Some(vec![(180.0, 380.0)]), "page 2 on its crop box, the default");
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf)));
|
||||
assert!(!e.is_empty(), "a page the file does not have");
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
@@ -1334,7 +1351,65 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
logged(&mut s, &base, &undefined);
|
||||
assert_eq!(s.documents().len(), 3);
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An SVG export to a name that ends with `.svgz` writes a compressed file at that name, without
|
||||
/// options and with `compressed` false; a name without the suffix stays a plain SVG. `cssProperties`
|
||||
/// picks how the style properties are written.
|
||||
#[test]
|
||||
fn export_file_keeps_an_svgz_name_compressed_and_applies_css_properties() {
|
||||
let base = folder("svgz");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 20, 20);\n\
|
||||
vc.run('shape.rectangle', {{x: 2, y: 2, width: 10, height: 10}});\n\
|
||||
d.exportFile(new File(dir + '/logo.svgz'), ExportType.SVG);\n\
|
||||
var o = new ExportOptionsSVG(); o.compressed = false;\n\
|
||||
d.exportFile(new File(dir + '/plain.SVGZ'), ExportType.SVG, o);\n\
|
||||
d.exportFile(new File(dir + '/page'), ExportType.SVG);\n\
|
||||
var a = new ExportOptionsSVG(); a.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;\n\
|
||||
d.exportFile(new File(dir + '/attributes'), ExportType.SVG, a);"
|
||||
),
|
||||
);
|
||||
for name in ["logo.svgz", "plain.SVGZ"] {
|
||||
assert!(std::fs::read(dir.join(name)).unwrap().starts_with(&[0x1f, 0x8b]), "{name}");
|
||||
assert!(!dir.join(format!("{name}.svg")).exists(), "{name}");
|
||||
}
|
||||
let page = std::fs::read_to_string(dir.join("page.svg")).unwrap();
|
||||
assert!(page.contains("style=\"fill:"), "a new options object's cssProperties is STYLEATTRIBUTES: {page}");
|
||||
let attributes = std::fs::read_to_string(dir.join("attributes.svg")).unwrap();
|
||||
assert!(attributes.contains(" fill=\"") && !attributes.contains("style=\"fill:"), "{attributes}");
|
||||
}
|
||||
|
||||
/// A path whose real path has no UTF-8 form, through a link to a folder of such a name, is refused
|
||||
/// before anything is written there.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_real_path_that_is_not_unicode_is_refused() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let base = folder("not-unicode");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd-\xff"));
|
||||
std::fs::create_dir_all(&odd).unwrap();
|
||||
std::os::unix::fs::symlink(&odd, dir.join("link")).unwrap();
|
||||
let link = quoted(&dir.join("link"));
|
||||
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
for call in [
|
||||
format!("app.activeDocument.exportFile(new File({link} + '/out.png'), ExportType.PNG24)"),
|
||||
format!("app.activeDocument.saveAs(new File({link} + '/out.svg'))"),
|
||||
format!("app.activeDocument.exportForScreens(new Folder({link}), ExportForScreensType.SE_PNG24)"),
|
||||
] {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; {call};"));
|
||||
assert!(e.contains("Script file path is not valid UTF-8"), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing is written in the folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1356,7 +1431,7 @@ fn crop_only_options_apply_to_an_editable_pdf() {
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf)));
|
||||
let cropped = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert!(cropped.width() > original.width() && cropped.height() > original.height());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1388,7 +1463,7 @@ fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() {
|
||||
assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}");
|
||||
assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1404,7 +1479,7 @@ fn script_document_open_rejects_files_over_the_read_limit() {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file)));
|
||||
assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}");
|
||||
assert_eq!(s.documents().len(), count);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1432,7 +1507,7 @@ fn pdf_open_options_reject_other_detected_formats() {
|
||||
s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf)));
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1451,7 +1526,7 @@ fn script_document_open_treats_null_pdf_options_as_omitted() {
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1484,7 +1559,7 @@ fn explicit_null_options_do_not_save_export_open_or_close() {
|
||||
assert_ne!(std::fs::read(&file).unwrap(), original);
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);");
|
||||
assert!(s.documents().is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its
|
||||
@@ -1531,7 +1606,6 @@ fn full_name_path_saved_and_close_follow_the_documents_file() {
|
||||
assert!(s.documents().is_empty());
|
||||
let e = failure(&mut s, &base, "app.documents.add(); app.activeDocument.close('DONOTSAVECHANGES');");
|
||||
assert!(e.contains("SaveOptions"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document whose file was saved under a relative name is in the working folder the file was
|
||||
@@ -1599,7 +1673,6 @@ fn a_document_without_unsaved_changes_closes_with_any_save_options() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([[true, true, 2], 1, 0]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `close(SaveOptions.SAVECHANGES)` saves in the format the document was last saved in, not the
|
||||
@@ -1615,10 +1688,14 @@ fn closing_with_save_changes_keeps_the_documents_format() {
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\
|
||||
vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);"
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());"
|
||||
),
|
||||
);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"Folder.userData; var d = app.activeDocument; vc.run('shape.rectangle', {x: 20, y: 20, width: 5, height: 5}); d.close(SaveOptions.SAVECHANGES);",
|
||||
);
|
||||
let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default();
|
||||
assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format");
|
||||
let pdf = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
@@ -1630,7 +1707,6 @@ fn closing_with_save_changes_keeps_the_documents_format() {
|
||||
assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}");
|
||||
assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}");
|
||||
assert!(s.documents().is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards
|
||||
@@ -1661,7 +1737,7 @@ fn closing_with_save_changes_refuses_a_save_of_some_artboards() {
|
||||
}
|
||||
assert_eq!(drawn, 0, "the file is left as the first save wrote it");
|
||||
assert!(s.active().unwrap().is_dirty(), "the change is still unsaved");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1705,7 +1781,7 @@ fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() {
|
||||
assert!(e.contains("some of its artboards"), "{e}");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF
|
||||
@@ -1741,7 +1817,7 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() {
|
||||
);
|
||||
assert!(s.documents().is_empty(), "the .ai file keeps every artboard, so it closes");
|
||||
assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A native file and a `.ai` file saved without separate artboard files, and an SVG file that
|
||||
@@ -1777,7 +1853,7 @@ fn closing_with_save_changes_saves_files_that_keep_every_artboard() {
|
||||
s.execute("document.open", &json!({"path": file.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "{name} keeps both artboards");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1814,7 +1890,7 @@ fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() {
|
||||
assert!(s.active().unwrap().doc.node_count() > nodes, "{range}");
|
||||
logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1853,7 +1929,7 @@ fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() {
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1873,7 +1949,7 @@ fn document_path_reflection_describes_folders_and_unsaved_strings() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// Setting `Document.saved` records the document's saved state without saving it: `true` lets
|
||||
@@ -1902,7 +1978,6 @@ fn setting_saved_records_the_saved_state() {
|
||||
assert_eq!(out[5][1], json!(1), "a document set as unsaved stays open");
|
||||
assert!(out[6].as_str().unwrap().contains("true or false"), "{}", out[6]);
|
||||
assert!(s.active().unwrap().is_dirty(), "the state stays after the run");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The warnings of a save go to the console after the method's name.
|
||||
@@ -1915,7 +1990,7 @@ fn save_as_writes_its_warnings_to_the_console() {
|
||||
let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A point change that waits to be written counts as an unsaved change for `saved` and `close`.
|
||||
@@ -1939,7 +2014,7 @@ fn waiting_point_changes_count_as_unsaved_changes() {
|
||||
assert_eq!(out[0], json!(false), "a waiting point change is unsaved");
|
||||
assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]);
|
||||
assert_eq!(out[1][1], json!(1), "close() keeps the document open");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1957,7 +2032,7 @@ fn unchanged_saved_assignments_do_not_record_commands() {
|
||||
assert_eq!(out, json!([true, false, true]));
|
||||
let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect();
|
||||
assert_eq!(changes, [json!(false), json!(true)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// With automation read roots that leave out the document's file, `fullName` and `path` throw
|
||||
@@ -1994,7 +2069,6 @@ fn full_name_and_path_leave_out_a_file_outside_the_read_roots() {
|
||||
assert!(e.contains(DENIED) && !e.contains("outside"), "SAVECHANGES does not write a file the script may not: {e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before, "the file is left as it was");
|
||||
assert_eq!(s.documents().len(), 1, "the document stays open");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2023,7 +2097,7 @@ fn implicit_multifile_save_redacts_preflight_refusals_before_writing() {
|
||||
let explicit =
|
||||
crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string();
|
||||
assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name
|
||||
@@ -2058,7 +2132,6 @@ fn a_bracketed_pdf_preset_names_the_built_in_preset() {
|
||||
);
|
||||
assert!(e.contains("unknown PDF preset"), "{bad}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A number given as `artboardRange` is read as `String(number)` reads it.
|
||||
@@ -2081,7 +2154,6 @@ fn a_number_artboard_range_names_that_artboard() {
|
||||
assert_eq!(pdf.artboards.len(), 1, "one page");
|
||||
let r = pdf.artboards[0].rect;
|
||||
assert!((r.width() - 60.0).abs() < 0.01 && (r.height() - 80.0).abs() < 0.01, "the second artboard: {r:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With `saveMultipleArtboards`, a `.ai` or EPS save also writes a file for each artboard of
|
||||
@@ -2143,5 +2215,4 @@ fn save_multiple_artboards_writes_a_file_per_artboard() {
|
||||
assert!(e.contains("range"), "{bad}: {e}");
|
||||
}
|
||||
assert!(!dir.join("aioff/b.ai").exists(), "a bad range writes nothing");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! Exporting for screens from a script: `Document.exportForScreens`, `ExportForScreensItemToExport`,
|
||||
//! the option classes and the file grants the folder goes through.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn screen_width_and_height_reject_effective_scales_outside_the_encoder_range() {
|
||||
for mode in ["SCALEBYWIDTH", "SCALEBYHEIGHT"] {
|
||||
for pixels in [65.0, 0.001] {
|
||||
let base = vectorcraft_testkit::TempDir::new("screen-size-limit");
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let output = dir.join("scaled");
|
||||
let source = format!(
|
||||
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 1, 1); \
|
||||
var o = new ExportForScreensOptionsPNG24(); \
|
||||
o.scaleType = ExportForScreensScaleType.{mode}; o.scaleTypeValue = {pixels}; \
|
||||
d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG24, o);",
|
||||
quoted(&output)
|
||||
);
|
||||
let error = failure(&mut s, &base, &source);
|
||||
assert!(error.contains("scale"), "{mode}: {pixels}: {error}");
|
||||
assert!(!output.exists(), "{mode}: {pixels}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_png8_without_matting_keeps_transparent_edge_colors() {
|
||||
let base = vectorcraft_testkit::TempDir::new("screen-png8-unmatted");
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 20, 20); \
|
||||
vc.run('shape.rectangle', {{x: 0, y: 0, width: 20, height: 20}}); \
|
||||
vc.run('paint.setFill', {{color: '#ff0000'}}); d.pageItems[0].opacity = 50; \
|
||||
var o = new ExportForScreensOptionsPNG8(); o.matte = false; \
|
||||
d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG8, o);",
|
||||
quoted(&dir.join("png8"))
|
||||
),
|
||||
);
|
||||
let output = dir.join("png8");
|
||||
let files = names(&output);
|
||||
assert_eq!(files.len(), 1);
|
||||
let rgba = image::open(output.join(&files[0])).unwrap().to_rgba8();
|
||||
let pixel = rgba.get_pixel(5, 5).0;
|
||||
assert!(pixel[0] > 200 && pixel[1] < 20 && pixel[2] < 20, "{pixel:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_screen_svg_images_are_rejected_before_output_is_created() {
|
||||
let base = vectorcraft_testkit::TempDir::new("screen-svg-linked");
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
|
||||
let output = dir.join("svg");
|
||||
let error = failure(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new ExportForScreensOptionsWebOptimizedSVG(); \
|
||||
o.rasterImageLocation = RasterImageLocation.LINK; \
|
||||
app.activeDocument.exportForScreens(new Folder({}), ExportForScreensType.SE_SVG, o);",
|
||||
quoted(&output)
|
||||
),
|
||||
);
|
||||
assert!(error.contains("not available yet"), "{error}");
|
||||
assert!(!output.exists());
|
||||
}
|
||||
|
||||
/// A volume root the person picked is a folder the export may write into: the export goes on to
|
||||
/// the command, which here refuses an asset the document does not have, and writes nothing.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_picked_volume_root_is_a_folder_to_export_into() {
|
||||
let base = vectorcraft_testkit::TempDir::new("screen-root");
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
|
||||
s.script_frames = true;
|
||||
let main = base.join("main/main.jsx");
|
||||
let script = "var p = Folder.selectDialog('p'); var i = new ExportForScreensItemToExport(); i.artboards = ''; i.assets = [987654321];\n\
|
||||
try { app.activeDocument.exportForScreens(p, ExportForScreensType.SE_PNG24, undefined, i); vc.log('exported'); } catch (e) { vc.log(String(e)); }";
|
||||
std::fs::write(&main, script).unwrap();
|
||||
assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true);
|
||||
let mut picked = false;
|
||||
let mut report = None;
|
||||
for _ in 0..10_000 {
|
||||
if !picked && s.script_picker().is_some() {
|
||||
picked = true;
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec!["/".into()], always: false }));
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
report = Some(r.unwrap());
|
||||
break;
|
||||
}
|
||||
}
|
||||
let report = report.unwrap_or_else(|| panic!("the run neither ended nor waited"));
|
||||
assert!(picked, "{report}");
|
||||
let said = report["log"][0].as_str().unwrap_or_default().to_string();
|
||||
assert!(!said.contains(DENIED) && !said.contains("exported") && said.contains("987654321"), "{said}");
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, by its real path, with `main` for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-screens-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`.
|
||||
fn session(base: &Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.attach_script_data(base.join("settings/Script Data"));
|
||||
s
|
||||
}
|
||||
|
||||
/// Runs `main/main.jsx` in `base` with the text `text` in `s`.
|
||||
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
|
||||
let main = base.join("main/main.jsx");
|
||||
std::fs::write(&main, text.as_bytes()).unwrap();
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
|
||||
}
|
||||
|
||||
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
|
||||
run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone()
|
||||
}
|
||||
|
||||
fn failure(s: &mut Session, base: &Path, text: &str) -> String {
|
||||
run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
/// The script's data folder, where it may write.
|
||||
fn data_folder(s: &mut Session, base: &Path) -> PathBuf {
|
||||
PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap())
|
||||
}
|
||||
|
||||
fn quoted(p: &Path) -> String {
|
||||
serde_json::to_string(&p.to_string_lossy()).unwrap()
|
||||
}
|
||||
|
||||
/// The names of the files in `dir`, sorted; none when it is not there.
|
||||
fn names(dir: &Path) -> Vec<String> {
|
||||
let mut v: Vec<String> =
|
||||
std::fs::read_dir(dir).map(|r| r.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// A script that makes a document of two artboards with a rectangle on the first, in `dir`.
|
||||
fn two_artboards(dir: &Path) -> String {
|
||||
format!(
|
||||
"Folder.userData; var dir = {}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n",
|
||||
quoted(dir)
|
||||
)
|
||||
}
|
||||
|
||||
/// Each export type writes its format into the folder, a file per artboard of the item's range, at
|
||||
/// the size the options' scale type gives.
|
||||
#[test]
|
||||
fn export_for_screens_writes_each_format_into_the_folder() {
|
||||
let base = folder("formats");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{}var one = new ExportForScreensItemToExport(); one.artboards = '1';\n\
|
||||
vc.log([one.typename, new ExportForScreensItemToExport().artboards, new ExportForScreensOptionsJPEG().scaleTypeValue]);\n\
|
||||
d.exportForScreens(new Folder(dir + '/jpg'), ExportForScreensType.SE_JPEG100, undefined, one);\n\
|
||||
var p = new ExportForScreensOptionsPNG24(); p.scaleType = ExportForScreensScaleType.SCALEBYFACTOR; p.scaleTypeValue = 2;\n\
|
||||
d.exportForScreens(new Folder(dir + '/png'), ExportForScreensType.SE_PNG24, p);\n\
|
||||
var w = new ExportForScreensOptionsPNG8(); w.scaleType = ExportForScreensScaleType.SCALEBYWIDTH; w.scaleTypeValue = 50;\n\
|
||||
d.exportForScreens(new Folder(dir + '/png8'), ExportForScreensType.SE_PNG8, w, one);\n\
|
||||
var r = new ExportForScreensOptionsJPEG(); r.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; r.scaleTypeValue = 144;\n\
|
||||
d.exportForScreens(new Folder(dir + '/ppi'), ExportForScreensType.SE_JPEG20, r, one);\n\
|
||||
d.exportForScreens(new Folder(dir + '/svg'), ExportForScreensType.SE_SVG);\n\
|
||||
d.exportForScreens(new Folder(dir + '/pdf'), ExportForScreensType.SE_PDF, new ExportForScreensPDFOptions(), one);",
|
||||
two_artboards(&dir)
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!(["ExportForScreensItemToExport", "all", 1]));
|
||||
let size = |sub: &str| {
|
||||
let files = names(&dir.join(sub));
|
||||
let image = image::open(dir.join(sub).join(&files[0])).unwrap();
|
||||
(files, image.width(), image.height())
|
||||
};
|
||||
let (jpg, w, h) = size("jpg");
|
||||
assert!(jpg.len() == 1 && jpg[0].ends_with(".jpg"), "one artboard: {jpg:?}");
|
||||
assert_eq!((w, h), (200, 100), "a pixel per point at 1x");
|
||||
let (png, w, h) = size("png");
|
||||
assert!(png.len() == 2 && png.iter().all(|n| n.ends_with("@2x.png")), "both artboards at 2x: {png:?}");
|
||||
assert_eq!((w, h), (400, 200), "{png:?}");
|
||||
let (png8, w, h) = size("png8");
|
||||
assert_eq!(png8.len(), 1, "{png8:?}");
|
||||
assert_eq!((w, h), (50, 25), "50 pixels wide, in proportion");
|
||||
let (_, w, h) = size("ppi");
|
||||
assert_eq!((w, h), (400, 200), "144 ppi is two pixels per point");
|
||||
let svg = names(&dir.join("svg"));
|
||||
assert!(svg.len() == 2 && svg.iter().all(|n| n.ends_with(".svg")), "{svg:?}");
|
||||
let pdf = names(&dir.join("pdf"));
|
||||
assert_eq!(pdf.len(), 1, "{pdf:?}");
|
||||
assert!(std::fs::read(dir.join("pdf").join(&pdf[0])).unwrap().starts_with(b"%PDF"));
|
||||
assert_eq!(s.active().unwrap().path, None, "the export leaves the document's file as it is");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without options, an export writes what an untouched new options object of its class gives.
|
||||
#[test]
|
||||
fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
let base = folder("defaults");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let types = [
|
||||
("SE_JPEG80", "ExportForScreensOptionsJPEG"),
|
||||
("SE_PNG24", "ExportForScreensOptionsPNG24"),
|
||||
("SE_PNG8", "ExportForScreensOptionsPNG8"),
|
||||
("SE_SVG", "ExportForScreensOptionsWebOptimizedSVG"),
|
||||
];
|
||||
let calls: String = types
|
||||
.iter()
|
||||
.map(|(t, c)| {
|
||||
format!(
|
||||
"d.exportForScreens(new Folder(dir + '/{t}-a'), ExportForScreensType.{t});\n\
|
||||
d.exportForScreens(new Folder(dir + '/{t}-b'), ExportForScreensType.{t}, new {c}());\n"
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
logged(&mut s, &base, &format!("{}{calls}", two_artboards(&dir)));
|
||||
for (t, _) in types {
|
||||
let (a, b) = (dir.join(format!("{t}-a")), dir.join(format!("{t}-b")));
|
||||
assert!(names(&a) == names(&b) && names(&a).len() == 2, "{t}: {:?} {:?}", names(&a), names(&b));
|
||||
for n in names(&a) {
|
||||
assert!(std::fs::read(a.join(&n)).unwrap() == std::fs::read(b.join(&n)).unwrap(), "{t}: {n} differs");
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `itemToExport` exports the artboards of its range, its assets and the whole document, each that
|
||||
/// it names; one that names nothing throws and writes nothing.
|
||||
#[test]
|
||||
fn item_to_export_picks_artboards_assets_and_the_document() {
|
||||
let base = folder("items");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{}var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\
|
||||
var a = new ExportForScreensItemToExport(); a.artboards = ''; a.assets = ids;\n\
|
||||
d.exportForScreens(new Folder(dir + '/assets'), ExportForScreensType.SE_SVG, undefined, a);\n\
|
||||
var whole = new ExportForScreensItemToExport(); whole.artboards = ''; whole.document = true;\n\
|
||||
d.exportForScreens(new Folder(dir + '/document'), ExportForScreensType.SE_PNG24, undefined, whole);\n\
|
||||
var both = new ExportForScreensItemToExport(); both.assets = ids; both.artboards = '2';\n\
|
||||
d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);",
|
||||
two_artboards(&dir)
|
||||
),
|
||||
);
|
||||
assert_eq!(names(&dir.join("assets")), ["Logo.svg"]);
|
||||
let whole = names(&dir.join("document"));
|
||||
assert_eq!(whole.len(), 1, "{whole:?}");
|
||||
let image = image::open(dir.join("document").join(&whole[0])).unwrap();
|
||||
let (w, h) = (image.width(), image.height());
|
||||
assert!((50..60).contains(&w) && (20..30).contains(&h), "the bounds of the document's art, not an artboard: {w}x{h}");
|
||||
let both = names(&dir.join("both"));
|
||||
assert!(both.len() == 2 && both.contains(&"Logo.svg".to_string()), "artboard 2 and the asset: {both:?}");
|
||||
for empty in ["''", "' '"] {
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var i = new ExportForScreensItemToExport(); i.artboards = {empty};\n\
|
||||
app.activeDocument.exportForScreens(new Folder({} + '/none'), ExportForScreensType.SE_PNG24, undefined, i);",
|
||||
quoted(&dir)
|
||||
),
|
||||
);
|
||||
assert!(e.contains("nothing to export"), "{empty}: {e}");
|
||||
}
|
||||
assert!(!dir.join("none").exists(), "an empty item writes nothing");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An asset named as an artboard of the item's range gets a file of its own: the artboard's file
|
||||
/// keeps its name and the asset's is numbered, in place of writing over it.
|
||||
#[test]
|
||||
fn an_asset_named_as_an_artboard_does_not_overwrite_its_file() {
|
||||
let base = folder("clash");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{}vc.run('artboard.setProps', {{artboards: [{{index: 0, name: 'Logo'}}]}});\n\
|
||||
var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\
|
||||
var both = new ExportForScreensItemToExport(); both.artboards = '1'; both.assets = ids;\n\
|
||||
d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);",
|
||||
two_artboards(&dir)
|
||||
),
|
||||
);
|
||||
assert_eq!(names(&dir.join("both")), ["Logo-2.svg", "Logo.svg"]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The prefix comes before each file's name, and a path character in it does not make a folder or
|
||||
/// reach out of the export folder.
|
||||
#[test]
|
||||
fn a_file_name_prefix_stays_in_the_folder() {
|
||||
let base = folder("prefix");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{}d.exportForScreens(new Folder(dir + '/out'), ExportForScreensType.SE_SVG, undefined, undefined, 'web-');\n\
|
||||
d.exportForScreens(new Folder(dir + '/up'), ExportForScreensType.SE_SVG, undefined, undefined, '../x/');",
|
||||
two_artboards(&dir)
|
||||
),
|
||||
);
|
||||
let out = names(&dir.join("out"));
|
||||
assert!(out.len() == 2 && out.iter().all(|n| n.starts_with("web-")), "{out:?}");
|
||||
let up = names(&dir.join("up"));
|
||||
assert!(up.len() == 2 && up.iter().all(|n| n.starts_with("..-x-")), "{up:?}");
|
||||
let entries: Vec<_> = std::fs::read_dir(dir.join("up")).unwrap().map(|e| e.unwrap()).collect();
|
||||
assert_eq!(entries.len(), 2, "{entries:?}");
|
||||
assert!(entries.iter().all(|e| e.file_type().unwrap().is_file()), "no folder was made");
|
||||
assert!(!dir.join("x").exists(), "nothing is written beside the folder");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The folder goes through the script's file grants: one outside them, and a file given as the
|
||||
/// folder, throw before anything is written.
|
||||
#[test]
|
||||
fn an_unwritable_folder_is_refused() {
|
||||
let base = folder("refused");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
std::fs::write(dir.join("taken"), "kept").unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let outside = quoted(&base.join("outside/screens"));
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({outside}), ExportForScreensType.SE_PNG24);"),
|
||||
);
|
||||
assert!(e.contains(DENIED), "{e}");
|
||||
assert!(!base.join("outside/screens").exists());
|
||||
let taken = quoted(&dir.join("taken"));
|
||||
let e =
|
||||
failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({taken}), ExportForScreensType.SE_PNG24);"));
|
||||
assert!(e.contains(crate::script::files::NOT_FOLDER), "{e}");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("taken")).unwrap(), "kept");
|
||||
assert_eq!(names(&base.join("outside")), Vec::<String>::new());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Only a `Folder` the `Folder` class made (or a `File`) names the folder: an object made from
|
||||
/// `Folder.prototype` throws a `TypeError`, and a `Folder` whose hidden path property a script set
|
||||
/// keeps its own path.
|
||||
#[test]
|
||||
fn a_forged_folder_is_refused() {
|
||||
let base = folder("forged");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let (inside, outside) = (quoted(&dir.join("in")), quoted(&base.join("outside/x")));
|
||||
let call = |f: &str| format!("Folder.userData; app.activeDocument.exportForScreens({f}, ExportForScreensType.SE_SVG);");
|
||||
let made = format!("(function () {{ var f = Object.create(Folder.prototype); f.__vcPath = {inside}; return f; }})()");
|
||||
let e = failure(&mut s, &base, &call(&made));
|
||||
assert!(e.contains("TypeError") && e.contains("needs a Folder"), "{e}");
|
||||
let moved = format!("(function () {{ var f = new Folder({outside}); f.__vcPath = {inside}; return f; }})()");
|
||||
let e = failure(&mut s, &base, &call(&moved));
|
||||
assert!(e.contains(DENIED), "{e}");
|
||||
assert!(!dir.join("in").exists() && !base.join("outside/x").exists(), "nothing is written");
|
||||
logged(&mut s, &base, &call(&format!("new File({inside})")));
|
||||
assert_eq!(names(&dir.join("in")).len(), 1, "a File names the folder at its path");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad arguments throw before anything is written.
|
||||
#[test]
|
||||
fn bad_arguments_are_refused_with_an_error() {
|
||||
let base = folder("bad");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let f = format!("new Folder({})", quoted(&dir.join("x")));
|
||||
let e = "app.activeDocument.exportForScreens";
|
||||
let long = "a".repeat(300);
|
||||
let cases: Vec<(String, &str)> = vec![
|
||||
(format!("{e}('x', ExportForScreensType.SE_PNG24);"), "needs a Folder"),
|
||||
(format!("{e}({f}, 'SE_PNG24');"), "ExportForScreensType"),
|
||||
(format!("{e}({f}, ExportType.PNG24);"), "ExportForScreensType"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, new ExportForScreensOptionsJPEG());"), "ExportForScreensOptionsPNG24"),
|
||||
(
|
||||
format!("{e}({f}, ExportForScreensType.SE_SVG, {{typename: 'ExportForScreensOptionsWebOptimizedSVG', svgMinified: true}});"),
|
||||
"has no option svgMinified",
|
||||
),
|
||||
(format!("var o = new ExportForScreensOptionsJPEG(); o.progressiveScan = 6; {e}({f}, ExportForScreensType.SE_JPEG50, o);"), "from 3 to 5"),
|
||||
(format!("var o = new ExportForScreensOptionsPNG8(); o.colorCount = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "from 2 to 256"),
|
||||
(format!("var o = new ExportForScreensOptionsPNG8(); o.matteColor = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "not available yet"),
|
||||
(format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 0; {e}({f}, ExportForScreensType.SE_PNG24, o);"), "above 0"),
|
||||
(
|
||||
format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 100; {e}({f}, ExportForScreensType.SE_PNG24, o);"),
|
||||
"from 0.01 to 64",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportForScreensOptionsPNG24(); o.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; o.scaleTypeValue = 5000; {e}({f}, ExportForScreensType.SE_PNG24, o);"
|
||||
),
|
||||
"from 0.72 to 4608",
|
||||
),
|
||||
(
|
||||
format!("var o = new ExportForScreensOptionsPNG24(); o.scaleType = 'SCALEBYWIDTH'; {e}({f}, ExportForScreensType.SE_PNG24, o);"),
|
||||
"ExportForScreensScaleType",
|
||||
),
|
||||
(
|
||||
format!("var o = new ExportForScreensOptionsPNG24(); o.antiAliasing = true; {e}({f}, ExportForScreensType.SE_PNG24, o);"),
|
||||
"AntiAliasingMethod",
|
||||
),
|
||||
(
|
||||
format!("var o = new ExportForScreensOptionsWebOptimizedSVG(); o.svgId = SVGFontType.SVGFONT; {e}({f}, ExportForScreensType.SE_SVG, o);"),
|
||||
"SVGIdType",
|
||||
),
|
||||
(format!("var o = new ExportForScreensPDFOptions(); o.pdfPreset = '{long}'; {e}({f}, ExportForScreensType.SE_PDF, o);"), "255 bytes"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, {{artboards: '1'}});"), "ExportForScreensItemToExport"),
|
||||
(format!("var i = new ExportForScreensItemToExport(); i.artboards = '2-1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"),
|
||||
(
|
||||
format!("var i = new ExportForScreensItemToExport(); i.artboards = 0; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
|
||||
"whole number from 1",
|
||||
),
|
||||
(
|
||||
format!("var i = new ExportForScreensItemToExport(); i.assets = 3; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
|
||||
"array of asset ids",
|
||||
),
|
||||
(
|
||||
format!("var i = new ExportForScreensItemToExport(); i.assets = [1.5]; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
|
||||
"not an asset id",
|
||||
),
|
||||
(
|
||||
format!("var i = new ExportForScreensItemToExport(); i.document = 'yes'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
|
||||
"true or false",
|
||||
),
|
||||
(
|
||||
format!("var i = new ExportForScreensItemToExport(); i.artboard = '1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
|
||||
"has no option artboard",
|
||||
),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, 5);"), "fileNamePrefix must be a string"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, null);"), "the options must be an object"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, null);"), "ExportForScreensItemToExport"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, null);"), "fileNamePrefix must be a string"),
|
||||
(format!("var i = new ExportForScreensItemToExport(); i.artboards = '3'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"),
|
||||
];
|
||||
for (case, wanted) in &cases {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; {case}"));
|
||||
assert!(e.contains(wanted), "{case}: {e}");
|
||||
}
|
||||
assert!(!dir.join("x").exists(), "nothing was written");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -3920,6 +3920,16 @@ proptest! {
|
||||
fn pasted_metafiles_never_panic(which in 0usize..2, cut in 0usize..200_000, edits in prop::collection::vec((0usize..200_000, any::<u8>()), 0..12)) {
|
||||
paste_from_elsewhere("clipboard.importEmf", json!({"dataBase64": mutated_b64(metafile_samples()[which].clone(), cut, &edits)}))?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_cad_files_never_panic(r12 in any::<bool>(), cut in 0usize..60_000, edits in prop::collection::vec((0usize..60_000, any::<u8>()), 0..12)) {
|
||||
static SAMPLES: std::sync::OnceLock<[Vec<u8>; 2]> = std::sync::OnceLock::new();
|
||||
let samples = SAMPLES.get_or_init(|| [rich_dxf("2018"), rich_dxf("R12")]);
|
||||
let dxf = mutated_b64(samples[usize::from(r12)].clone(), cut, &edits);
|
||||
paste_from_elsewhere("clipboard.importCad", json!({"dataBase64": dxf, "format": "dxf"}))?;
|
||||
let plot = mutated_b64(b"IN;SP1;PA0,0;PD1016,0,1016,1016,0,1016,0,0;PU;LBText\x03;".to_vec(), cut % 64, &edits);
|
||||
paste_from_elsewhere("clipboard.importCad", json!({"dataBase64": plot, "format": "hpgl"}))?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- PICT pictures: opened and placed ----------
|
||||
|
||||
@@ -47,6 +47,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||||
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
|
||||
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
|
||||
("Document.prototype.exportForScreens", "app.activeDocument.exportForScreens(f, ExportForScreensType.SE_PNG24);", "filesWritten"),
|
||||
("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"),
|
||||
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
|
||||
];
|
||||
@@ -98,12 +99,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
(
|
||||
"",
|
||||
"activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \
|
||||
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
"activeDocument activeDocument= app Application Artboard Artboards BlendModes Brush Brushes ColorModel CompoundPathItem \
|
||||
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
|
||||
GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
|
||||
PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
|
||||
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||||
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
|
||||
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
|
||||
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
|
||||
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
|
||||
View Views ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
@@ -132,15 +135,15 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \
|
||||
"activeLayer activeLayer= artboards brushes characterStyles close compoundPathItems constructor convertCoordinate \
|
||||
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
|
||||
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
|
||||
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
|
||||
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
|
||||
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -151,7 +154,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Layer.prototype.",
|
||||
"artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \
|
||||
dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \
|
||||
locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \
|
||||
locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \
|
||||
preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \
|
||||
toString typename visible visible= zOrder zOrderPosition",
|
||||
),
|
||||
@@ -160,7 +163,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("GroupItem.", "prototype"),
|
||||
(
|
||||
"GroupItem.prototype.",
|
||||
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \
|
||||
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \
|
||||
rasterItems rasterItems= symbolItems symbolItems= textFrames",
|
||||
),
|
||||
("GroupItems.", "prototype"),
|
||||
@@ -239,13 +242,42 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
strokeWidth strokeWidth= stroked stroked=",
|
||||
),
|
||||
("PathPoints.", "prototype"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll toString typename"),
|
||||
("PathPoint.", "prototype"),
|
||||
(
|
||||
"PathPoint.prototype.",
|
||||
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
|
||||
rightDirection= selected selected= typename",
|
||||
rightDirection= selected selected= toString typename",
|
||||
),
|
||||
("Swatches.", "prototype"),
|
||||
("Swatches.prototype.", "add constructor getByName getSelected getSelected= index length parent removeAll typename"),
|
||||
("Swatch.", "prototype"),
|
||||
("Swatch.prototype.", "color color= constructor name name= parent remove typename"),
|
||||
("Spots.", "prototype"),
|
||||
("Spots.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Spot.", "prototype"),
|
||||
("Spot.prototype.", "color color= colorType colorType= constructor getInternalColor name name= parent remove spotKind typename"),
|
||||
("SwatchGroups.", "prototype"),
|
||||
("SwatchGroups.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("SwatchGroup.", "prototype"),
|
||||
("SwatchGroup.prototype.", "addSpot addSwatch constructor getAllSwatches name name= parent remove removeAll typename"),
|
||||
("Symbols.", "prototype"),
|
||||
("Symbols.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Symbol.", "prototype"),
|
||||
("Symbol.prototype.", "constructor duplicate name name= parent remove typename"),
|
||||
("SymbolItems.", "prototype"),
|
||||
("SymbolItems.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("SymbolItem.", "prototype"),
|
||||
("SymbolItem.prototype.", "constructor symbol symbol="),
|
||||
("GraphicStyles.", "prototype"),
|
||||
("GraphicStyles.prototype.", "constructor getByName index length parent removeAll typename"),
|
||||
("GraphicStyle.", "prototype"),
|
||||
("GraphicStyle.prototype.", "applyTo constructor mergeTo name name= parent remove typename"),
|
||||
("Brushes.", "prototype"),
|
||||
("Brushes.prototype.", "constructor getByName index length parent typename"),
|
||||
("Brush.", "prototype"),
|
||||
("Brush.prototype.", "applyTo constructor name parent typename"),
|
||||
("ColorModel.", "PROCESS REGISTRATION SPOT"),
|
||||
("Tags.", "prototype"),
|
||||
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Tag.", "prototype"),
|
||||
@@ -272,8 +304,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
|
||||
("SpotColorKind.", "SPOTCMYK SPOTLAB SPOTRGB"),
|
||||
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
|
||||
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
|
||||
(
|
||||
"SymbolRegistrationPoint.",
|
||||
"SYMBOLBOTTOMLEFTPOINT SYMBOLBOTTOMMIDDLEPOINT SYMBOLBOTTOMRIGHTPOINT SYMBOLCENTERPOINT SYMBOLMIDDLELEFTPOINT \
|
||||
SYMBOLMIDDLERIGHTPOINT SYMBOLTOPLEFTPOINT SYMBOLTOPMIDDLEPOINT SYMBOLTOPRIGHTPOINT",
|
||||
),
|
||||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
// The enumerations of saving, exporting and opening.
|
||||
@@ -340,6 +378,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.prototype.", "rasterize windowCapture windowCapture="),
|
||||
("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"),
|
||||
("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"),
|
||||
// The enumerations of exporting for screens (`AntiAliasingMethod`, `SVGCSSPropertyLocation` and `SVGFontType` are above).
|
||||
("", "ExportForScreensScaleType ExportForScreensType JPEGCompressionMethodType RasterImageLocation SVGIdType"),
|
||||
("ExportForScreensScaleType.", "SCALEBYFACTOR SCALEBYHEIGHT SCALEBYRESOLUTION SCALEBYWIDTH"),
|
||||
("ExportForScreensType.", "SE_JPEG100 SE_JPEG20 SE_JPEG50 SE_JPEG80 SE_PDF SE_PNG24 SE_PNG8 SE_SVG"),
|
||||
("JPEGCompressionMethodType.", "BASELINEOPTIMIZED BASELINESTANDARD PROGRESSIVE"),
|
||||
("RasterImageLocation.", "EMBED LINK PRESERVE"),
|
||||
("SVGIdType.", "SVGIDMINIMAL SVGIDREGULAR SVGIDUNIQUE"),
|
||||
// The enumerations of placed and raster items.
|
||||
("", "ImageColorSpace RasterLinkState"),
|
||||
("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"),
|
||||
@@ -435,6 +480,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
|
||||
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
|
||||
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
|
||||
// The text classes and their enumerations.
|
||||
(
|
||||
"",
|
||||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||||
@@ -570,9 +616,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
/// that have no members of their own, the color classes, and the save, export, rasterize and image
|
||||
/// capture option classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
|
||||
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
|
||||
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor cmykColor \
|
||||
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \
|
||||
ImageCaptureOptions RasterizeOptions";
|
||||
ImageCaptureOptions RasterizeOptions \
|
||||
ExportForScreensItemToExport ExportForScreensOptionsJPEG ExportForScreensOptionsPNG24 \
|
||||
ExportForScreensOptionsPNG8 ExportForScreensOptionsWebOptimizedSVG ExportForScreensPDFOptions";
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
/// own API, and what `vc.run` does depends on the command it runs.
|
||||
|
||||
@@ -140,6 +140,144 @@ fn native_composite_meanings_survive_editable_and_embedded_placement() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_dimension_label_font_follows_a_renamed_composite_font() {
|
||||
let _context = FontContext::hold();
|
||||
let dir = TempDir::new("native-composite-dimension");
|
||||
let path = dir.join("dimension.vectorcraft");
|
||||
// The second name is 255 bytes, so an alias that only counted characters would pass the 256
|
||||
// bytes a dimension's family keeps.
|
||||
for name in ["NativeAdoptionDimension".to_string(), "\u{3042}".repeat(85)] {
|
||||
assert_dimension_alias(&path, &name);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_dimension_alias(path: &Path, name: &str) {
|
||||
let incoming = CompositeFont::new(name, "Source Sans 3", "Regular");
|
||||
let mut source = destination(std::slice::from_ref(&incoming));
|
||||
let options = json!({"fontFamily": incoming.name, "fontStyle": "Regular"});
|
||||
source.execute("dimension.create", &json!({"a": [4, 20], "b": [60, 20], "options": options})).unwrap();
|
||||
let source_doc = document(&source).clone();
|
||||
source.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap();
|
||||
write_native(path, &source_doc);
|
||||
for linked in [false, true] {
|
||||
let mut existing = incoming.clone();
|
||||
existing.parts.roman.size = 125.0;
|
||||
let mut session = destination(&[existing]);
|
||||
let id = place(&mut session, path, linked);
|
||||
let root = document(&session).node(id).unwrap();
|
||||
let (mut stored, mut drawn) = (Vec::new(), Vec::new());
|
||||
root.walk(&mut |node| {
|
||||
if let Some(dimension) = &node.extras().dimension {
|
||||
stored.push(dimension.options.font_family.clone());
|
||||
}
|
||||
if let NodeKind::Text(text) = &node.kind {
|
||||
drawn.extend(text.runs.iter().map(|run| run.style.font_family.clone()));
|
||||
}
|
||||
});
|
||||
assert_eq!(stored.len(), 1, "REGRESSION: the placed art keeps its one editable dimension");
|
||||
assert!(stored[0].len() <= 256, "REGRESSION: the alias fits a dimension's family ({} bytes)", stored[0].len());
|
||||
assert!(!drawn.is_empty(), "CONTROL: the dimension draws a label");
|
||||
assert!(!CompositeFont::same_name(&drawn[0], &incoming.name), "CONTROL: the conflicting name is aliased");
|
||||
assert!(
|
||||
drawn.iter().all(|family| family == &stored[0]),
|
||||
"REGRESSION: a redrawn dimension label must keep the aliased composite font ({stored:?} vs {drawn:?})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_dimension_reuses_an_equal_same_named_composite_font_with_a_longer_spelling() {
|
||||
let _context = FontContext::hold();
|
||||
let dir = TempDir::new("native-composite-dimension-same-name");
|
||||
let path = dir.join("dimension.vectorcraft");
|
||||
// 86 ASCII letters are 86 bytes; 86 Kelvin signs are the same name in any case and 258 bytes.
|
||||
let incoming = CompositeFont::new("k".repeat(86), "Source Sans 3", "Regular");
|
||||
let mut source = destination(std::slice::from_ref(&incoming));
|
||||
let options = json!({"fontFamily": incoming.name, "fontStyle": "Regular"});
|
||||
source.execute("dimension.create", &json!({"a": [4, 20], "b": [60, 20], "options": options})).unwrap();
|
||||
let source_doc = document(&source).clone();
|
||||
source.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap();
|
||||
write_native(&path, &source_doc);
|
||||
let mut existing = incoming.clone();
|
||||
existing.name = "\u{212A}".repeat(86);
|
||||
assert!(existing.name.len() > 256, "CONTROL: the destination's spelling is longer than a dimension's family keeps");
|
||||
assert!(CompositeFont::same_name(&existing.name, &incoming.name), "CONTROL: the two spellings are one name");
|
||||
for linked in [false, true] {
|
||||
let mut session = destination(std::slice::from_ref(&existing));
|
||||
let id = place(&mut session, &path, linked);
|
||||
assert_eq!(
|
||||
document(&session).composite_fonts.len(),
|
||||
1,
|
||||
"REGRESSION: an equal composite font of the same name is reused, not copied under a new name"
|
||||
);
|
||||
let mut stored = Vec::new();
|
||||
document(&session).node(id).unwrap().walk(&mut |node| {
|
||||
stored.extend(node.extras().dimension.as_ref().map(|d| d.options.font_family.clone()));
|
||||
});
|
||||
assert_eq!(stored, vec![incoming.name.clone()], "REGRESSION: the dimension keeps its own spelling of the reused name");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_composite_alias_skips_a_family_named_by_a_dimension_in_brush_art() {
|
||||
let _context = FontContext::hold();
|
||||
let dir = TempDir::new("native-composite-brush-dimension");
|
||||
let path = dir.join("lettering.vectorcraft");
|
||||
let incoming = CompositeFont::new("NativeAdoptionBrushDimension", "Source Sans 3", "Regular");
|
||||
write_native(&path, &font_document(&incoming));
|
||||
let taken = format!("{} 2", incoming.name);
|
||||
// The destination's only use of the first free alias is a dimension inside an art brush.
|
||||
let mut builder = destination(&[]);
|
||||
let options = json!({"fontFamily": taken, "fontStyle": "Regular"});
|
||||
let made = builder.execute("dimension.create", &json!({"a": [4, 20], "b": [60, 20], "options": options})).unwrap();
|
||||
let dimension = NodeId(made["id"].as_u64().unwrap());
|
||||
builder.execute("brush.new", &json!({"type": "art", "name": "NativeAdoptionDimensionBrush", "ids": [dimension.0]})).unwrap();
|
||||
let mut doc = document(&builder).clone();
|
||||
if doc.node(dimension).is_some() {
|
||||
doc.remove(dimension).unwrap();
|
||||
}
|
||||
// Leave the dimension's options as the only place the family is named, as in a label drawn
|
||||
// before its options changed, so the reservation cannot come from the label's own runs.
|
||||
fn relabel(node: &mut Node) {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
for run in &mut text.runs {
|
||||
run.style.font_family = "Source Sans 3".into();
|
||||
}
|
||||
}
|
||||
for child in node.children_mut().into_iter().flatten() {
|
||||
relabel(std::sync::Arc::make_mut(child));
|
||||
}
|
||||
}
|
||||
let mut brushes = vectorcraft_brush::library(&doc);
|
||||
for art in brushes.iter_mut().flat_map(|brush| brush.art_mut()) {
|
||||
relabel(art);
|
||||
}
|
||||
vectorcraft_brush::store(&mut doc, &brushes);
|
||||
let mut in_art = Vec::new();
|
||||
doc.visit_stored(|node, _| in_art.extend(node.extras().dimension.as_ref().map(|d| d.options.font_family.clone())));
|
||||
assert!(in_art.is_empty(), "CONTROL: no dimension is left in the document's art");
|
||||
let mut in_brush = Vec::new();
|
||||
for brush in vectorcraft_brush::library(&doc) {
|
||||
if let vectorcraft_brush::BrushKind::Art(art) = &brush.kind {
|
||||
art.art.walk(&mut |node| in_brush.extend(node.extras().dimension.as_ref().map(|d| d.options.font_family.clone())));
|
||||
}
|
||||
}
|
||||
assert_eq!(in_brush, vec![taken.clone()], "CONTROL: the brush art holds the dimension");
|
||||
let mut existing = incoming.clone();
|
||||
existing.parts.roman.size = 125.0;
|
||||
let mut session = Session::new();
|
||||
session.add_document(doc, None);
|
||||
session.execute("type.compositeFonts.set", &json!({"fonts": [existing]})).unwrap();
|
||||
let id = place(&mut session, &path, false);
|
||||
let family = placed_family(&session, id);
|
||||
assert!(!CompositeFont::same_name(&family, &incoming.name), "CONTROL: the conflicting name is aliased");
|
||||
assert!(
|
||||
!CompositeFont::same_name(&family, &taken),
|
||||
"REGRESSION: the alias must not take a family a brush-art dimension already names ({family})"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_composite_alias_is_reused_without_changing_destination_art() {
|
||||
let _context = FontContext::hold();
|
||||
|
||||
@@ -80,6 +80,27 @@ impl Interp {
|
||||
})?;
|
||||
instance(self, proto, fs)
|
||||
}
|
||||
|
||||
/// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is
|
||||
/// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads
|
||||
/// it, or a `Folder` the `Folder` class made, as [`folder_ref`] gives one; `None` for any other
|
||||
/// object, one made with `Object.create(File.prototype)` or `Object.create(Folder.prototype)`
|
||||
/// included.
|
||||
pub(crate) fn file_ref_of(&self, id: ObjId) -> JsResult<Option<crate::Data>> {
|
||||
let Some(c) = &self.files else { return Ok(None) };
|
||||
let o = self.object(id)?;
|
||||
let key = if o.proto == Some(c.file_proto) {
|
||||
crate::FILE_REF_KEY
|
||||
} else if o.proto == Some(c.folder_proto) {
|
||||
FOLDER_REF_KEY
|
||||
} else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(match &o.class {
|
||||
Class::FsEntry(s) => Some(crate::Data::Object(vec![(key.to_string(), crate::Data::String(s.to_rust_string()))])),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of `o` when the `File` or `Folder` class made it.
|
||||
@@ -147,21 +168,6 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype`
|
||||
/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an
|
||||
/// object made with `Object.create(File.prototype)` included.
|
||||
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
|
||||
let Some(c) = &i.files else { return Ok(None) };
|
||||
let o = i.object(id)?;
|
||||
if o.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match own_path(i, id)? {
|
||||
Some(Value::String(s)) => Some(s.to_rust_string()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
|
||||
if let Value::String(s) = &value {
|
||||
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
|
||||
|
||||
+11
-7
@@ -203,9 +203,9 @@ struct Reading {
|
||||
ancestors: Vec<ObjId>,
|
||||
path: Vec<Step>,
|
||||
function: Rc<str>,
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under
|
||||
/// [`crate::FILE_REF_KEY`], and a plain object that has one of the keys, or
|
||||
/// [`crate::FOLDER_REF_KEY`], is refused.
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` or a `Folder` as its
|
||||
/// path under [`crate::FILE_REF_KEY`] or [`crate::FOLDER_REF_KEY`], and a plain object that has
|
||||
/// one of those keys is refused.
|
||||
hosted: bool,
|
||||
}
|
||||
|
||||
@@ -276,12 +276,16 @@ impl Interp {
|
||||
if r.ancestors.len() >= r.limits.depth {
|
||||
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
|
||||
}
|
||||
// A `File` reads as its path ([`crate::FILE_REF_KEY`]).
|
||||
// A `File` or a `Folder` reads as its path ([`crate::FILE_REF_KEY`], [`crate::FOLDER_REF_KEY`]).
|
||||
if r.hosted
|
||||
&& let Some(path) = crate::file_classes::file_path(self, id)?
|
||||
&& let Some(file) = self.file_ref_of(id)?
|
||||
{
|
||||
self.charge_reading(r, path.len().saturating_add(16))?;
|
||||
return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))]));
|
||||
let len: usize = match &file {
|
||||
Data::Object(items) => items.iter().map(|(_, v)| if let Data::String(p) = v { p.len() } else { 0 }).sum(),
|
||||
_ => 0,
|
||||
};
|
||||
self.charge_reading(r, len.saturating_add(16))?;
|
||||
return Ok(file);
|
||||
}
|
||||
let shape = match &self.object(id)?.class {
|
||||
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
|
||||
|
||||
@@ -29,7 +29,8 @@
|
||||
//!
|
||||
//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each
|
||||
//! member of its class and of the classes it descends from, apart from the members that are not
|
||||
//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members,
|
||||
//! available yet ([`HostMember::Unavailable`]). A member a class declares, available or not, hides
|
||||
//! the member of that name in the classes it descends from. `for`-`in` lists the properties among those members,
|
||||
//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and
|
||||
//! `Object.getOwnPropertyDescriptor` do not report the members.
|
||||
//!
|
||||
@@ -38,7 +39,7 @@
|
||||
//! told always matches what the class has. A class that names a member twice, or describes a member
|
||||
//! it does not have, is refused.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key};
|
||||
@@ -147,10 +148,9 @@ pub(crate) struct Entry {
|
||||
family: u32,
|
||||
/// The class this class's prototype inherits from, as an index into the realm's classes.
|
||||
parent: Option<u32>,
|
||||
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
|
||||
own: Rc<HashSet<Key>>,
|
||||
/// The names of the members this class declares as unavailable.
|
||||
unavailable: Rc<HashSet<Key>>,
|
||||
/// The names of the members the class declares, each with whether `hasOwnProperty` reports it:
|
||||
/// every member but the unavailable ones.
|
||||
own: Rc<HashMap<Key, bool>>,
|
||||
/// The class's own members as `reflect` lists them.
|
||||
members: Rc<[Reflected]>,
|
||||
}
|
||||
@@ -250,19 +250,15 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
|
||||
|
||||
impl Interp {
|
||||
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
|
||||
/// class, and `k` names an available member of that class or of a class it descends from. The
|
||||
/// nearest class that declares `k` decides, so a member a class declares unavailable is not
|
||||
/// reported even when a class it descends from has it.
|
||||
/// class, and the closest of that class and the classes it descends from that declares `k`
|
||||
/// declares it as available.
|
||||
pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(false) };
|
||||
let mut class = Some(h.class);
|
||||
while let Some(c) = class {
|
||||
let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) };
|
||||
if e.own.contains(k) {
|
||||
return Ok(true);
|
||||
}
|
||||
if e.unavailable.contains(k) {
|
||||
return Ok(false);
|
||||
if let Some(available) = e.own.get(k) {
|
||||
return Ok(*available);
|
||||
}
|
||||
class = e.parent;
|
||||
}
|
||||
@@ -589,7 +585,8 @@ fn install_checked(
|
||||
let v = i.write_hosted(d)?;
|
||||
undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?;
|
||||
}
|
||||
Ok(())
|
||||
// The prototypes, constructors and members are made without a reservation of their own.
|
||||
i.reserve_heap(0)
|
||||
}
|
||||
|
||||
/// Adds the global properties `globals`, each read with its getter and assigned with its setter as
|
||||
@@ -624,8 +621,7 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
|
||||
let r = fill_class(i, proto, &class);
|
||||
i.temp_roots.truncate(mark);
|
||||
let ctor = r?;
|
||||
let (unavailable, own_members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
|
||||
let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::<HashSet<Key>>();
|
||||
let own = class.members.iter().map(|(name, m)| (key(name), !matches!(m, HostMember::Unavailable(_)))).collect();
|
||||
i.host_classes.push(Entry {
|
||||
name: class.name.as_str().into(),
|
||||
proto,
|
||||
@@ -634,10 +630,14 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
|
||||
index: class.index,
|
||||
family,
|
||||
parent: parent_class,
|
||||
own: Rc::new(names(own_members)),
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
own: Rc::new(own),
|
||||
members,
|
||||
});
|
||||
// The host class named `Symbol` keeps the built-in `Symbol` global. Its objects use the host prototype.
|
||||
let global = i.global;
|
||||
if class.name == "Symbol" && i.get_own_property(global, &key(&class.name))?.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,31 @@ fn non_finite_indexer_keys_reach_the_host_unchanged() {
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_named_like_a_built_in_global_leaves_the_built_in() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let name: HostFunction = Rc::new(|_| Ok(Data::String("art".into())));
|
||||
let class = HostClass {
|
||||
name: "Symbol".into(),
|
||||
parent: None,
|
||||
members: vec![("name".into(), HostMember::Get(name))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Symbol", &[1.0]))]).unwrap();
|
||||
let source = "[typeof Symbol(), typeof Symbol.iterator, it.name, it instanceof Symbol].join('|')";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("symbol|symbol|art|false".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_replaces_an_existing_global_other_than_symbol() {
|
||||
let mut r = realm(1_000_000);
|
||||
let class = HostClass { name: "Math".into(), parent: None, members: vec![], info: Vec::new(), index: None, construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Math", &[1.0]))]).unwrap();
|
||||
assert_eq!(r.run("it instanceof Math && it.constructor === Math").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
|
||||
for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] {
|
||||
@@ -861,6 +886,31 @@ fn with_thing(r: &mut Realm, make: Option<HostFunction>) {
|
||||
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() {
|
||||
let mut r = realm(1_000_000);
|
||||
let interp = r.interp();
|
||||
interp.collect_garbage();
|
||||
interp.limits.heap_bytes = interp.heap.bytes;
|
||||
let class = HostClass { name: "Empty".into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: None };
|
||||
let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap));
|
||||
}
|
||||
|
||||
/// A new object of a host class adds its handle to the heap's total as well as itself, so objects
|
||||
/// made one after another count each other's handles before a collection does.
|
||||
#[test]
|
||||
fn an_object_of_a_host_class_counts_its_handle_toward_the_heap() {
|
||||
let mut r = realm(1_000_000);
|
||||
with_thing(&mut r, None);
|
||||
let interp = r.interp();
|
||||
let handle: Vec<f64> = (0..64).map(f64::from).collect();
|
||||
let before = interp.heap.bytes;
|
||||
interp.write_host_ref(&host_ref("Thing", &handle)).unwrap();
|
||||
let added = interp.heap.bytes - before;
|
||||
assert!(added >= crate::heap::OBJECT_BYTES + crate::host_classes::handle_bytes(handle.len()), "{added}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -1104,6 +1154,41 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_a_class_declares_hides_the_one_its_parent_declares() {
|
||||
let mut r = realm(1_000_000);
|
||||
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
|
||||
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
|
||||
let base = HostClass {
|
||||
name: "Base".into(),
|
||||
parent: None,
|
||||
members: vec![
|
||||
("size".to_string(), HostMember::Get(value.clone())),
|
||||
("later".to_string(), HostMember::Unavailable(missing.clone())),
|
||||
("kept".to_string(), HostMember::Get(value.clone())),
|
||||
],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let leaf = HostClass {
|
||||
name: "Leaf".into(),
|
||||
parent: Some("Base".into()),
|
||||
members: vec![("size".to_string(), HostMember::Unavailable(missing)), ("later".to_string(), HostMember::Get(value))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
|
||||
r.start(
|
||||
"var read; try { it.size; read = 'read'; } catch (e) { read = 'threw'; }\
|
||||
[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), read, it.hasOwnProperty('later'),\
|
||||
it.propertyIsEnumerable('later'), it.hasOwnProperty('kept')].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,threw,true,true,true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unavailable_member_hides_the_member_its_parent_class_has() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -18,6 +18,7 @@ use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -284,7 +285,15 @@ impl LiveBackend {
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } =
|
||||
cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
|
||||
// The router's own decision on the last lookup (it asks for consent, then makes the
|
||||
// headless session, under one lock), so the session's file access follows that decision.
|
||||
let agents_in = Arc::new(AtomicBool::new(false));
|
||||
let decided = Arc::clone(&agents_in);
|
||||
let consent = move |dir: &Path| {
|
||||
let consent = Consent::new(allowed(), read_settings(dir));
|
||||
decided.store(consent.allowed && consent.settings.allow_agent_control, Ordering::SeqCst);
|
||||
consent
|
||||
};
|
||||
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
|
||||
let mut window = Window::new(w.port, w.token.clone());
|
||||
window.connect()?;
|
||||
@@ -292,7 +301,9 @@ impl LiveBackend {
|
||||
};
|
||||
let make_headless = move |wanted: &HeadlessFolders| -> Result<SharedHeadless, String> {
|
||||
let roots = if wanted.read.is_empty() && wanted.write.is_none() {
|
||||
None
|
||||
// Agents the person let in are confined to the agent folders: when none can be
|
||||
// used (the default one can't be made), the session gets no file access.
|
||||
if agents_in.load(Ordering::SeqCst) { Some(AutomationRoots::none()) } else { None }
|
||||
} else {
|
||||
let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect();
|
||||
let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect();
|
||||
@@ -329,6 +340,10 @@ impl Backend for LiveBackend {
|
||||
matches!(self.live.resolve(), Ok(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn ui(&self) -> Result<bool, String> {
|
||||
Ok(matches!(self.live.resolve()?, Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window"
|
||||
.into()
|
||||
|
||||
@@ -13,6 +13,11 @@ pub trait Backend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String>;
|
||||
/// True when a real UI is attached (`ui.*` methods like `ui.key` / `ui.inspect` work).
|
||||
fn has_ui(&self) -> bool;
|
||||
/// Whether a real UI is attached, as [`Self::has_ui`], or why the backend could not reach the
|
||||
/// window (a launch that timed out, a failed handshake).
|
||||
fn ui(&self) -> Result<bool, String> {
|
||||
Ok(self.has_ui())
|
||||
}
|
||||
/// Short human description ("headless", "remote 127.0.0.1:7979").
|
||||
fn describe(&self) -> String;
|
||||
}
|
||||
|
||||
@@ -132,6 +132,21 @@ fn a_window_that_cannot_prove_the_token_gets_nothing() {
|
||||
assert_eq!(served.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
// A tool that needs the window reports why the window could not be reached, not that it is closed.
|
||||
#[test]
|
||||
fn a_ui_tool_reports_why_the_window_could_not_be_reached() {
|
||||
let dir = TempFolder::new("agents-ui-bad-token");
|
||||
let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
let r = crate::tools::call_tool(&mut b, "inspect_ui", &json!({}));
|
||||
assert!(r.is_error);
|
||||
let text = r.content[0]["text"].as_str().unwrap_or_default();
|
||||
assert!(text.contains("could not prove"), "{text}");
|
||||
assert!(!text.contains(crate::agents::NEEDS_WINDOW), "{text}");
|
||||
assert_eq!(served.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
|
||||
let dir = TempFolder::new("agents-stale");
|
||||
@@ -151,6 +166,35 @@ fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
}
|
||||
|
||||
// The agent folder can't be made (its parent is a file): the headless session the person chose for
|
||||
// a closed app gets no file access, rather than access to everything.
|
||||
#[test]
|
||||
fn a_headless_agent_session_without_usable_folders_reads_and_writes_nothing() {
|
||||
let dir = TempFolder::new("agents-no-folder");
|
||||
std::fs::write(dir.file("blocker"), b"").unwrap();
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("blocker").join("Agents"));
|
||||
assert!(!b.has_ui());
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_ne!(folders["unrestricted"], true, "{folders}");
|
||||
let outside = dir.file("outside.svg");
|
||||
std::fs::write(&outside, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="3"/>"#).unwrap();
|
||||
let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.contains("read authority is absent"), "{e}");
|
||||
let saved = dir.file("saved.svg");
|
||||
let e = b.call("app.save", json!({"path": saved.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.contains("write authority is absent"), "{e}");
|
||||
assert!(!saved.exists(), "the refused save must not write the file");
|
||||
|
||||
// With Allow Agent Control off, the session is the ordinary headless fallback, as before.
|
||||
fn control_off(dir: &Path) -> AgentSettings {
|
||||
let mut s = settings_headless(dir);
|
||||
s.allow_agent_control = false;
|
||||
s
|
||||
}
|
||||
let mut b = live(&dir, || true, control_off, dir.file("blocker").join("Agents"));
|
||||
assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true);
|
||||
}
|
||||
|
||||
/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix.
|
||||
fn shown(p: PathBuf) -> String {
|
||||
let s = p.to_string_lossy().into_owned();
|
||||
|
||||
@@ -418,6 +418,22 @@ fn alias_tools_name_their_pair() {
|
||||
assert!(description("ui_screenshot").contains("window:true"));
|
||||
}
|
||||
|
||||
/// answer_dialog's description gives the save-changes answers that docs/mcp.md gives: Don't Save
|
||||
/// sets `choice` and confirms in a second call, and `applyToAll` answers every waiting document.
|
||||
#[test]
|
||||
fn answer_dialog_describes_the_save_changes_answers() {
|
||||
let tools = tool_definitions();
|
||||
let description = tools.iter().find(|t| t["name"] == "answer_dialog").unwrap()["description"].as_str().unwrap().to_string();
|
||||
for snippet in [
|
||||
"app.quit, file.close or file.closeAll",
|
||||
r#"{set:[{field:"choice",value:"dontSave"}]} followed by a second call with {action:"confirm"}"#,
|
||||
r#"{field:"applyToAll",value:true}"#,
|
||||
] {
|
||||
assert!(description.contains(snippet), "answer_dialog's description is missing {snippet}: {description}");
|
||||
}
|
||||
assert!(!description.contains("discard"), "the save-changes dialog takes choice, not discard: {description}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conventions_tool_panics_are_tool_errors() {
|
||||
let mut s = Server::new(Box::new(Panics));
|
||||
|
||||
@@ -314,7 +314,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"answer_dialog",
|
||||
"Answer dialog",
|
||||
"Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none and answers that same dialog in the same request (ui.dialog.set with action). When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit or file.close replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"choice\",value:\"dontSave\"}],action:\"confirm\"} closes without saving, {action:\"cancel\"} cancels. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.",
|
||||
"Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none and answers that same dialog in the same request (ui.dialog.set with action). When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit, file.close or file.closeAll replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"choice\",value:\"dontSave\"}]} followed by a second call with {action:\"confirm\"} closes without saving, and {action:\"cancel\"} cancels the close or quit. choice takes save, dontSave or cancel; while more modified documents wait to be asked about, adding {field:\"applyToAll\",value:true} to set gives the same answer for each of them. Give set and action in separate calls for this question. The second call answers whichever dialog is open when it arrives. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.",
|
||||
obj(
|
||||
json!({
|
||||
"set": {
|
||||
|
||||
@@ -25,7 +25,8 @@ pub(super) fn exec(b: &mut dyn Backend, cmd: &str, params: Value) -> Result<Valu
|
||||
}
|
||||
|
||||
pub(super) fn need_ui(b: &dyn Backend, tool: &str) -> Result<(), String> {
|
||||
if b.has_ui() { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) }
|
||||
// A window that could not be reached says why, rather than that it isn't open.
|
||||
if b.ui()? { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) }
|
||||
}
|
||||
|
||||
/// Paint argument → `paint.setFill` / `paint.setStroke` params.
|
||||
|
||||
@@ -175,7 +175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"prefs.agents",
|
||||
"AI Integrations",
|
||||
"",
|
||||
"{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences",
|
||||
"{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's or a control client's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences",
|
||||
),
|
||||
("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"),
|
||||
(
|
||||
@@ -223,7 +223,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.shortcutImportDialog",
|
||||
"Import Shortcut Set…",
|
||||
"",
|
||||
"{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too",
|
||||
"{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded. The review opens inside Edit › Keyboard Shortcuts, which ui.inspect does not list in `dialogs` and ui.dialog.set does not reach; with a file the reply is {entries, unread}. Without the window, shortcutSet.read reads a file and matches its entries, and importMatches.set stores matches. Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too",
|
||||
),
|
||||
("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"),
|
||||
("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"),
|
||||
@@ -1030,7 +1030,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (listed last in ui.inspect's `dialogs`, with key null), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action (it also lists tab, more, goToKind, goToTarget and the read-only message), which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -1555,7 +1555,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -2003,7 +2003,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
@@ -2022,7 +2022,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.printPresetDialog",
|
||||
"Print Preset",
|
||||
"",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (listed last in ui.inspect's `dialogs`, with key null; fields: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets",
|
||||
),
|
||||
(
|
||||
"plugin.dialog",
|
||||
@@ -2106,7 +2106,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.checkScript",
|
||||
"Check Script…",
|
||||
"",
|
||||
"{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)",
|
||||
"{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (listed last in ui.inspect's `dialogs`, with key null; fields `lines`, `notes` and `groups`); with a file the reply is script.check's result, and the report's Copy button copies the report as text; without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)",
|
||||
),
|
||||
(
|
||||
"ui.perspectiveGridDialog",
|
||||
@@ -2234,6 +2234,11 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move",
|
||||
),
|
||||
("ui.findAndReplace", "Find and Replace…", "", "{} open the Find and Replace dialog (Edit › Find and Replace…; dialog `findReplace`)"),
|
||||
(
|
||||
"ui.findAndReplace",
|
||||
"Find and Replace…",
|
||||
"",
|
||||
"{} open the Find and Replace dialog (Edit › Find and Replace…; listed last in ui.inspect's `dialogs`, with key null; fields and buttons as ui.paramDialog with edit.findReplace)",
|
||||
),
|
||||
("ui.retype", "Retype", "", "{} open the Retype panel (Window › Retype) or start Retype"),
|
||||
];
|
||||
@@ -53,6 +53,8 @@ pub struct RasterExportOptions {
|
||||
pub quality: u8,
|
||||
/// WebP: lossless (`true`), or lossy at [`Self::quality`].
|
||||
pub webp_lossless: bool,
|
||||
/// WebP: the sRGB profile in an `ICCP` chunk.
|
||||
pub webp_embed_icc: bool,
|
||||
/// JPEG colour model, coding and profile.
|
||||
pub jpeg: jpeg::JpegOptions,
|
||||
/// PNG-8 and GIF: the colour reduction (also BMP's at 1, 4 and 8 bits).
|
||||
@@ -79,6 +81,7 @@ impl Default for RasterExportOptions {
|
||||
interlaced: false,
|
||||
quality: 90,
|
||||
webp_lossless: true,
|
||||
webp_embed_icc: true,
|
||||
jpeg: jpeg::JpegOptions::default(),
|
||||
palette: quantize::PaletteOptions::default(),
|
||||
tiff: tiff::TiffOptions::default(),
|
||||
@@ -128,7 +131,7 @@ impl RasterExportOptions {
|
||||
};
|
||||
jpeg::encode(&px, img.width, img.height, self.quality, Some(self.ppi), &self.jpeg)
|
||||
}
|
||||
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality)),
|
||||
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality), self.webp_embed_icc),
|
||||
RasterFormat::Png8 | RasterFormat::Gif => {
|
||||
let ix = quantize::quantize(&img.to_straight(), img.width, img.height, &self.palette);
|
||||
match format {
|
||||
@@ -188,8 +191,14 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] {
|
||||
}
|
||||
|
||||
/// WebP: lossless (`VP8L`) when `lossy_quality` is `None`, else lossy (`VP8 `, with an `ALPH`
|
||||
/// chunk when some pixels are not opaque) at that quality 0–100.
|
||||
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>, String> {
|
||||
/// chunk when some pixels are not opaque) at that quality 0–100. With `embed_icc` the file is
|
||||
/// extended (`VP8X`) and holds the sRGB profile in an `ICCP` chunk.
|
||||
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>, embed_icc: bool) -> Result<Vec<u8>, String> {
|
||||
let icc = if embed_icc {
|
||||
Some(vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).map_err(|e| format!("WebP colour profile: {e}"))?.to_vec())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let src = craft_image_codecs::Image::from_raw(
|
||||
img.width,
|
||||
img.height,
|
||||
@@ -197,10 +206,12 @@ pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
img.to_straight(),
|
||||
)
|
||||
.map_err(|e| format!("WebP encoding failed: {e}"))?;
|
||||
.map_err(|e| format!("WebP encoding failed: {e}"))?
|
||||
.with_icc(icc);
|
||||
let opts = craft_image_codecs::EncodeOptions {
|
||||
webp_lossless: lossy_quality.is_none(),
|
||||
webp_quality: lossy_quality.unwrap_or(100).min(100),
|
||||
embed_icc,
|
||||
..craft_image_codecs::EncodeOptions::default()
|
||||
};
|
||||
let file = craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}"))?;
|
||||
|
||||
@@ -220,9 +220,10 @@ fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
|
||||
#[test]
|
||||
fn lossy_webp_keeps_transparent_pixels_transparent() {
|
||||
let d = circle_doc();
|
||||
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &RasterExportOptions::default()).unwrap();
|
||||
let no_icc = RasterExportOptions { webp_embed_icc: false, ..Default::default() };
|
||||
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &no_icc).unwrap();
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..Default::default() };
|
||||
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..no_icc };
|
||||
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
let img = export(&d, RasterFormat::WebP, &o);
|
||||
@@ -236,6 +237,35 @@ fn lossy_webp_keeps_transparent_pixels_transparent() {
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
}
|
||||
|
||||
/// The payload of the first chunk of type `ty` in RIFF WebP `file`.
|
||||
fn webp_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> &'a [u8] {
|
||||
let at = chunk_offset(file, ty);
|
||||
let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().unwrap()) as usize;
|
||||
&file[at + 8..at + 8 + len]
|
||||
}
|
||||
|
||||
/// By default a WebP file, lossless or lossy, holds the sRGB profile in an `ICCP` chunk that its
|
||||
/// `VP8X` header flags, and a decoder reads the profile back; with `webp_embed_icc` off it holds
|
||||
/// none.
|
||||
#[test]
|
||||
fn webp_embeds_the_srgb_profile_unless_told_not_to() {
|
||||
let d = circle_doc();
|
||||
let srgb = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap();
|
||||
for lossless in [true, false] {
|
||||
let o = RasterExportOptions { webp_lossless: lossless, ..Default::default() };
|
||||
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
|
||||
let chunks = webp_chunks(&file);
|
||||
assert_eq!(chunks[..2], [*b"VP8X", *b"ICCP"], "lossless {lossless}: {chunks:?}");
|
||||
assert_ne!(webp_chunk(&file, b"VP8X")[0] & 0x20, 0, "lossless {lossless}: the VP8X ICC flag");
|
||||
assert_eq!(webp_chunk(&file, b"ICCP"), &*srgb, "lossless {lossless}");
|
||||
let mut dec = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&file)).unwrap();
|
||||
assert_eq!(image::ImageDecoder::icc_profile(&mut dec).unwrap().as_deref(), Some(&*srgb), "lossless {lossless}");
|
||||
let off = RasterExportOptions { webp_embed_icc: false, ..o };
|
||||
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &off).unwrap();
|
||||
assert!(!webp_chunks(&file).contains(b"ICCP"), "lossless {lossless}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A lossy frame's tag (RFC 6386 §9.1) holds its first partition's size in 19 bits. A frame whose
|
||||
/// size field is at that limit may hold a larger partition, so it is refused; frames below it
|
||||
/// decode with another decoder at every quality, a 1 × 1 image and transparent pixels included.
|
||||
|
||||
@@ -424,7 +424,7 @@ impl Rendered {
|
||||
}
|
||||
/// Encode as lossless WebP.
|
||||
pub fn to_webp(&self) -> Result<Vec<u8>, String> {
|
||||
encode::webp(self, None)
|
||||
encode::webp(self, None, false)
|
||||
}
|
||||
/// Straight-alpha RGBA at (x, y).
|
||||
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
|
||||
|
||||
@@ -27,7 +27,10 @@ use crate::catalog::{self, FeatureId};
|
||||
use crate::directives;
|
||||
use crate::lex::{Lexer, T, Token, expr_after};
|
||||
use crate::report::{self, Acc, OutsideId};
|
||||
use sig::{COMPOUND, LineBreaks, NEWER, Read, Sig, ends_value, for_in, goes_on_after, goes_on_with, is, member_mark, newer_number, unquote, word};
|
||||
use sig::{
|
||||
COMPOUND, LineBreaks, NEWER, Read, Sig, ends_value, exact_unquote, for_in, goes_on_after, goes_on_with, is, member_mark, newer_number, unquote,
|
||||
word,
|
||||
};
|
||||
|
||||
mod declared;
|
||||
mod features;
|
||||
@@ -691,6 +694,18 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
|
||||
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
|
||||
writers: HashMap<String, u8>,
|
||||
/// The variables a function body read before any literal gave them methods, in a way that
|
||||
/// changes or shares them ([`Analyzer::writer_use`]): the body may run after the literal (a
|
||||
/// hoisted declaration), so the literal's methods are not the script's own. Each name has the
|
||||
/// most function bodies that were open where it was read; a literal in a body with that many
|
||||
/// open or more is unaffected, since it gives a variable of its own.
|
||||
shared_early: HashMap<String, usize>,
|
||||
/// [`Analyzer::shared_early`] had no room for a name: no literal gives methods that are the
|
||||
/// script's own from then on.
|
||||
shared_full: bool,
|
||||
/// The function body that the token being read closed (its `}`): how many bodies were open
|
||||
/// in it and the names it declared. A value read just before the `}` is read in that body.
|
||||
closed_body: Option<(usize, Vec<String>)>,
|
||||
/// The object literals being assigned to a variable, the innermost last, up to
|
||||
/// [`crate::Limits::nesting`] of them.
|
||||
objects: Vec<ObjectValue>,
|
||||
@@ -700,6 +715,29 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
|
||||
/// that is not such a variable.
|
||||
index_receiver: u8,
|
||||
/// Whether that receiver's own methods hold at this place ([`Analyzer::stable`]).
|
||||
index_stable: bool,
|
||||
/// The depths of the open `[` that index the global object (`$.global[`, `this[`,
|
||||
/// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them.
|
||||
global_indexes: Vec<usize>,
|
||||
/// The last token was the `]` that closes an index of the global object.
|
||||
global_index_closed: bool,
|
||||
/// The offset of the last `]` that closes an index of the global object by a string literal
|
||||
/// alone, with the variable name it reads (`$.global['local']`, `this['local']`), or `None` when
|
||||
/// the literal does not decode to one exact name.
|
||||
global_bracket: Option<(usize, Option<String>)>,
|
||||
/// The offset of the last name read as a property of the global object (`local` in
|
||||
/// `$.global.local`, `globalThis.local` or `this.local`).
|
||||
global_member: Option<usize>,
|
||||
/// The `with` statement whose head is being read: the bracket depth of its `with`, and whether
|
||||
/// its `)` was read.
|
||||
with_head: Option<(usize, bool)>,
|
||||
/// The bracket depths the bodies of the open `with` statements hold at, the innermost last, up
|
||||
/// to [`crate::Limits::nesting`] of them ([`Analyzer::with_step`]).
|
||||
withs: Vec<usize>,
|
||||
/// A `with` statement had no room in [`Analyzer::withs`]: no call of a literal's own method is
|
||||
/// known from then on.
|
||||
withs_full: bool,
|
||||
/// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`].
|
||||
others: bool,
|
||||
/// The variables that may get another value when code read elsewhere runs: assigned inside a
|
||||
@@ -786,9 +824,20 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(),
|
||||
maybe_files_full: false,
|
||||
writers: HashMap::new(),
|
||||
shared_early: HashMap::new(),
|
||||
shared_full: false,
|
||||
closed_body: None,
|
||||
objects: vec![],
|
||||
closed: None,
|
||||
index_receiver: 0,
|
||||
index_stable: false,
|
||||
global_indexes: vec![],
|
||||
global_index_closed: false,
|
||||
global_bracket: None,
|
||||
global_member: None,
|
||||
with_head: None,
|
||||
withs: vec![],
|
||||
withs_full: false,
|
||||
others: known.others || declared.includes,
|
||||
later: HashSet::new(),
|
||||
later_full: false,
|
||||
@@ -872,6 +921,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
|
||||
fn token(&mut self, mut t: Sig<'s>) {
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
self.closed_body = None;
|
||||
// The name of a grouped value whose last `)` was read, or of a value without parentheses that
|
||||
// `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or
|
||||
// closes a function body.
|
||||
@@ -1195,7 +1245,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// in them gets back what it held outside them, and the `var` statement a body was in goes on.
|
||||
fn close_scopes(&mut self) {
|
||||
while self.scopes.last().is_some_and(|s| self.depth() < s.depth) {
|
||||
let open = self.scopes.len();
|
||||
let Some(scope) = self.scopes.pop() else { return };
|
||||
if self.closed_body.is_none() {
|
||||
self.closed_body = Some((open, scope.saved.keys().cloned().collect()));
|
||||
}
|
||||
self.var_depth = scope.var_depth;
|
||||
for (name, saved) in scope.saved {
|
||||
self.restore(name, saved);
|
||||
@@ -1491,6 +1545,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
{
|
||||
let h1 = self.h[1];
|
||||
let declared = word(h1, "var") || (is(h1, ",") && self.var_depth.is_some());
|
||||
if !declared && !member_mark(h1) && !is(h1, "@") {
|
||||
self.share_early(name.text);
|
||||
}
|
||||
if declared {
|
||||
if self.in_catch(name.text) {
|
||||
self.declare_in_catch(name.text);
|
||||
@@ -1507,13 +1564,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
|
||||
}
|
||||
}
|
||||
if let Some((name, _)) = self.updated(t)
|
||||
&& !self.scopes.is_empty()
|
||||
&& !self.declared_in_body(name)
|
||||
{
|
||||
self.reassigned_later(name);
|
||||
let updated = self.updated(t);
|
||||
if let Some((name, _)) = updated {
|
||||
self.share_early(name);
|
||||
if !self.scopes.is_empty() && !self.declared_in_body(name) {
|
||||
self.reassigned_later(name);
|
||||
}
|
||||
}
|
||||
match self.updated(t) {
|
||||
match updated {
|
||||
// The value on the right is read at this depth, and the name holds nothing the check
|
||||
// follows once that value ends ([`Analyzer::settle_groups`]).
|
||||
Some((name, true)) => self.start_value(name.to_string(), Operand::Other),
|
||||
@@ -1527,19 +1585,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// closes a function body, so a literal given to the body's own variable stays inside the body.
|
||||
/// No variable joins when code the scan does not follow at that point may give it another value:
|
||||
/// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a
|
||||
/// member assignment of a property of that name, which may be the global object's
|
||||
/// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of
|
||||
/// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
|
||||
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
|
||||
/// function body read before the literal that changes or shares the variable, or assigns a property
|
||||
/// of that name, which may be the global object's ([`Analyzer::shared_early`]), code given as text
|
||||
/// or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
|
||||
/// assigns the variable use [`Declared::looped`] to classify its methods.
|
||||
fn settle_literal(&mut self, t: &Sig<'s>) {
|
||||
if let Some((name, bits)) = self.closed.take()
|
||||
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
|
||||
&& !self.shared_full
|
||||
&& self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len())
|
||||
&& !self.unsure
|
||||
&& !self.others
|
||||
&& !self.declared.rebound.contains(&name)
|
||||
&& !self.declared.body_assigned.contains(name.as_str())
|
||||
&& !self.declared.body_writer_assigned
|
||||
&& !self.later_full
|
||||
&& !self.later.contains(&name)
|
||||
&& !self.declared.looped_full
|
||||
@@ -1586,8 +1643,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing
|
||||
/// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the
|
||||
/// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on
|
||||
/// (`{…} && d`), see the variable as it was.
|
||||
/// (`{…} && d`), see the variable as it was. A `this` or the variable's own name inside the body
|
||||
/// of such a function expression takes the method out as well: running it may replace the
|
||||
/// object's methods (`{saveAs: function () { this.saveAs = d.saveAs; }}`).
|
||||
fn object_key(&mut self, t: &Sig<'s>, before: usize) {
|
||||
if t.kind == T::Ident {
|
||||
for o in self.objects.iter_mut().filter(|o| o.depth < before) {
|
||||
if let Some((bit, Value::Body)) = o.value
|
||||
&& (t.text == "this" || t.text == o.name)
|
||||
{
|
||||
o.value = Some((bit, Value::Other));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) {
|
||||
o.step(t);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{
|
||||
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark,
|
||||
unquote, word,
|
||||
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, exact_unquote, for_in, goes_on_after, goes_on_with, is,
|
||||
member_mark, unquote, word,
|
||||
};
|
||||
|
||||
/// The names that give variables values the analysis doesn't read: a `with` statement makes an
|
||||
@@ -76,11 +76,16 @@ pub(crate) struct Declared<'s> {
|
||||
/// also before its body in the text when it is a declaration, so a variable of that name may lose
|
||||
/// the value an assignment the analysis read gave it.
|
||||
pub(super) body_assigned: HashSet<&'s str>,
|
||||
/// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`]
|
||||
/// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is
|
||||
/// defined, and the object may be any variable's, so no variable's method of that name stays
|
||||
/// the script's own.
|
||||
pub(super) body_writer_assigned: bool,
|
||||
/// The variables whose document write method a function body may replace (`local.saveAs = …`,
|
||||
/// `local['saveAs'] += …`, `local[k] = …`, `var y = local`), unless the body declared the name
|
||||
/// before it, each by the offset of the `{` of the function body that declares it anywhere in
|
||||
/// the body (`None`: the global code's). The function may run at any time after it is defined,
|
||||
/// also before its body in the text when it is a declaration.
|
||||
pub(super) method_replaced: HashSet<(Option<usize>, &'s str)>,
|
||||
/// The variables of [`Declared::method_replaced`] whose declaring body is not known, because a
|
||||
/// body around the replacement is past [`crate::Limits::nesting`] or ran out of room for its
|
||||
/// names: the replacement counts for a variable of that name in any body.
|
||||
pub(super) method_replaced_any: HashSet<&'s str>,
|
||||
/// The file has an `#include` line: the included file's code may give its variables values.
|
||||
pub(super) includes: bool,
|
||||
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
|
||||
@@ -139,6 +144,9 @@ struct Declarations<'s, 'a, 'l> {
|
||||
brackets: Brackets,
|
||||
/// The three significant tokens before this one, the latest first.
|
||||
h: [Option<Sig<'s>>; 3],
|
||||
/// The two significant tokens before the three of `h`, the latest first.
|
||||
h3: Option<Sig<'s>>,
|
||||
h4: Option<Sig<'s>>,
|
||||
/// `function` was read at this bracket depth, and its body's `{` is still to come.
|
||||
function: Option<usize>,
|
||||
/// The bracket depth of the `var` statement being read.
|
||||
@@ -155,6 +163,20 @@ struct Declarations<'s, 'a, 'l> {
|
||||
keys: Vec<Key>,
|
||||
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
|
||||
loops: Vec<Loop>,
|
||||
/// The replacements of a variable's methods ([`Declared::method_replaced`]) read so far, each with
|
||||
/// the entries of [`Declared::bodies`] around it, the outermost first. A `var` statement later in
|
||||
/// a body declares the name for the whole body, so the body that declares the variable is found
|
||||
/// once every body's names are known.
|
||||
replaced: HashSet<(Vec<usize>, &'s str)>,
|
||||
/// The entries of [`Declared::bodies`] whose names ran out of room: one of them may declare any
|
||||
/// name.
|
||||
names_full: HashSet<usize>,
|
||||
/// The parameters of the function whose parentheses are being read: the bracket depth inside
|
||||
/// them, the names so far, and whether they ran out of room.
|
||||
params: Option<(usize, Vec<&'s str>, bool)>,
|
||||
/// The parameters of each entry of [`Declared::bodies`], which are the body's own variables
|
||||
/// (ECMA-262 3rd edition, section 10.1.3).
|
||||
body_params: HashMap<usize, Vec<&'s str>>,
|
||||
out: Declared<'s>,
|
||||
}
|
||||
|
||||
@@ -200,6 +222,8 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
acc,
|
||||
brackets: Brackets::default(),
|
||||
h: [None; 3],
|
||||
h3: None,
|
||||
h4: None,
|
||||
function: None,
|
||||
var_depth: None,
|
||||
assign: None,
|
||||
@@ -207,6 +231,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
untracked: None,
|
||||
keys: vec![],
|
||||
loops: vec![],
|
||||
replaced: HashSet::new(),
|
||||
names_full: HashSet::new(),
|
||||
params: None,
|
||||
body_params: HashMap::new(),
|
||||
out: Declared::default(),
|
||||
};
|
||||
let mut breaks = LineBreaks::default();
|
||||
@@ -221,6 +249,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
while let Some(body) = d.bodies.pop() {
|
||||
d.settle_looped(body);
|
||||
}
|
||||
d.settle_replaced();
|
||||
let mut out = d.out;
|
||||
for ids in out.looped.values_mut() {
|
||||
ids.sort_unstable();
|
||||
@@ -255,6 +284,17 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
self.bracket(&t);
|
||||
} else if t.kind == T::Ident {
|
||||
self.declaration(&t);
|
||||
let depth = self.depth();
|
||||
if let Some((at, names, full)) = self.params.as_mut()
|
||||
&& *at == depth
|
||||
&& (is(h0, "(") || is(h0, ","))
|
||||
{
|
||||
if self.acc.room(names.len()) {
|
||||
names.push(t.text);
|
||||
} else {
|
||||
*full = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let depth = self.depth();
|
||||
self.loop_end(&t, depth);
|
||||
@@ -266,6 +306,27 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
{
|
||||
self.looped(name.text);
|
||||
}
|
||||
// `o.local = …` or `o['local'] = …` in a loop: the object may be the global object
|
||||
// ([`Declared::rebound`]), so the global variable of that name may get another value on each
|
||||
// pass. A key with an escape may spell any name: any variable may be assigned in a loop.
|
||||
if t.is("=") && !self.loops.is_empty() {
|
||||
let property = if member_mark(h1) {
|
||||
h0.filter(|s| s.kind == T::Ident).map(|s| s.text)
|
||||
} else if is(h0, "]") && is(self.h[2], "[") {
|
||||
let key = h1.filter(|s| s.kind == T::Str);
|
||||
if key.is_some_and(|s| s.text.contains('\\')) {
|
||||
self.out.looped_full = true;
|
||||
}
|
||||
key.filter(|s| s.text.len() >= 2 && !s.text.contains('\\')).and_then(|s| s.text.get(1..s.text.len() - 1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = property {
|
||||
let id = self.out.loop_spans.len().saturating_sub(1);
|
||||
self.keep_looped(None, name, vec![id]);
|
||||
}
|
||||
}
|
||||
self.method_replacement(&t);
|
||||
if let Some(after_new) = self.assign.take() {
|
||||
if t.word("new") && !after_new {
|
||||
self.assign = Some(true);
|
||||
@@ -289,9 +350,123 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if !self.bodies.is_empty() || self.untracked.is_some() {
|
||||
self.body_assignment(&t, depth);
|
||||
}
|
||||
self.h4 = self.h3;
|
||||
self.h3 = self.h[2];
|
||||
self.h = [Some(t), h0, h1];
|
||||
}
|
||||
|
||||
/// `t` changes or shares a variable's methods, as [`Analyzer::writer_use`] reads it: `=`, a
|
||||
/// compound operator, `++` or `--` on `local.saveAs` or `local['saveAs']` (one of the document
|
||||
/// write methods), `++local.saveAs`, a key in brackets that is not one string literal
|
||||
/// (`local[k]`, `local['sa' + 'veAs']`), `delete local`, or `local` used as a value
|
||||
/// (`var y = local`, `f(local)`), where another name may hold its object. In a loop, `local` may
|
||||
/// hold another method when a call of it earlier in the loop runs again ([`Declared::looped`]); in
|
||||
/// a function body that does not declare `local`, the function may replace the method before any
|
||||
/// call of it runs ([`Declared::method_replaced`]).
|
||||
fn method_replacement(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, h2] = self.h;
|
||||
let (h3, h4) = (self.h3, self.h4);
|
||||
let ident = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident && !member_mark(before));
|
||||
let write = |s: Option<Sig<'s>>| s.is_some_and(|s| s.kind == T::Ident && catalog::DOM_FILE_WRITES.contains(&s.text));
|
||||
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
|
||||
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
|
||||
let receiver = if changes && is(h1, ".") && write(h0) {
|
||||
ident(h2, h3)
|
||||
} else if changes
|
||||
&& is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(key) = h1.filter(|s| s.kind == T::Str)
|
||||
{
|
||||
// A key whose escapes do not decode to one exact name may spell any method's.
|
||||
let writes = exact_unquote(key.text).is_none_or(|m| catalog::DOM_FILE_WRITES.contains(&m.as_str()));
|
||||
ident(h3, h4).filter(|_| writes)
|
||||
} else if is(h0, ".") && (is(h2, "++") || is(h2, "--")) && write(Some(*t)) && (h2.is_some_and(|s| s.nl) || !h1.is_some_and(|s| s.nl)) {
|
||||
// `++local.saveAs`, not `n++` ending the line before `local.saveAs`.
|
||||
ident(h1, h2)
|
||||
} else if word(h0, "delete") {
|
||||
ident(Some(*t), h0)
|
||||
} else if let Some(name) = ident(h0, h1).filter(|_| !t.is(".") && !t.is("[") && !t.is("=") && !key) {
|
||||
// `local` used as a value, or changed by a compound or update operator.
|
||||
Some(name)
|
||||
} else if is(h0, "[") {
|
||||
// `local[k]`: a key that is not one string or number literal may name any method.
|
||||
ident(h1, h2).filter(|_| t.kind != T::Str && t.kind != T::Number)
|
||||
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str || s.kind == T::Number) {
|
||||
// `local['sa' + k]`
|
||||
ident(h2, h3).filter(|_| !t.is("]"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(name) = receiver.map(|s| s.text) else { return };
|
||||
if !self.loops.is_empty() {
|
||||
self.looped(name);
|
||||
}
|
||||
// Only the innermost body's own variable is not the one a nested function may reach from
|
||||
// outside before the call runs.
|
||||
let own = self.untracked.is_none()
|
||||
&& self.bodies.last().is_some_and(|b| b.names.contains(name) || self.body_params.get(&b.index).is_some_and(|p| p.contains(&name)));
|
||||
if (!self.bodies.is_empty() || self.untracked.is_some()) && !own {
|
||||
if self.untracked.is_some() {
|
||||
// A body past the nesting limit keeps no names, so any body around may declare the
|
||||
// variable.
|
||||
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
|
||||
self.out.method_replaced_any.insert(name);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
} else {
|
||||
let key = (self.bodies.iter().map(|b| b.index).collect::<Vec<_>>(), name);
|
||||
if self.replaced.contains(&key) || self.acc.room(self.replaced.len()) {
|
||||
self.replaced.insert(key);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps each replacement in [`Self::replaced`] for the innermost body around it that declares
|
||||
/// the variable anywhere in the body, or as a parameter, or for the global code when none does.
|
||||
/// A replacement of a variable of the innermost body itself is not kept, as when the body
|
||||
/// declared it before the replacement. When a body around it ran out of room for its names, the
|
||||
/// body that declares the variable is not known, and the replacement counts for the variable of
|
||||
/// that name in every body ([`Declared::method_replaced_any`]).
|
||||
fn settle_replaced(&mut self) {
|
||||
for (around, name) in std::mem::take(&mut self.replaced) {
|
||||
let mut owner = None;
|
||||
let mut known = true;
|
||||
for (i, &index) in around.iter().enumerate().rev() {
|
||||
if self.out.bodies.get(index).is_some_and(|(_, names)| names.contains(&name))
|
||||
|| self.body_params.get(&index).is_some_and(|p| p.contains(&name))
|
||||
{
|
||||
owner = self.out.bodies.get(index).map(|(at, _)| (*at, i + 1 == around.len()));
|
||||
break;
|
||||
}
|
||||
if self.names_full.contains(&index) {
|
||||
known = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
|
||||
self.out.method_replaced_any.insert(name);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if owner.is_some_and(|(_, innermost)| innermost) {
|
||||
continue;
|
||||
}
|
||||
let key = (owner.map(|(at, _)| at), name);
|
||||
if self.out.method_replaced.contains(&key) || self.acc.room(self.out.method_replaced.len()) {
|
||||
self.out.method_replaced.insert(key);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one
|
||||
/// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`].
|
||||
fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) {
|
||||
@@ -557,9 +732,6 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
None
|
||||
};
|
||||
if let Some(name) = property {
|
||||
if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) {
|
||||
self.out.body_writer_assigned = true;
|
||||
}
|
||||
if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) {
|
||||
self.out.rebound.insert(name);
|
||||
} else {
|
||||
@@ -579,7 +751,11 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
match t.text {
|
||||
"(" | "[" | "{" => {
|
||||
let body = t.text == "{" && self.function.take() == Some(self.depth());
|
||||
let params = t.text == "(" && self.function == Some(self.depth());
|
||||
self.brackets.open(t, self.acc.limits.nesting);
|
||||
if params {
|
||||
self.params = Some((self.depth(), vec![], false));
|
||||
}
|
||||
if t.text == "[" {
|
||||
// After a value, `[` starts a property's name in brackets (ECMA-262 3rd
|
||||
// edition, section 11.2.1); elsewhere it starts an array literal.
|
||||
@@ -593,8 +769,17 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if !body {
|
||||
return;
|
||||
}
|
||||
let params = self.params.take();
|
||||
if self.bodies.len() < self.acc.limits.nesting {
|
||||
let index = self.out.bodies.len();
|
||||
if let Some((_, names, full)) = params {
|
||||
if full {
|
||||
self.names_full.insert(index);
|
||||
}
|
||||
if !names.is_empty() {
|
||||
self.body_params.insert(index, names);
|
||||
}
|
||||
}
|
||||
self.out.bodies.push((t.start, vec![]));
|
||||
self.bodies.push(Body {
|
||||
depth: self.depth(),
|
||||
@@ -652,10 +837,14 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
return;
|
||||
}
|
||||
if let Some(body) = self.bodies.last_mut() {
|
||||
if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) {
|
||||
body.names.insert(t.text);
|
||||
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
|
||||
names.push(t.text);
|
||||
if (var || body.depth == depth) && !body.names.contains(t.text) {
|
||||
if self.acc.room(body.names.len()) {
|
||||
body.names.insert(t.text);
|
||||
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
|
||||
names.push(t.text);
|
||||
}
|
||||
} else {
|
||||
self.names_full.insert(body.index);
|
||||
}
|
||||
}
|
||||
} else if function && depth == 0 && !self.out.global.contains(t.text) && self.acc.room(self.out.global.len()) {
|
||||
|
||||
@@ -1,6 +1,36 @@
|
||||
//! The platform features, menu commands and later syntax the analysis recognises.
|
||||
|
||||
use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word};
|
||||
use super::{
|
||||
Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, exact_unquote, is, member_mark, newer_number, report, unquote, word,
|
||||
};
|
||||
|
||||
/// Words that start or continue a statement or an expression, never a variable's name.
|
||||
const RESERVED: [&str; 24] = [
|
||||
"var",
|
||||
"function",
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"do",
|
||||
"return",
|
||||
"new",
|
||||
"typeof",
|
||||
"delete",
|
||||
"in",
|
||||
"instanceof",
|
||||
"this",
|
||||
"with",
|
||||
"switch",
|
||||
"case",
|
||||
"try",
|
||||
"catch",
|
||||
"finally",
|
||||
"throw",
|
||||
"break",
|
||||
"continue",
|
||||
"void",
|
||||
];
|
||||
|
||||
/// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…).
|
||||
pub(super) fn platform_name(n: &str) -> bool {
|
||||
@@ -85,6 +115,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.with_step(t);
|
||||
self.writer_use(t);
|
||||
match t.kind {
|
||||
T::Ident => self.name(t, line),
|
||||
@@ -292,7 +323,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
|
||||
"[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)),
|
||||
"[" => {
|
||||
self.index_receiver = self.writer_bits(h0, h1, Some(t.start));
|
||||
self.index_stable = h0.is_some_and(|r| self.stable(r.text));
|
||||
}
|
||||
"(" => self.call(t, line),
|
||||
// `Name.prototype["+"] = …` defines an operator.
|
||||
"=" => {
|
||||
@@ -338,15 +372,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
chain.and_then(|c| c.path.strip_suffix(called))
|
||||
}
|
||||
|
||||
/// `(` after a name: a call.
|
||||
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
/// What the call whose `(` is the current token reaches.
|
||||
fn classify_call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
// `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
|
||||
if is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
{
|
||||
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name))
|
||||
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !(self.index_stable && Self::defines(self.index_receiver, &name)))
|
||||
|| (name == catalog::DOM_PRINT && self.document_print("[]()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
@@ -388,7 +422,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
{
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
} else if (file && catalog::FILE_WRITES.contains(&n))
|
||||
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
|
||||
|| (catalog::DOM_FILE_WRITES.contains(&n)
|
||||
&& !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)))
|
||||
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
@@ -413,6 +448,113 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a call of `name`'s own method may be left out: the call is in the global code, or in a
|
||||
/// function body that declares `name` itself. A body that reads `name` from outside may run
|
||||
/// after the variable was given another value, so its calls are not known. Inside the body of a
|
||||
/// `with` statement the name may be a property of the statement's object, so no call is known
|
||||
/// there ([`Analyzer::with_step`]).
|
||||
fn stable(&self, name: &str) -> bool {
|
||||
!self.withs_full && self.withs.is_empty() && self.scopes.last().is_none_or(|s| s.saved.contains_key(name))
|
||||
}
|
||||
|
||||
/// Follows the `with` statements around `t`. A body in braces ends with its `}`; a body without
|
||||
/// braces is taken to last until the block the statement is in closes.
|
||||
fn with_step(&mut self, t: &Sig<'s>) {
|
||||
let depth = self.depth();
|
||||
self.withs.retain(|d| *d <= depth);
|
||||
match self.with_head {
|
||||
Some((d, false)) if t.is(")") && depth == d => self.with_head = Some((d, true)),
|
||||
Some((d, true)) => {
|
||||
self.with_head = None;
|
||||
let body = if t.is("{") { depth } else { d };
|
||||
if self.withs.len() < self.acc.limits.nesting {
|
||||
self.withs.push(body);
|
||||
} else {
|
||||
self.withs_full = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if t.kind == T::Ident && t.text == "with" && !member_mark(self.h[0]) {
|
||||
self.with_head = Some((depth, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` may have been given another value through the global object: neither the variable
|
||||
/// nor the outer variables of that name that the open function bodies and `catch` blocks keep
|
||||
/// to put back hold their literal's methods any longer.
|
||||
fn forget_writer(&mut self, name: &str) {
|
||||
self.writers.remove(name);
|
||||
for s in &mut self.scopes {
|
||||
if let Some(saved) = s.saved.get_mut(name) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
}
|
||||
for c in self.catches.iter_mut().filter(|c| c.name == name) {
|
||||
c.saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The global variable `name` read through the global object may be held under another name
|
||||
/// ([`Self::forget_writer`]). A variable of that name that the innermost function body or a
|
||||
/// `catch` block declares is another variable, and keeps its literal's methods.
|
||||
fn forget_global_writer(&mut self, name: &str) {
|
||||
let shadowed = self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) || self.catches.iter().any(|c| c.name == name);
|
||||
if !shadowed {
|
||||
self.forget_writer(name);
|
||||
return;
|
||||
}
|
||||
for s in &mut self.scopes {
|
||||
if let Some(saved) = s.saved.get_mut(name) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
}
|
||||
for c in self.catches.iter_mut().filter(|c| c.name == name) {
|
||||
c.saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Any variable may have been given another value through the global object
|
||||
/// ([`Self::forget_writer`] for every name).
|
||||
fn forget_writers(&mut self) {
|
||||
self.writers.clear();
|
||||
for saved in self.scopes.iter_mut().flat_map(|s| s.saved.values_mut()) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
for c in &mut self.catches {
|
||||
c.saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// A function body uses `name`, which no literal has given methods and the body does not declare,
|
||||
/// in a way that may change or share it ([`Analyzer::shared_early`]). With no room left for the
|
||||
/// name, no literal's methods are the script's own from then on.
|
||||
pub(super) fn share_early(&mut self, name: &str) {
|
||||
self.share_early_as(name, false);
|
||||
}
|
||||
|
||||
/// [`Analyzer::share_early`], and with `global` set, for the global variable `name` read through
|
||||
/// the global object (`$.global.local`) even when the body declares a variable of that name.
|
||||
fn share_early_as(&mut self, name: &str, global: bool) {
|
||||
// A value read just before the `}` that closes a function body is read in that body.
|
||||
let (open, declared) = match &self.closed_body {
|
||||
Some((open, names)) => (*open, names.iter().any(|n| n == name)),
|
||||
None => match self.scopes.last() {
|
||||
Some(body) => (self.scopes.len(), body.saved.contains_key(name)),
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
if (declared && !global) || self.writers.contains_key(name) {
|
||||
return;
|
||||
}
|
||||
if self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()) {
|
||||
let seen = self.shared_early.entry(name.to_string()).or_insert(open);
|
||||
*seen = (*seen).max(open);
|
||||
} else {
|
||||
self.shared_full = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `receiver`, which `before` comes before, is the application object: the name `app`
|
||||
/// that no `.` comes before and that the script has not declared as its own.
|
||||
fn app_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
|
||||
@@ -430,9 +572,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
|
||||
return 0;
|
||||
}
|
||||
// A function body that replaces the method may run before the call, wherever it is in
|
||||
// the text. The replacement is kept for the body that declares the variable: the
|
||||
// innermost body around the call that declares it, or the global code.
|
||||
let looped = at.is_some_and(|at| {
|
||||
let owner = self.scopes.iter().rev().find(|s| s.saved.get(r.text).is_some_and(|v| v.local)).map(|s| s.start);
|
||||
self.declared.looped_full
|
||||
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
|
||||
|| self.declared.method_replaced_any.contains(r.text)
|
||||
|| self.declared.method_replaced.contains(&(owner, r.text))
|
||||
|| self.declared.looped.get(&(owner, r.text)).is_some_and(|ids| {
|
||||
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
|
||||
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
|
||||
})
|
||||
@@ -447,9 +595,39 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
|
||||
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
|
||||
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
|
||||
/// `local[k] = w`, `delete local.saveAs`).
|
||||
/// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's
|
||||
/// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global
|
||||
/// object, so its methods are no longer known either. An assignment to a property of the global
|
||||
/// object under any other key (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may give any such
|
||||
/// variable a new value: no variable's methods are known after it.
|
||||
fn writer_use(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
let global_index_closed = std::mem::take(&mut self.global_index_closed);
|
||||
if t.kind == T::Ident
|
||||
&& is(h0, ".")
|
||||
&& ((word(h1, "global") && is(h2, ".") && word(h3, "$") && !member_mark(self.h4))
|
||||
|| ((word(h1, "this") || word(h1, "globalThis")) && !member_mark(h2)))
|
||||
{
|
||||
self.global_member = Some(t.start);
|
||||
}
|
||||
if t.is("[") {
|
||||
let global = (word(h0, "global") && is(h1, ".") && word(h2, "$") && !member_mark(h3))
|
||||
|| ((word(h0, "this") || word(h0, "globalThis")) && !member_mark(h1));
|
||||
if global && self.global_indexes.len() < self.acc.limits.nesting {
|
||||
self.global_indexes.push(self.depth());
|
||||
}
|
||||
} else if t.is("]") {
|
||||
let depth = self.depth();
|
||||
self.global_index_closed = self.global_indexes.last() == Some(&(depth + 1));
|
||||
self.global_indexes.retain(|d| *d <= depth);
|
||||
// `$.global['local']` or `this['local']`: the `]` reads the global variable `local`.
|
||||
if self.global_index_closed
|
||||
&& is(h1, "[")
|
||||
&& let Some(key) = h0.filter(|s| s.kind == T::Str)
|
||||
{
|
||||
self.global_bracket = Some((t.start, exact_unquote(key.text)));
|
||||
}
|
||||
}
|
||||
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
|
||||
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
|
||||
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
|
||||
@@ -468,31 +646,166 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.reassigned_global(&name);
|
||||
}
|
||||
}
|
||||
let h4 = self.h4;
|
||||
// `$.global.local`, `globalThis.local` or `this.local`: `h2` names the global variable `local`.
|
||||
let global_member = h2.is_some_and(|s| self.global_member == Some(s.start));
|
||||
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
|
||||
let escaped = if word(h0, "delete") {
|
||||
// `delete local…`
|
||||
writer(Some(*t), h0)
|
||||
} else if let Some(name) = writer(h0, h1) {
|
||||
// `local` followed by anything but a member, its own assignment or an object key's `:`.
|
||||
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
|
||||
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
|
||||
// `local.saveAs = …`
|
||||
writer(h2, h3)
|
||||
} else if is(h0, "[") {
|
||||
// `local[k]` with a key that is not a string literal.
|
||||
writer(h1, h2).filter(|_| t.kind != T::Str)
|
||||
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
|
||||
// `local['name' + k]`.
|
||||
writer(h2, h3).filter(|_| !t.is("]"))
|
||||
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
|
||||
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
|
||||
writer(h3, self.h4)
|
||||
let escape = |writer: &dyn Fn(Option<Sig<'s>>, Option<Sig<'s>>) -> Option<&'s str>| -> Option<&'s str> {
|
||||
if word(h0, "delete") {
|
||||
// `delete local…`
|
||||
writer(Some(*t), h0)
|
||||
} else if let Some(name) = writer(h0, h1) {
|
||||
// `local` followed by anything but a member, its own assignment or an object key's `:`.
|
||||
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
|
||||
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
|
||||
// `local.saveAs = …` or `$.global.local.saveAs = …`
|
||||
writer(h2, if global_member { None } else { h3 })
|
||||
} else if is(h0, "[") {
|
||||
// `local[k]` with a key that is not a string literal.
|
||||
writer(h1, h2).filter(|_| t.kind != T::Str)
|
||||
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
|
||||
// `local['name' + k]`.
|
||||
writer(h2, h3).filter(|_| !t.is("]"))
|
||||
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
|
||||
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
|
||||
writer(h3, h4)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let escaped = escape(&writer);
|
||||
// A function body reads a variable of the enclosing code that no literal has given methods yet
|
||||
// in a way that changes or shares it: the body may run after the literal, as a hoisted
|
||||
// declaration does.
|
||||
let early = if escaped.is_none() && !self.scopes.is_empty() {
|
||||
let captured = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| {
|
||||
s.filter(|s| {
|
||||
s.kind == T::Ident
|
||||
&& !member_mark(before)
|
||||
&& !self.writers.contains_key(s.text)
|
||||
&& self.scopes.last().is_some_and(|b| !b.saved.contains_key(s.text))
|
||||
})
|
||||
.map(|s| s.text)
|
||||
};
|
||||
escape(&captured)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = escaped {
|
||||
self.writers.remove(name);
|
||||
}
|
||||
if let Some(name) = early {
|
||||
self.share_early(name);
|
||||
}
|
||||
// `$.global['local']` or `this['local']` used as a value (`var alias = $.global['local']`,
|
||||
// `f(this['local'])`): another name may hold the global variable's object.
|
||||
if !changes
|
||||
&& !t.is(".")
|
||||
&& !t.is("[")
|
||||
&& let Some((_, name)) = self.global_bracket.as_ref().filter(|(at, _)| h0.is_some_and(|s| s.start == *at))
|
||||
{
|
||||
match name.clone() {
|
||||
Some(name) => {
|
||||
self.forget_global_writer(&name);
|
||||
self.share_early_as(&name, true);
|
||||
}
|
||||
None => self.forget_writers(),
|
||||
}
|
||||
}
|
||||
// `$.global.local`, `this.local` or `globalThis.local` used as a value (`var alias = this.local`),
|
||||
// not `holder.local`: another name may hold the global variable's object.
|
||||
if !changes
|
||||
&& !t.is(".")
|
||||
&& !t.is("[")
|
||||
&& let Some(m) = h0.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start))
|
||||
{
|
||||
self.forget_global_writer(m.text);
|
||||
self.share_early_as(m.text, true);
|
||||
}
|
||||
// A document write method of a global variable replaced through a bracket form:
|
||||
// `$.global['local'].saveAs = …`, `this['local']['saveAs'] = …` or `$.global.local['saveAs'] = …`.
|
||||
if changes {
|
||||
let write_key = |s: Option<Sig<'s>>| s.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str()));
|
||||
let bracketed =
|
||||
|s: Option<Sig<'s>>| s.and_then(|s| self.global_bracket.as_ref().filter(|(at, _)| *at == s.start).map(|(_, name)| name.clone()));
|
||||
let global = if is(h1, ".") && h0.is_some_and(|m| m.kind == T::Ident) && write_key(h0) {
|
||||
bracketed(h2)
|
||||
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|m| m.kind == T::Str) && write_key(h1) {
|
||||
bracketed(h3).or_else(|| h3.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start)).map(|s| Some(s.text.to_string())))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match global {
|
||||
// The global variable's value may be saved under a body's or a `catch`'s own variable of
|
||||
// that name, so forget every value of the name.
|
||||
Some(Some(name)) => {
|
||||
self.forget_writer(&name);
|
||||
self.share_early_as(&name, true);
|
||||
}
|
||||
// A key that does not decode to one exact name may name any variable.
|
||||
Some(None) => self.forget_writers(),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
// A name read in a function body that the body does not declare, as a receiver or otherwise. A
|
||||
// receiver is settled once its member is read: assigning a property that is not one of the
|
||||
// document methods that write a file (`d.n = 1`) leaves its methods as they are.
|
||||
if let Some(r) = h0.filter(|r| r.kind == T::Ident && !member_mark(h1) && !RESERVED.contains(&r.text) && !t.is(".")) {
|
||||
self.share_early(r.text);
|
||||
}
|
||||
if let Some(r) = h2.filter(|r| is(h1, ".") && r.kind == T::Ident && (!member_mark(h3) || global_member) && !RESERVED.contains(&r.text)) {
|
||||
let own_property = t.is("=") && h0.is_some_and(|m| m.kind == T::Ident && !catalog::DOM_FILE_WRITES.contains(&m.text));
|
||||
if !own_property {
|
||||
self.share_early_as(r.text, global_member);
|
||||
}
|
||||
}
|
||||
if changes {
|
||||
// A member assignment of a property `local` (`o.local = …`, `o['local'] = …`): the object may
|
||||
// be the global object (`this`, `globalThis`, `$.global`, or any object holding it, as
|
||||
// `holder.this`), so the variable of that name may get another value.
|
||||
let rebound = if is(h1, ".") {
|
||||
h0.filter(|s| s.kind == T::Ident).map(|s| Some(s.text.to_string()))
|
||||
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|s| s.kind == T::Str) {
|
||||
h1.filter(|s| s.kind == T::Str).map(|s| exact_unquote(s.text))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(Some(name)) = rebound {
|
||||
// In a function body: the function may run after a later literal gives the name methods.
|
||||
if !self.scopes.is_empty() {
|
||||
self.reassigned_later(&name);
|
||||
}
|
||||
self.forget_writer(&name);
|
||||
} else if global_index_closed || rebound.is_some() {
|
||||
// `$.global[key] = …`, or a key that does not decode to one exact name: the key may
|
||||
// name any of them.
|
||||
self.forget_writers();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `(` after a name: a call ([`Self::classify_call`]). A call of a variable of
|
||||
/// [`Analyzer::writers`]'s method other than the `saveAs` or `exportFile` its literal defines
|
||||
/// (`local.install()`, `local['install']()`) may replace the object's methods through `this`, so
|
||||
/// after the call they are no longer known.
|
||||
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
let bits = self.writer_bits(h2, h3, None);
|
||||
let receiver = if is(h1, ".") && bits != 0 && h0.is_some_and(|s| s.kind == T::Ident && !Self::defines(bits, s.text)) {
|
||||
h2
|
||||
} else if is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& self.index_receiver != 0
|
||||
&& h1.is_some_and(|s| s.kind == T::Str && !Self::defines(self.index_receiver, &unquote(s.text, 32)))
|
||||
{
|
||||
h3
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.classify_call(t, line);
|
||||
if let Some(r) = receiver {
|
||||
self.writers.remove(r.text);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
|
||||
|
||||
@@ -135,6 +135,34 @@ pub(super) fn newer_number(text: &str) -> bool {
|
||||
text.contains('_') || (b.len() > 1 && b.last() == Some(&b'n')) || matches!((b.first(), b.get(1)), (Some(b'0'), Some(b'b' | b'B' | b'o' | b'O')))
|
||||
}
|
||||
|
||||
/// A string literal's whole value ([`unquote`] without a length limit), or `None` when an escape
|
||||
/// does not decode to exactly one character: a `\x` without two hex digits, a `\u` without four
|
||||
/// (`\u{63}` included), or a code unit that is not a character on its own.
|
||||
pub(super) fn exact_unquote(text: &str) -> Option<String> {
|
||||
let b = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'\\' {
|
||||
let digits = match b.get(i + 1) {
|
||||
Some(b'x') => 2,
|
||||
Some(b'u') => 4,
|
||||
_ => 0,
|
||||
};
|
||||
if digits > 0 {
|
||||
let hex = b.get(i + 2..i + 2 + digits).filter(|d| d.iter().all(u8::is_ascii_hexdigit))?;
|
||||
// A surrogate code unit (`\uD800` to `\uDFFF`) is not a character on its own.
|
||||
if digits == 4 && matches!(hex[0], b'd' | b'D') && matches!(hex[1], b'8'..=b'9' | b'a'..=b'f' | b'A'..=b'F') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Some(unquote(text, text.chars().count()))
|
||||
}
|
||||
|
||||
/// A string literal's value, its quotes removed and its escapes undone (`\n`, `\xHH`, `\uHHHH`,
|
||||
/// octal escapes, a backslash before a line break), up to `max` characters.
|
||||
pub(super) fn unquote(text: &str, max: usize) -> String {
|
||||
|
||||
@@ -76,8 +76,10 @@ pub(crate) const REFLECT: &str = "reflect";
|
||||
// The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
|
||||
pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"];
|
||||
|
||||
// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/
|
||||
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs"];
|
||||
// Document methods that write the file they are given, or files in the folder they are given:
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
|
||||
// https://www.indesignjs.de/indesignapi/illustrator/Document.html (exportForScreens)
|
||||
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs", "exportForScreens"];
|
||||
// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
|
||||
pub(crate) const DOM_FILE_READS: &[&str] = &["open"];
|
||||
|
||||
|
||||
@@ -19,6 +19,20 @@ fn feature<'r>(r: &'r Report, id: &str) -> Option<&'r Feature> {
|
||||
r.features.iter().find(|f| f.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_changes_text_requires_enumeration_member_context() {
|
||||
for source in ["vc.log('SAVECHANGES');", "var text = 'SAVECHANGES';", "other['SAVECHANGES'];"] {
|
||||
let r = report(source);
|
||||
assert!(feature(&r, "file.write").is_none(), "{source}");
|
||||
assert!(!r.outside.iter().any(|outside| outside.id == "filesWritten"), "{source}");
|
||||
}
|
||||
for source in ["SaveOptions['SAVECHANGES'];", "'SaveOptions.SAVECHANGES';"] {
|
||||
let r = report(source);
|
||||
assert!(feature(&r, "file.write").is_some(), "{source}");
|
||||
assert!(r.outside.iter().any(|outside| outside.id == "filesWritten"), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
fn problems(r: &Report) -> Vec<(&'static str, Option<usize>, Option<&str>)> {
|
||||
r.problems.iter().map(|p| (p.code, p.line, p.detail.as_deref())).collect()
|
||||
}
|
||||
@@ -588,6 +602,21 @@ fn export_variables_in_brackets_writes_a_file() {
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
|
||||
/// A document's `exportForScreens` writes files into the folder it is given, called directly or by
|
||||
/// its name in brackets; an object of the script's own that defines it writes nothing.
|
||||
#[test]
|
||||
fn export_for_screens_writes_files() {
|
||||
let r = report(concat!(
|
||||
"var dir = new Folder(p);\n",
|
||||
"app.activeDocument.exportForScreens(dir, ExportForScreensType.SE_PNG24);\n",
|
||||
"documents[0]['exportForScreens'](dir, ExportForScreensType.SE_SVG);\n",
|
||||
"var local = {exportForScreens: function () {}};\n",
|
||||
"local.exportForScreens(dir);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[2, 3][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
|
||||
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
|
||||
@@ -912,6 +941,627 @@ fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..]));
|
||||
}
|
||||
|
||||
/// A call of another method of such an object may replace its `saveAs` through `this`, and a property
|
||||
/// assignment that names the variable (`this.local = d`) may give it another value through the global
|
||||
/// object: after either, its `saveAs` writes the file again.
|
||||
#[test]
|
||||
fn a_method_call_or_a_global_property_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}, install: function () { this.saveAs = app.activeDocument.saveAs; }};\n",
|
||||
"var b = {saveAs: function () {}, install: function () {}};\n",
|
||||
"var c = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f); a.install();\n",
|
||||
"b['install']();\n",
|
||||
"this.c = app.activeDocument;\n",
|
||||
"$.global['e'] = app.activeDocument;\n",
|
||||
"g.saveAs(f); g.saveAs(f);\n",
|
||||
"a.saveAs(f);\n",
|
||||
"b.saveAs(f);\n",
|
||||
"c.saveAs(f);\n",
|
||||
"e.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..]));
|
||||
}
|
||||
|
||||
/// An assignment to a property under a key that is not one string literal may give any such variable
|
||||
/// another value through the global object, so every `saveAs` of such a variable writes the file,
|
||||
/// before the assignment too.
|
||||
#[test]
|
||||
fn a_computed_global_property_ends_every_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"var rows = [];\n",
|
||||
"rows[k] = 1; $.global['b'] = app.activeDocument;\n",
|
||||
"a.saveAs(f);\n",
|
||||
"$.global[key] = app.activeDocument;\n",
|
||||
"a.saveAs(f);\n",
|
||||
"var c = {saveAs: function () {}};\n",
|
||||
"this['lo' + 'cal'] = app.activeDocument;\n",
|
||||
"c.saveAs(f);\n",
|
||||
"var h = {saveAs: function () {}};\n",
|
||||
"globalThis[names[0]] = app.activeDocument;\n",
|
||||
"h.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 7, 10, 13][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 7, 10, 13][..])]);
|
||||
}
|
||||
|
||||
/// A `saveAs` whose body uses `this` or the variable's own name may replace the object's methods
|
||||
/// when it runs, so it is not the script's own and its calls write the file. A `this` in another
|
||||
/// method's body leaves `saveAs` the script's own.
|
||||
#[test]
|
||||
fn an_own_save_as_that_may_replace_itself_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var doc = app.activeDocument;\n",
|
||||
"var a = {saveAs: function () { this.saveAs = function (g) { doc.saveAs(g); }; }};\n",
|
||||
"var b = {saveAs: function () { b.saveAs = w; }};\n",
|
||||
"var c = {saveAs: function (g) { return g; }, install: function () { this.n = 1; }};\n",
|
||||
"a.saveAs(f);\n",
|
||||
"a.saveAs(f);\n",
|
||||
"b.saveAs(f);\n",
|
||||
"c.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7, 8][..]));
|
||||
}
|
||||
|
||||
/// A loop that replaces a variable's `saveAs` (`local.saveAs = …`, `local['saveAs'] = …`) may run a
|
||||
/// call of it before the replacement in the text on a later pass: the call writes a file. A loop
|
||||
/// that only calls the method, or replaces it on another object, leaves it the script's own.
|
||||
#[test]
|
||||
fn an_own_save_as_replaced_later_in_a_loop_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (;;) { local.saveAs(f); local.saveAs = g; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"while (n--) { other.saveAs(f); other['saveAs'] = g; }\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"for (;;) { calm.saveAs(f); holder.calm.saveAs = g; }\n",
|
||||
"for (;;) { calm.saveAs(f); }\n",
|
||||
"for (;;) { calm.saveAs(f); holder.calm['saveAs'] = g; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
|
||||
}
|
||||
|
||||
/// A function declared after a call is hoisted, so it may replace the variable's `saveAs` before the
|
||||
/// call runs: the call writes a file. A function that only calls the method, or replaces it on a
|
||||
/// variable of its own, leaves it the script's own.
|
||||
#[test]
|
||||
fn a_hoisted_function_declared_later_that_replaces_the_method_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"install();\n",
|
||||
"function install() { local.saveAs = app.activeDocument.saveAs; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function swap(w) { other['saveAs'] = w; }\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"calm.saveAs(f);\n",
|
||||
"function d() { calm.saveAs(f); }\n",
|
||||
"function e() { var calm = {}; calm.saveAs = 1; }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"third.saveAs(f);\n",
|
||||
"function h(w) { third['save\\x41s'] = w; }\n",
|
||||
"function run() {\n",
|
||||
" var mine = {saveAs: function () {}};\n",
|
||||
" fix(); mine.saveAs(f);\n",
|
||||
" function fix() { mine.saveAs = app.activeDocument.saveAs; }\n",
|
||||
"}\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 7, 11, 14, 18][..]));
|
||||
}
|
||||
|
||||
/// A hoisted function declared after a call may also replace the variable's `saveAs` under a key
|
||||
/// the check can't read (`local[k] = w`, `local['sa' + 've' + 'As'] = w`), with a compound or update
|
||||
/// operator (`local.saveAs += w`, `local['saveAs']++`, `++local.saveAs`), or through another name
|
||||
/// that holds the object (`var y = local; y.saveAs = w`, `give(local)`): the call writes a file. The
|
||||
/// same holds in a loop, where the replacement may run before the call on a later pass.
|
||||
#[test]
|
||||
fn a_method_replaced_by_a_computed_key_an_operator_or_an_alias_ends_the_own_save_as() {
|
||||
let head = "var f = new File(p);\nvar local = {saveAs: function () {}};\n";
|
||||
let mut wrong = vec![];
|
||||
for (tail, lines) in [
|
||||
("local.saveAs(f);\nfunction h(w, k) { local[k] = w; }\n", &[3][..]),
|
||||
("local.saveAs(f);\nfunction h(w) { local['sa' + 've' + 'As'] = w; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h(w) { local.saveAs += w; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { local['saveAs']++; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { local.saveAs--; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { ++local.saveAs; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h(w) { var y = local; y.saveAs = w; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { give(local); }\n", &[3]),
|
||||
("for (;;) { local.saveAs(f); local[k] = w; }\n", &[3]),
|
||||
("for (;;) { local.saveAs(f); local.saveAs += w; }\n", &[3]),
|
||||
("for (;;) { local.saveAs(f); var z = local; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { local.saveAs(f); local['name'] = 1; }\n", &[4]),
|
||||
("local.saveAs(f);\nfunction h() { return local[0]; }\n", &[]),
|
||||
] {
|
||||
let r = report(&format!("{head}{tail}"));
|
||||
if feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()) != lines || r.truncated {
|
||||
wrong.push((tail, feature(&r, "file.write").map(|f| f.lines.clone())));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// A function that replaces a variable's `saveAs` may stand before the `var` statement that declares
|
||||
/// the variable in the body around it, since `var` declares the name for the whole body: the call
|
||||
/// after the literal writes a file. A function whose own later `var` declares the name replaces
|
||||
/// the method on its own variable, which leaves the outer one the script's own.
|
||||
#[test]
|
||||
fn a_method_replaced_before_the_hoisted_var_that_declares_it_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function run() {\n",
|
||||
" function fix() { give(mine); }\n",
|
||||
" var mine = {saveAs: function () {}};\n",
|
||||
" mine.saveAs(f);\n",
|
||||
"}\n",
|
||||
"function late() {\n",
|
||||
" mine2 = {saveAs: function () {}};\n",
|
||||
" mine2.saveAs(f);\n",
|
||||
" function fix() { give(mine2); }\n",
|
||||
" var mine2;\n",
|
||||
"}\n",
|
||||
"function deep() {\n",
|
||||
" held = {saveAs: function () {}};\n",
|
||||
" held.saveAs(f);\n",
|
||||
" function a() { function b() { held.saveAs = w; } }\n",
|
||||
" var held;\n",
|
||||
"}\n",
|
||||
"function calm() {\n",
|
||||
" var quiet = {saveAs: function () {}};\n",
|
||||
" function g(w) { give(quiet); var quiet; }\n",
|
||||
" quiet.saveAs(f);\n",
|
||||
"}\n",
|
||||
"function own() {\n",
|
||||
" give(mine3);\n",
|
||||
" var mine3 = {saveAs: function () {}};\n",
|
||||
" mine3.saveAs(f);\n",
|
||||
"}\n",
|
||||
"function par() {\n",
|
||||
" function fix(mine4) { mine4.saveAs = w; }\n",
|
||||
" var mine4 = {saveAs: function () {}};\n",
|
||||
" mine4.saveAs(f);\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function h(a, local) { return local; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9, 15][..]));
|
||||
}
|
||||
|
||||
/// A call inside a nested function on a variable of the body around it, whose `saveAs` another
|
||||
/// function replaces, writes a file: the replacement is looked up for the body that declares the
|
||||
/// variable, not for the innermost body.
|
||||
#[test]
|
||||
fn a_call_in_a_nested_function_on_a_replaced_outer_variable_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function run() {\n",
|
||||
" var mine = {saveAs: function () {}};\n",
|
||||
" function use() { mine.saveAs(f); }\n",
|
||||
" function fix(w) { give(mine); }\n",
|
||||
"}\n",
|
||||
"var top = {saveAs: function () {}};\n",
|
||||
"function use2() { var other = 1; top.saveAs(f); }\n",
|
||||
"function fix2(w) { give(top); }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 8][..]));
|
||||
}
|
||||
|
||||
/// A global variable read through the global object as a value (`$.global.local`, `this.local`,
|
||||
/// `globalThis.local`) may be held under another name, also by a hoisted function declared before
|
||||
/// the literal: the variable's `saveAs` writes a file.
|
||||
#[test]
|
||||
fn a_global_member_used_as_a_value_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function a() { var alias = $.global.local; alias.saveAs = app.activeDocument.saveAs; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"var held = this.other;\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function b() { use(globalThis.third); }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"third.saveAs(f);\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"use(holder.calm);\n",
|
||||
"calm.saveAs(f);\n",
|
||||
"function g() { var mine = {saveAs: function () {}}; var alias = $.global.mine; mine.saveAs(f); }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..]));
|
||||
}
|
||||
|
||||
/// A function declared before the literal is hoisted, so it may change or share the variable before
|
||||
/// the literal's later calls run: its calls then keep reporting the write. A function with a
|
||||
/// variable of its own of the same name, and one that only calls the method, leave the method the
|
||||
/// script's own.
|
||||
#[test]
|
||||
fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function a(w) { local.saveAs = w; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function b() { use(other); }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function c() { var calm = app.activeDocument; use(calm); }\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"calm.saveAs(f);\n",
|
||||
"function d() { quiet.saveAs(f); }\n",
|
||||
"var quiet = {saveAs: function () {}};\n",
|
||||
"quiet.saveAs(f);\n",
|
||||
"function g1() { use(mine); }\n",
|
||||
"function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11, 13][..]));
|
||||
}
|
||||
|
||||
/// A function body that declares the variable's name itself can still give the variable another
|
||||
/// value through the global object: the variable's methods are not put back when the body closes.
|
||||
/// A body that only declares the name leaves the methods the script's own.
|
||||
#[test]
|
||||
fn a_global_assignment_under_a_shadowing_declaration_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function replace() { var local = 1; $.global.local = app.activeDocument; }\n",
|
||||
"replace();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"function keep() { var calm = 1; }\n",
|
||||
"keep();\n",
|
||||
"calm.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
}
|
||||
|
||||
/// An assignment under a computed key of the global object may give any variable another value, so
|
||||
/// after one anywhere in the file every call is reported.
|
||||
#[test]
|
||||
fn a_computed_global_assignment_ends_every_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"function any() { var other = 1; $.global[k] = app.activeDocument; }\n",
|
||||
"any();\n",
|
||||
"other.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
}
|
||||
|
||||
/// A function declared before the literal may run after it and give the variable another value
|
||||
/// through any form of a global object property: `$.global.name`, `globalThis.name` and
|
||||
/// `$.global['name']`. The literal's later calls keep reporting the write. An assignment in the
|
||||
/// global code runs once, before a later literal, and leaves that literal's methods the script's own.
|
||||
#[test]
|
||||
fn a_hoisted_global_property_assignment_ends_a_later_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function replace() { $.global.local = app.activeDocument; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"replace();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function swap() { globalThis.other = app.activeDocument; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"swap();\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function put() { $.global['third'] = app.activeDocument; }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"put();\n",
|
||||
"third.saveAs(f);\n",
|
||||
"$.global.fresh = 1;\n",
|
||||
"var fresh = {saveAs: function () {}};\n",
|
||||
"fresh.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9, 13][..]));
|
||||
}
|
||||
|
||||
/// Inside the body of a `with` statement a name may be a property of the statement's object, so a
|
||||
/// call of a literal's method there is reported. A `with` statement also gives names values the
|
||||
/// check does not read, so the calls after its body are reported too.
|
||||
#[test]
|
||||
fn a_call_inside_a_with_body_is_not_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"with ({local: app.activeDocument}) {\n",
|
||||
" local.saveAs(f);\n",
|
||||
"}\n",
|
||||
"local.saveAs(f);\n",
|
||||
"if (x) { with (o) local.saveAs(f); }\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6, 7, 8][..]));
|
||||
}
|
||||
|
||||
/// A table of shared names with no room left for one more means a function may share any name: no
|
||||
/// literal after it gives methods that are the script's own.
|
||||
#[test]
|
||||
fn a_full_table_of_shared_names_keeps_reporting_the_write() {
|
||||
let src = concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function a(w) { p1.saveAs = w; p2.saveAs = w; p3.saveAs = w; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
);
|
||||
let r = check("test.jsx", src.as_bytes(), None, &Limits { entries: 2, ..Limits::default() });
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
|
||||
}
|
||||
|
||||
/// A function body that assigns a variable it does not declare (`=`, a compound operator, `++` or
|
||||
/// `--`) may run after the literal and give the variable another value.
|
||||
#[test]
|
||||
fn an_assignment_in_a_hoisted_function_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function a(w) { local = w; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function b() { other += 1; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function c() { third++; }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"third.saveAs(f);\n",
|
||||
"function e() { --fourth; }\n",
|
||||
"var fourth = {saveAs: function () {}};\n",
|
||||
"fourth.saveAs(f);\n",
|
||||
"function d() { var mine = 1; mine = 2; }\n",
|
||||
"var mine = {saveAs: function () {}};\n",
|
||||
"mine.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10, 13][..]));
|
||||
}
|
||||
|
||||
/// A function body that calls a method of, or reads, a variable it does not declare may run before
|
||||
/// the literal as well, so a later literal's calls keep reporting the write.
|
||||
#[test]
|
||||
fn a_member_call_or_read_in_a_hoisted_function_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function a() { local.run(); }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function b() { other['m'](); }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function c() { return third.name; }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"third.saveAs(f);\n",
|
||||
"function d() { var calm = 1; return calm.name; }\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"calm.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..]));
|
||||
}
|
||||
|
||||
/// A function that reads the variable from outside runs after whatever the script gave it since, so
|
||||
/// its calls keep reporting the write. A `var` after a label or a `case` is in a branch as well.
|
||||
#[test]
|
||||
fn a_captured_or_labelled_own_save_as_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function run() { local.saveAs(f); }\n",
|
||||
"function run2() { local['saveAs'](f); }\n",
|
||||
"local = app.activeDocument;\n",
|
||||
"run();\n",
|
||||
"function own() { var inner = {saveAs: function () {}}; inner.saveAs(f); inner['saveAs'](f); }\n",
|
||||
"if (flag) skip:\n",
|
||||
"var lab = {saveAs: function () {}};\n",
|
||||
"lab.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4, 10][..]));
|
||||
}
|
||||
|
||||
/// A property assignment in a loop may give the global variable of that name another value on the
|
||||
/// next pass, so a call on it in the same loop may write a file.
|
||||
#[test]
|
||||
fn a_property_assignment_in_a_loop_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) {\n",
|
||||
" local.saveAs(f);\n",
|
||||
" $.global.local = app.activeDocument;\n",
|
||||
"}\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"for (var j = 0; j < 2; j++) {\n",
|
||||
" other.saveAs(f);\n",
|
||||
" $.global['other'] = app.activeDocument;\n",
|
||||
"}\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9][..]));
|
||||
// The property names the global variable, not a function's own variable of the same name.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function g() {\n",
|
||||
" var local = {saveAs: function () {}};\n",
|
||||
" for (var i = 0; i < 2; i++) { local.saveAs(f); $.global.local = app.activeDocument; }\n",
|
||||
"}\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), None);
|
||||
// A key with an escape may name the variable.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) { local.saveAs(f); $.global['lo\\u0063al'] = app.activeDocument; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
// Hex escapes and a line continuation in the key.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) { local.saveAs(f); this['lo\\x63\\\n",
|
||||
"al'] = app.activeDocument; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
// A key longer than 256 characters names the variable of that whole name.
|
||||
let long = "v".repeat(300);
|
||||
let r = report(&format!(
|
||||
"var f = new File(p);\nvar {long} = {{saveAs: function () {{}}}};\nfor (var i = 0; i < 2; i++) {{ {long}.saveAs(f); $.global['{long}'] = app.activeDocument; }}\n"
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
let r = report(&format!("var f = new File(p);\nvar {long} = {{saveAs: function () {{}}}};\n$.global['{long}'].saveAs = w;\n{long}.saveAs(f);\n"));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
|
||||
// A key whose escape does not decode to one exact name may name any variable.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"this['lo\\u{63}al'] = app.activeDocument;\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var kept = {saveAs: function () {}};\n",
|
||||
"$.global['k\\uD800'].saveAs = w;\n",
|
||||
"kept.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
|
||||
}
|
||||
|
||||
/// A function that replaces a method through the global object's property (`$.global.local.saveAs`)
|
||||
/// changes the variable's methods, as `local.saveAs = …` does.
|
||||
#[test]
|
||||
fn a_method_replaced_through_the_global_object_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install() {\n",
|
||||
" $.global.local.saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var mine = {saveAs: function () {}};\n",
|
||||
"globalThis.mine.saveAs = w;\n",
|
||||
"mine.saveAs(f);\n",
|
||||
"function install2() { var kept; $.global.kept.saveAs = w; }\n",
|
||||
"var kept = {saveAs: function () {}};\n",
|
||||
"install2();\n",
|
||||
"kept.saveAs(f);\n",
|
||||
"var safe = {saveAs: function () {}};\n",
|
||||
"holder.global.safe.saveAs = w;\n",
|
||||
"safe.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9, 12, 16][..]));
|
||||
}
|
||||
|
||||
/// Bracket forms of the global object's property (`$.global['local'].saveAs`, `this['local'].saveAs`,
|
||||
/// `$.global.local['saveAs']`) change the variable's methods, as the dot forms do.
|
||||
#[test]
|
||||
fn a_method_replaced_through_a_bracketed_global_member_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install() {\n",
|
||||
" $.global['local'].saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var mine = {saveAs: function () {}};\n",
|
||||
"this['mine'].saveAs = w;\n",
|
||||
"mine.saveAs(f);\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"$.global.third['saveAs'] = w;\n",
|
||||
"third.saveAs(f);\n",
|
||||
"var fourth = {saveAs: function () {}};\n",
|
||||
"globalThis['fourth']['saveAs'] = w;\n",
|
||||
"fourth.saveAs(f);\n",
|
||||
"var safe = {saveAs: function () {}};\n",
|
||||
"holder.global['safe'].saveAs = w;\n",
|
||||
"safe.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9, 12, 15, 18][..]));
|
||||
// A body's own variable of the same name does not keep the global variable's methods.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function g() { var local = {saveAs: function () {}}; $.global['local'].saveAs = w; }\n",
|
||||
"g();\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
}
|
||||
|
||||
/// A bracketed read of the global variable used as a value (`var alias = $.global['local']`) shares
|
||||
/// its object, so a later literal's `saveAs` is not the script's own.
|
||||
#[test]
|
||||
fn a_bracketed_global_member_used_as_a_value_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install() {\n",
|
||||
" var alias = $.global['local'];\n",
|
||||
" alias.saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var safe = {saveAs: function () {}};\n",
|
||||
"var other = holder['safe'];\n",
|
||||
"safe.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 10][..]));
|
||||
}
|
||||
|
||||
/// A hoisted function body whose last value, read without a `;` before its closing `}`, is the
|
||||
/// variable shares it with its caller, as one that ends with `;` does.
|
||||
#[test]
|
||||
fn a_variable_read_just_before_a_function_body_closes_ends_the_own_save_as() {
|
||||
for read in ["$.global['local']", "$.global.local", "this.local", "local"] {
|
||||
let r = report(&format!(
|
||||
concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function get() {{ return {} }}\n",
|
||||
"var local = {{saveAs: function () {{}}}};\n",
|
||||
"get().saveAs = function (f) {{\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
"}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
),
|
||||
read
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 7][..]), "{read}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.global.local.saveAs = …` in a function whose parameter is named `local` replaces the global
|
||||
/// variable's method; the parameter alone leaves the outer literal's `saveAs` the script's own.
|
||||
#[test]
|
||||
fn a_dot_global_method_assignment_under_a_parameter_shadow_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function install(local) {\n",
|
||||
" $.global.local.saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"install(null);\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9][..]));
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install(local) { local.n = 1; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install({});\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), None);
|
||||
}
|
||||
|
||||
/// Only a `var` statement directly in a function body or the global code that gives its first name
|
||||
/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the
|
||||
/// statement. A literal given in a branch, one the value goes on from, one given by an assignment
|
||||
|
||||
@@ -74,6 +74,9 @@ craft-image-codecs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Unpacks the interface language catalogs, which build.rs stores Brotli-compressed (src/i18n.rs).
|
||||
# Pure Rust, builds for wasm32, and already in Cargo.lock through craft-i18n.
|
||||
brotli-decompressor = { version = "6", default-features = false, features = ["std"] }
|
||||
|
||||
# Floating panels open in OS windows of their own on the desktop; on the web they stay in the page.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
@@ -110,16 +113,22 @@ vectorcraft-tools = { workspace = true, features = ["testing"] }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
|
||||
wat = { workspace = true }
|
||||
# Compresses bad catalogs for the i18n unpacking tests.
|
||||
brotli = { version = "9", default-features = false, features = ["std"] }
|
||||
|
||||
[build-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
# Compresses the interface language catalogs (src/i18n/*.tsv); already in Cargo.lock through craft-i18n.
|
||||
brotli = { version = "9", default-features = false, features = ["std"] }
|
||||
|
||||
# The files of other crates that this crate's tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = [
|
||||
"crates/engine/src/cmd/addons/cutting/banner.rs",
|
||||
"crates/plugins/tests/fixtures/desaturate.wasm",
|
||||
"docs/control-protocol.md",
|
||||
"docs/mcp.md",
|
||||
"packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/nightly_plist.py",
|
||||
]
|
||||
@@ -6,12 +6,72 @@
|
||||
//! JSON says the entry was verified (`people_entry`).
|
||||
//!
|
||||
//! A missing or malformed file gives empty tables (or no names) and a warning.
|
||||
//!
|
||||
//! Also compress the interface language catalogs, `src/i18n/*.tsv`, with Brotli into `OUT_DIR/i18n/`,
|
||||
//! and write `i18n_catalogs.rs`, the table `src/i18n.rs` unpacks them from. A catalog that can't be
|
||||
//! read or is larger than [`MAX_CATALOG_BYTES`] stops the build.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// The largest catalog embedded, in bytes; `src/i18n.rs` unpacks no more than this.
|
||||
const MAX_CATALOG_BYTES: usize = 8 << 20;
|
||||
|
||||
fn main() {
|
||||
if let Err(e) = pack_catalogs() {
|
||||
println!("cargo::error=packing the interface language catalogs: {e}");
|
||||
}
|
||||
credits();
|
||||
}
|
||||
|
||||
/// Compress each `src/i18n/<code>.tsv` to `OUT_DIR/i18n/<code>.tsv.br` and list them, by code, in
|
||||
/// `OUT_DIR/i18n_catalogs.rs` as `CATALOGS: &[(code, compressed text, text length in bytes)]`.
|
||||
fn pack_catalogs() -> Result<(), String> {
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/i18n");
|
||||
println!("cargo::rerun-if-changed={}", src.display());
|
||||
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").ok_or("OUT_DIR is not set")?);
|
||||
let packed = out.join("i18n");
|
||||
std::fs::create_dir_all(&packed).map_err(|e| format!("{}: {e}", packed.display()))?;
|
||||
let mut codes = Vec::new();
|
||||
for entry in std::fs::read_dir(&src).map_err(|e| format!("{}: {e}", src.display()))? {
|
||||
let path = entry.map_err(|e| format!("{}: {e}", src.display()))?.path();
|
||||
if let (Some(code), Some("tsv")) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) {
|
||||
codes.push(code.to_string());
|
||||
}
|
||||
}
|
||||
codes.sort();
|
||||
let mut table = String::from("const CATALOGS: &[(&str, &[u8], usize)] = &[\n");
|
||||
for code in codes {
|
||||
let path = src.join(format!("{code}.tsv"));
|
||||
println!("cargo::rerun-if-changed={}", path.display());
|
||||
let text = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if text.len() > MAX_CATALOG_BYTES {
|
||||
return Err(format!("{} is {} bytes, over the {MAX_CATALOG_BYTES}-byte limit", path.display(), text.len()));
|
||||
}
|
||||
let mut compressed = Vec::new();
|
||||
{
|
||||
// Quality 9, a 4 MiB window.
|
||||
let mut encoder = brotli::CompressorWriter::new(&mut compressed, 4096, 9, 22);
|
||||
encoder.write_all(&text).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
let file = packed.join(format!("{code}.tsv.br"));
|
||||
if std::fs::read(&file).ok().as_deref() != Some(compressed.as_slice()) {
|
||||
std::fs::write(&file, &compressed).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
}
|
||||
let _ = writeln!(table, " ({code:?}, include_bytes!(concat!(env!(\"OUT_DIR\"), \"/i18n/{code}.tsv.br\")), {}),", text.len());
|
||||
}
|
||||
table.push_str("];\n");
|
||||
let file = out.join("i18n_catalogs.rs");
|
||||
if std::fs::read_to_string(&file).is_ok_and(|old| old == table) {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::write(&file, table).map_err(|e| format!("{}: {e}", file.display()))
|
||||
}
|
||||
|
||||
fn credits() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors");
|
||||
let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| {
|
||||
serde_json::from_str::<Value>(t).map_err(|e| e.to_string())
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, Randomize
|
||||
//! Opacity, Sort Objects and Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command
|
||||
//! on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
//! Opacity, Sort Objects, Add Artboard Guides and Mark Bounds of Each, which preview on the canvas and run their
|
||||
//! `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active
|
||||
//! view to the selection.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -29,9 +30,10 @@ const MATCH: &str = "addon.arrange.match";
|
||||
const ROWS: &str = "addon.arrange.groupRows";
|
||||
const OPACITY: &str = "addon.arrange.randomizeOpacity";
|
||||
const SORT: &str = "addon.arrange.sort";
|
||||
const GUIDES: &str = "addon.arrange.artboardGuides";
|
||||
const MARKS: &str = "addon.arrange.markBounds";
|
||||
/// Each dialog's command and heading.
|
||||
const DIALOGS: [(&str, &str); 9] = [
|
||||
const DIALOGS: [(&str, &str); 10] = [
|
||||
(GRID, "Arrange in Grid"),
|
||||
(OFFSET, "Offset Objects"),
|
||||
(REPLACE, "Replace with Top Object"),
|
||||
@@ -40,8 +42,11 @@ const DIALOGS: [(&str, &str); 9] = [
|
||||
(ROWS, "Group by Row"),
|
||||
(OPACITY, "Randomize Opacity"),
|
||||
(SORT, "Sort Objects"),
|
||||
(GUIDES, "Add Artboard Guides"),
|
||||
(MARKS, "Mark Bounds of Each"),
|
||||
];
|
||||
/// The artboards Add Artboard Guides puts guides around: `all` false or true.
|
||||
const SCOPES: [(&str, &str); 2] = [("active", "Active Artboard"), ("all", "All Artboards")];
|
||||
/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights.
|
||||
const MARK_LENGTHS: std::ops::RangeInclusive<f64> = 0.001..=1e6;
|
||||
const WEIGHTS: std::ops::RangeInclusive<f64> = 0.01..=1000.0;
|
||||
@@ -77,6 +82,7 @@ pub fn menu() -> Vec<Node> {
|
||||
c("Group by Row…", ROWS),
|
||||
c("Randomize Opacity…", OPACITY),
|
||||
c("Sort Objects…", SORT),
|
||||
c("Add Artboard Guides…", GUIDES),
|
||||
c("Mark Bounds of Each…", MARKS),
|
||||
Sep,
|
||||
cp("Zoom to Selection", ZOOM, json!({})),
|
||||
@@ -91,6 +97,7 @@ static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: No
|
||||
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None };
|
||||
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
|
||||
|
||||
/// The dialog over `rows`, titled by the heading of `command`.
|
||||
@@ -201,6 +208,11 @@ fn sort_rows() -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn guides_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
// More than 0 outside the artboard, less than 0 inside it.
|
||||
vec![length("offset", "Offset:", 0.0, GAPS, lengths), choice("scope", "Artboards:", &SCOPES, "active")]
|
||||
}
|
||||
|
||||
fn marks_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")];
|
||||
let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")];
|
||||
@@ -258,10 +270,39 @@ fn sort_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&sort_rows(), fields))
|
||||
}
|
||||
|
||||
/// Add Artboard Guides' offset, and `all` for All Artboards, else the artboard active when the dialog opened.
|
||||
fn guides_params(fields: &DialogFields) -> Value {
|
||||
let mut params = form::json_of(&guides_rows(POINTS), fields);
|
||||
let all = fields.text("scope") == Some("all");
|
||||
params.remove("scope");
|
||||
if all {
|
||||
params.remove("artboardId");
|
||||
}
|
||||
params.insert("all".into(), json!(all));
|
||||
Value::Object(params)
|
||||
}
|
||||
|
||||
pub(super) fn resolve_guides_artboard(app: &VectorcraftApp, params: &mut Value) -> Result<(), String> {
|
||||
if params["all"] == true {
|
||||
return Ok(());
|
||||
}
|
||||
let id = params["artboardId"].as_u64();
|
||||
let index = app.session.active().and_then(|st| st.doc.artboards.iter().position(|a| Some(u64::from(a.id)) == id));
|
||||
let Some(index) = index else { return Err("The artboard no longer exists.".into()) };
|
||||
if let Some(params) = params.as_object_mut() {
|
||||
params.remove("artboardId");
|
||||
params.insert("artboard".into(), json!(index));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens the dialog of command `id` on the active document; `None` for another command and without a document.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, String>> {
|
||||
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
|
||||
let st = app.session.active()?;
|
||||
if command == GUIDES && st.doc.artboards.is_empty() {
|
||||
return Some(Err("the document has no artboards".into()));
|
||||
}
|
||||
let strokes = app.session.prefs.scale_strokes;
|
||||
let key = st.selection.key.is_some();
|
||||
let lengths = general_lengths(app);
|
||||
@@ -295,6 +336,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
"by": "area", "apply": "stacking", "order": "ascending", "distribute": false, "seed": st.revision % SEEDS, "scaleStrokes": strokes,
|
||||
}),
|
||||
),
|
||||
GUIDES => (
|
||||
guides_rows(lengths),
|
||||
json!({
|
||||
"offset": 0, "scope": "active",
|
||||
"artboardId": st.doc.artboards.get(crate::panels::artboards::selected(app, st.doc.artboards.len())).map(|a| a.id),
|
||||
}),
|
||||
),
|
||||
MARKS => (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })),
|
||||
// The first selected object's size, as the command measures it (a side it lacks: the least).
|
||||
_ => {
|
||||
@@ -328,6 +376,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
|
||||
}),
|
||||
SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))),
|
||||
GUIDES => super::dialogs::open(app, &GUIDES_SPEC, fields, move |fields| dialog(GUIDES, guides_rows(lengths)).values(Bind::bound(fields))),
|
||||
MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).values(Bind::bound(fields))),
|
||||
_ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| {
|
||||
let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true);
|
||||
|
||||
@@ -164,6 +164,182 @@ fn real_opacity_edits_drive_validation_confirmation_and_cancel() {
|
||||
assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The bounds of the guide paths on the top-level layer Artboard Guides, from the back.
|
||||
fn artboard_guides(app: &VectorcraftApp) -> Vec<vectorcraft_geom::Rect> {
|
||||
let d = &app.session.doc().unwrap().doc;
|
||||
let layer = d.layers.iter().find(|l| l.name.as_deref() == Some("Artboard Guides"));
|
||||
let guides = layer.and_then(|l| l.children()).into_iter().flatten();
|
||||
guides.filter(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: true, .. })).map(|n| n.geometric_bounds().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step() {
|
||||
for cancel in [true, false] {
|
||||
let (app, _, _) = app();
|
||||
let board = app.session.doc().unwrap().doc.artboards[0].rect;
|
||||
let (original, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len());
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Add Artboard Guides…");
|
||||
panel.frame();
|
||||
type_number(&mut panel, "Offset", "-12");
|
||||
let id = host::dialog_id(&panel.app());
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.number("offset")), Some(-12.0));
|
||||
assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)], "the preview insets the active artboard");
|
||||
panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(artboard_guides(&panel.app()).is_empty(), "no guide with Preview off");
|
||||
panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)]);
|
||||
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo, "a preview makes no step");
|
||||
panel.click(if cancel { "Cancel" } else { "OK" });
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert!(!app.any_dialog_open());
|
||||
let state = app.session.doc().unwrap();
|
||||
if cancel {
|
||||
assert!(*state.doc == *original, "Cancel leaves the document as it was");
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
} else {
|
||||
assert_eq!(artboard_guides(&app), vec![board.inflate(-12.0, -12.0)]);
|
||||
assert_eq!(state.history.undo.len(), undo + 1, "OK adds the guide as one undo step");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let boards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
assert_eq!(host::read(&app, id, |f| (f.number("offset"), f.text("scope").map(str::to_owned))), (Some(0.0), Some("active".to_owned())));
|
||||
host::set(&app, id, "offset", json!(18));
|
||||
host::set(&app, id, "scope", json!("all"));
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), boards.iter().map(|b| b.inflate(18.0, 18.0)).collect::<Vec<_>>());
|
||||
// The second artboard is 100 pt tall: an inset of 50 leaves it nothing, so OK adds nothing.
|
||||
let (before, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len());
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "offset", json!(-50));
|
||||
host::set(&app, id, "scope", json!("all"));
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(*app.session.doc().unwrap().doc == *before);
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_does_not_open_without_artboards() {
|
||||
let (mut app, _, _) = app();
|
||||
std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).artboards.clear();
|
||||
let opened = crate::addons::dialogs::open_from_menu(&mut app, "addon.arrange.artboardGuides");
|
||||
assert!(matches!(opened, Some(Err(_))), "{opened:?}");
|
||||
assert!(!app.any_dialog_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_keeps_the_opening_artboard_after_reordering() {
|
||||
for preview in [false, true] {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
let board = app.session.doc().unwrap().doc.artboards[0].rect;
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "preview", json!(preview));
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
app.session.cancel_interaction().unwrap();
|
||||
}
|
||||
app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap();
|
||||
let n = steps(&app);
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![board]);
|
||||
assert_eq!(steps(&app), n);
|
||||
}
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![board]);
|
||||
assert_eq!(steps(&app), n + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() {
|
||||
for preview in [false, true] {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "preview", json!(preview));
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
app.session.cancel_interaction().unwrap();
|
||||
}
|
||||
app.run("artboard.delete", json!({"index": 0})).unwrap();
|
||||
let (before, n) = (app.session.doc().unwrap().doc.clone(), steps(&app));
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
assert!(artboard_guides(&app).is_empty());
|
||||
assert_eq!(steps(&app), n);
|
||||
}
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(artboard_guides(&app).is_empty());
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
assert_eq!(steps(&app), n);
|
||||
assert_eq!(app.ui.status, "The artboard no longer exists.");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_guides_menu_dialog_is_available_without_a_selection() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(menus::enabled(&app, "ui.menuDialog"));
|
||||
let guides = json!({"command": "addon.arrange.artboardGuides"});
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &guides).map(|s| s.0), Some(true));
|
||||
let transform = json!({"command": "object.move"});
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(false));
|
||||
let grid = json!({"command": "addon.arrange.grid"});
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(false));
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(true));
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(true));
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("ui.menuDialog", guides).unwrap();
|
||||
let id = host::dialog_id(&app);
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![app.session.doc().unwrap().doc.artboards[0].rect]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_uses_the_artboard_the_view_shows() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let second = app.session.doc().unwrap().doc.artboards[1].rect;
|
||||
// The view moves to the second artboard without a command that tells the document, which
|
||||
// still names the first.
|
||||
app.view_mut().unwrap().artboard = 1;
|
||||
let first = app.session.doc().unwrap().doc.artboards[0].id;
|
||||
app.session.active_mut().unwrap().active_artboard = Some(first);
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "offset", json!(6));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "the preview");
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "OK");
|
||||
}
|
||||
|
||||
/// The objects of the first layer, from the back.
|
||||
fn stacking(panel: &Harness) -> Vec<NodeId> {
|
||||
panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
|
||||
@@ -29,6 +29,16 @@ pub(crate) struct Spec {
|
||||
pub found: Option<Found>,
|
||||
}
|
||||
|
||||
impl Spec {
|
||||
fn params(&self, app: &VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
|
||||
let mut params = (self.params)(fields);
|
||||
if self.command == "addon.arrange.artboardGuides" {
|
||||
super::arrange::resolve_guides_artboard(app, &mut params)?;
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
}
|
||||
|
||||
/// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AddonDialogs {
|
||||
@@ -141,11 +151,19 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
app.addon_dialogs.preview = LivePreview::default();
|
||||
app.addon_dialogs.preview_error = None;
|
||||
}
|
||||
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
|
||||
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), spec.params(app, d.fields()))));
|
||||
if on_document && let Some((previewing, params)) = &live {
|
||||
let mut preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
|
||||
let answer = preview.run(app, *previewing, label, spec.command, params);
|
||||
let answer = match params {
|
||||
Ok(params) => preview.run(app, *previewing, label, spec.command, params),
|
||||
Err(error) => {
|
||||
preview.cancel(app);
|
||||
preview = LivePreview::default();
|
||||
app.status(error.clone());
|
||||
Some(Err(error.clone()))
|
||||
}
|
||||
};
|
||||
app.addon_dialogs.preview = preview;
|
||||
if spec.command == super::select::points_only::COMMAND {
|
||||
match &answer {
|
||||
@@ -172,11 +190,13 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
} else if !on_document {
|
||||
app.status("The add-on settings apply only to the drawing where the dialog opened.");
|
||||
} else {
|
||||
let params = (spec.params)(&result.fields);
|
||||
let answer = if spec.command == super::select::points_only::COMMAND {
|
||||
preview.commit_selection(app, spec.command, params)
|
||||
} else {
|
||||
preview.commit(app, spec.command, params)
|
||||
let answer = match spec.params(app, &result.fields) {
|
||||
Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params),
|
||||
Ok(params) => preview.commit(app, spec.command, params),
|
||||
Err(error) => {
|
||||
preview.cancel(app);
|
||||
Err(error)
|
||||
}
|
||||
};
|
||||
if let Err(error) = answer {
|
||||
app.status(error);
|
||||
|
||||
@@ -147,8 +147,10 @@ const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"
|
||||
/// `prefs.agents`: the agent settings of Preferences › AI Integrations, the link's status and the
|
||||
/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves those
|
||||
/// settings first. Agents can't change them: their requests run confined to the agent folders, and
|
||||
/// widening those is the person's choice.
|
||||
/// widening those is the person's choice. A control client started without automation roots can't
|
||||
/// change them either.
|
||||
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let automated = app.automation_is_acting() || file_access::current().is_some();
|
||||
let Some(agents) = app.agents.as_mut() else {
|
||||
return Err("agents can't use this window: it keeps no preferences (VECTORCRAFT_NO_PREFS), or it is a nightly".into());
|
||||
};
|
||||
@@ -157,7 +159,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
|
||||
if let Some(unknown) = given.keys().find(|k| !KEYS.contains(&k.as_str())) {
|
||||
return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", ")));
|
||||
}
|
||||
if file_access::current().is_some() {
|
||||
if automated {
|
||||
return Err("agents can't change the agent settings: the person sets them in Preferences › AI Integrations".into());
|
||||
}
|
||||
let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -133,3 +133,27 @@ fn prefs_agents_saves_and_agents_cannot_change_it() {
|
||||
assert!(file_access::confine(Some(&roots), || app.run("prefs.agents", json!({}))).is_ok());
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
// A control client started without automation roots runs unconfined, and it still can't change the
|
||||
// agent settings: only the person sets them.
|
||||
#[test]
|
||||
fn prefs_agents_refuses_changes_from_an_unconfined_control_client() {
|
||||
let base = folders("prefs-unconfined");
|
||||
let (app, saved) = app_with_agents(&base, AgentSwitch::fixed(true, false));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut app = app.with_control(rx);
|
||||
let ctx = app.ui_ctx.clone().unwrap_or_default();
|
||||
let mut request = |params: Value| {
|
||||
let (req, reply) = craft::automation::ControlRequest::new("engine.execute", json!({"command": "prefs.agents", "params": params}));
|
||||
tx.send(req).unwrap();
|
||||
app.run_control(&ctx);
|
||||
reply.try_recv().unwrap()
|
||||
};
|
||||
let widened = request(json!({"readRoot": s(base.clone())}));
|
||||
assert_eq!(widened["ok"], false, "{widened}");
|
||||
assert!(widened["error"].as_str().is_some_and(|e| e.contains("can't change the agent settings")), "{widened}");
|
||||
assert!(saved.lock().unwrap().is_empty(), "nothing was saved");
|
||||
let read = request(json!({}));
|
||||
assert_ne!(read["ok"], false, "{read}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
@@ -180,6 +180,8 @@ impl VectorcraftApp {
|
||||
multi_color: None,
|
||||
global_edit_count: None,
|
||||
shape_angle: None,
|
||||
radius_corners: None,
|
||||
selected_rectangles: None,
|
||||
trace_presets: None,
|
||||
trace_target: None,
|
||||
attributes_info: None,
|
||||
|
||||
@@ -124,10 +124,11 @@ impl VectorcraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align,
|
||||
/// Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols
|
||||
/// panel act on the active artboard, the view's, which the app adds to command `id`'s `params` as
|
||||
/// `artboard`. A batch passes it on to those steps. While the Artboard tool has several artboards
|
||||
/// Add Artboard Guides (Object › Plug-ins › Arrange Tools), Paste in place, in front and in
|
||||
/// back (#693), Select › All on Active Artboard (#1006), and Align, Distribute Objects and
|
||||
/// Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols panel act on the
|
||||
/// active artboard, the view's, which the app adds to command `id`'s `params` as `artboard`. A
|
||||
/// batch passes it on to those steps. While the Artboard tool has several artboards
|
||||
/// selected, the paste commands get those as `artboards` instead, and paste a copy on each; in a
|
||||
/// document without artboards they get neither.
|
||||
fn add_active_artboard(&self, id: &str, params: &mut Value) {
|
||||
|
||||
@@ -160,6 +160,12 @@ pub struct CanvasCache {
|
||||
pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>,
|
||||
/// The selected live shape's angle, for (document uid, revision, kind of shape).
|
||||
pub shape_angle: Option<ShapeAngleCache>,
|
||||
/// The corners a live shape's Corner Radius field sets, as one hash, for (document uid,
|
||||
/// File › Revert count, revision).
|
||||
pub(crate) radius_corners: Option<((u64, u64, u64), u64)>,
|
||||
/// The selected live rectangles the per-corner fields set, as one hash, for (document uid,
|
||||
/// File › Revert count, revision).
|
||||
pub(crate) selected_rectangles: Option<((u64, u64, u64), u64)>,
|
||||
/// The Image Trace presets, for the session's preset revision.
|
||||
pub(crate) trace_presets: Option<(u64, Arc<crate::panels::image_trace::PresetList>)>,
|
||||
/// What the Image Trace panel traces, for (document uid, revision).
|
||||
|
||||
@@ -127,10 +127,11 @@ fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let Some(picked) = crate::panels::picked_corners(app) else { return };
|
||||
let label = tl!("Corner Radius:");
|
||||
let lengths = crate::canvas::general_lengths(app);
|
||||
let target = crate::panels::corner_target(app, &picked.corners);
|
||||
let mut typed = None;
|
||||
group(ui, rank::GROUP, |ui| {
|
||||
crate::panels::corners_link(app, ui);
|
||||
let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui);
|
||||
let number = NumberField::length(label, Bind::given(picked.radius), lengths).edit_target(target).show(ui);
|
||||
typed = number.edit.events.committed().copied().flatten().or(typed);
|
||||
});
|
||||
if let Some(radius) = typed {
|
||||
|
||||
@@ -3224,6 +3224,34 @@ fn the_control_bar_opacity_drops_an_unfinished_value_on_file_revert() {
|
||||
assert_eq!(opacity, 0.01, "Revert drops the unfinished value: 1%, not 20+1");
|
||||
}
|
||||
|
||||
/// A radius typed into the Control bar's Corner Radius field and not yet entered is dropped when
|
||||
/// another corner with the same radius is Direct-Selected: Enter sets only what was typed after.
|
||||
#[test]
|
||||
fn the_control_bar_corner_radius_drops_an_unfinished_value_when_the_corners_change() {
|
||||
use egui::{Key, Modifiers};
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("object.expandShape", json!({})).unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar);
|
||||
bar.room(egui::vec2(2400.0, 400.0)).frame();
|
||||
bar.click_role("Corner Radius:", Role::SPIN_BUTTON);
|
||||
bar.key(Key::A, Modifiers::COMMAND);
|
||||
bar.type_text("3+");
|
||||
bar.app().run("select.anchors", json!({"id": id, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
bar.frame();
|
||||
assert_eq!(bar.value_role("Corner Radius:", Role::SPIN_BUTTON).as_deref(), Some("0 pt"), "the field shows the new corner's radius");
|
||||
bar.type_text("1");
|
||||
bar.key(Key::Enter, Modifiers::NONE);
|
||||
let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
|
||||
let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap();
|
||||
assert_eq!((0..4).map(|k| lc.radius(k)).collect::<Vec<_>>(), [0.0, 1.0, 0.0, 0.0], "the second corner takes 1 pt, not 3+1");
|
||||
}
|
||||
|
||||
/// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard
|
||||
/// controls while it has room, and the Distribute buttons for two or more selected artboards with
|
||||
/// Align to Artboard and three or more with Align to Selection. A
|
||||
|
||||
@@ -28,7 +28,8 @@
|
||||
//! a path, or with `data: true`, as `pngBase64`)
|
||||
//! - `app.open {path}` (any readable format) / `app.save {path?, svg?: {…SVG options}}` / `app.quit`
|
||||
//! (`file.close`, `file.closeAll` and `app.quit` first open a `saveChanges` dialog for each
|
||||
//! modified document: `ui.dialog.confirm` saves, set `discard: true` then confirm to discard)
|
||||
//! modified document: `ui.dialog.confirm` saves, set `choice: "dontSave"` then confirm to close
|
||||
//! without saving)
|
||||
//! - `app.export {path?, format?, …document.export options}`: encoded by the engine, written through
|
||||
//! the host; the document keeps its path. No path → `{dataBase64, format, bytes}` (as headless)
|
||||
//! - `wait: true` on `app.save` and `app.export`: the file is written before the reply, even with
|
||||
|
||||
@@ -332,9 +332,16 @@ impl HoldsOk for DxfImportDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `ext` the extension of a drawing this dialog opens (DXF, or DWG converted to DXF)?
|
||||
/// Is `ext` the extension (or format id) of a drawing this dialog opens (DXF, or DWG converted to
|
||||
/// DXF)?
|
||||
pub(crate) fn is_drawing_ext(ext: &str) -> bool {
|
||||
matches!(ext, "dxf" | "dwg")
|
||||
ext == "dxf" || is_dwg_ext(ext)
|
||||
}
|
||||
|
||||
/// Is `ext` the extension (or format id) of a DWG drawing: `.dwg`, a `.dws` standards file or a
|
||||
/// `.dwt` template?
|
||||
pub(crate) fn is_dwg_ext(ext: &str) -> bool {
|
||||
fileio::readable_format(ext).is_some_and(|f| fileio::reads_as_dwg(f.id))
|
||||
}
|
||||
|
||||
/// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they
|
||||
@@ -351,7 +358,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
|
||||
/// drawing is converted on a job of its own ([`crate::opening::convert_drawing`]) and its dialog
|
||||
/// opens once that is done ([`converted`]) → true; false when `bytes` aren't a DWG drawing.
|
||||
pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>) -> bool {
|
||||
if !vectorcraft_cad::dwg::DECODES || !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| f.id != "dwg") {
|
||||
if !vectorcraft_cad::dwg::DECODES || !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| !fileio::reads_as_dwg(f.id)) {
|
||||
return false;
|
||||
}
|
||||
crate::opening::convert_drawing(app, name, bytes.to_vec(), path, place.cloned());
|
||||
@@ -365,10 +372,10 @@ pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8],
|
||||
/// converted (true).
|
||||
pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
|
||||
if !vectorcraft_cad::dwg::DECODES || p.get("dxf").is_some() || named.as_deref() != Some("dwg") {
|
||||
if !vectorcraft_cad::dwg::DECODES || p.get("dxf").is_some() || !named.as_deref().is_some_and(is_dwg_ext) {
|
||||
return false;
|
||||
}
|
||||
let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dwg") else { return false };
|
||||
let Some((name, bytes, path)) = place_source(app, p, is_dwg_ext) else { return false };
|
||||
if !vectorcraft_cad::is_dwg(&bytes) {
|
||||
return false;
|
||||
}
|
||||
@@ -443,8 +450,8 @@ fn show(
|
||||
open_held(app, dialog, move |app, choices| confirm(app, &source, choices)).is_some()
|
||||
}
|
||||
|
||||
/// `file.place` with params `p` asks first (true) when they name a `.dxf` or `.dwg` drawing and no
|
||||
/// `dxf` options.
|
||||
/// `file.place` with params `p` asks first (true) when they name a `.dxf`, `.dwg`, `.dws` or `.dwt`
|
||||
/// drawing and no `dxf` options.
|
||||
pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
|
||||
if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) {
|
||||
@@ -456,7 +463,8 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
|
||||
/// The `dxf` options a drawing `file.place` params `p` name is placed with when Show Import Options
|
||||
/// is off: the choices confirmed last (fit, lineweights, centring, layers), the drawing at 1:1 in
|
||||
/// its own unit. `None` when `p` names no `.dxf` or `.dwg` drawing or already gives `dxf` options.
|
||||
/// its own unit. `None` when `p` names no DXF or DWG drawing ([`is_drawing_ext`]) or already gives
|
||||
/// `dxf` options.
|
||||
pub fn last_options(app: &VectorcraftApp, p: &Value) -> Option<Value> {
|
||||
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
|
||||
if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) {
|
||||
@@ -808,6 +816,46 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
/// A `.dwt` template and a `.dws` standards file are DWG drawings: they are converted off the UI
|
||||
/// thread and go through the dialog as a `.dwg` does, and the template opens untitled.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn a_dwt_template_and_a_dws_file_open_and_place_as_dwg_drawings() {
|
||||
vectorcraft_engine::dwg::allow_in_process();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap();
|
||||
let dir = crate::tests_folder::Folder::new("dxf-import-dwt-dws");
|
||||
let (template, standards) = (dir.join("plan.dwt"), dir.join("plan.dws"));
|
||||
std::fs::write(&template, &dwg).unwrap();
|
||||
std::fs::write(&standards, &dwg).unwrap();
|
||||
let (template, standards) = (template.to_string_lossy().into_owned(), standards.to_string_lossy().into_owned());
|
||||
crate::opening::tests::with_threads(|| {
|
||||
let mut app = host::app();
|
||||
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
|
||||
crate::io::open_file(&mut app, &template, true).unwrap();
|
||||
assert!(!host::is_open(&app, KIND) && app.opening.converting.len() == 1, "the template is converted first");
|
||||
finish_conversions(&mut app);
|
||||
assert_eq!(host::fields(&app, KIND)["mode"], "open");
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
let st = app.session.doc().unwrap();
|
||||
assert!(st.doc.title.starts_with("Untitled"), "a template opens untitled: {}", st.doc.title);
|
||||
let w = st.doc.artboards[0].rect.width();
|
||||
assert!((w - 100.0 * Unit::Millimeters.points()).abs() < 1e-6, "the model space line at 1:1: {w}");
|
||||
crate::io::open_file(&mut app, &standards, true).unwrap();
|
||||
assert_eq!(app.opening.converting.len(), 1, "the standards file is converted first");
|
||||
finish_conversions(&mut app);
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc.title, "plan.dws");
|
||||
// Placed by the user, each is converted first and asks for its options.
|
||||
for path in [&template, &standards] {
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": path })).unwrap();
|
||||
assert!(!host::is_open(&app, KIND), "{path}");
|
||||
finish_conversions(&mut app);
|
||||
assert_eq!(host::fields(&app, KIND)["mode"], "place", "{path}");
|
||||
host::cancel(&app, KIND);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Waits for the DWG conversions under way to finish, then lets [`crate::opening::poll`] hand
|
||||
/// them on.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
@@ -650,3 +650,25 @@ fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected()
|
||||
assert_eq!(selected(&p), vec![first]);
|
||||
assert_eq!(undo_steps(&p), before);
|
||||
}
|
||||
|
||||
/// `ui.findAndReplace` and `ui.paramDialog` with edit.findReplace open the dialog that `ui.inspect` lists with key null
|
||||
/// and the fields the params text names, as both params texts say.
|
||||
#[test]
|
||||
fn params_texts_match_what_ui_inspect_lists() {
|
||||
let expected = ["find", "replace", "matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers", "action"];
|
||||
let doc = |command: &str| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3;
|
||||
for (command, params) in [("ui.findAndReplace", json!({})), ("ui.paramDialog", json!({"command": super::COMMAND, "params": {}}))] {
|
||||
let mut app = crate::testing::windowed(app_with(&["alpha"]).0);
|
||||
app.run(command, params).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let ui = crate::control::inspect(&app, &ctx);
|
||||
let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog");
|
||||
assert_eq!(entry.get("key"), Some(&Value::Null), "{command}: {entry}");
|
||||
assert!(doc(command).contains("with key null"), "{command} opens a dialog with key null, which its params text does not say");
|
||||
let missing: Vec<&str> = expected.iter().copied().filter(|f| entry["fields"].get(*f).is_none()).collect();
|
||||
assert!(missing.is_empty(), "{command}: ui.inspect does not list {missing:?}");
|
||||
}
|
||||
let named = doc("ui.paramDialog");
|
||||
let unnamed: Vec<&str> = expected.iter().copied().filter(|f| !named.contains(*f)).collect();
|
||||
assert!(unnamed.is_empty(), "the params text of ui.paramDialog does not name {unnamed:?}");
|
||||
}
|
||||
@@ -111,6 +111,10 @@ impl StackDialog for JavaScriptFiles {
|
||||
dialog_id(KEY)
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let Self { open, files, form } = self;
|
||||
let shown = Dialog::new(tl!("JavaScript Files"))
|
||||
@@ -418,4 +422,19 @@ mod tests {
|
||||
fixture.click(&add);
|
||||
assert_eq!(form.borrow().pending, Some(Pending::Add));
|
||||
}
|
||||
|
||||
/// `ui.javascriptFilesDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it.
|
||||
#[test]
|
||||
fn params_text_names_the_dialog_key_ui_inspect_lists() {
|
||||
const COMMAND: &str = "ui.javascriptFilesDialog";
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run(COMMAND, json!({})).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let ui = crate::control::inspect(&app, &ctx);
|
||||
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
|
||||
assert_eq!(key, KEY);
|
||||
assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name");
|
||||
}
|
||||
}
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user