mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 10:14:46 +01:00
Merge main into fix/panel-drags-after-file-revert
This commit is contained in:
commit
e6ffa5cc9e
259 files changed
+20025
-1432
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings).
|
||||
crates/cad/tests/data/*.dxf -text
|
||||
@@ -130,7 +130,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
Generated
+86
-86
@@ -1239,7 +1239,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1280,7 +1280,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1291,7 +1291,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1302,7 +1302,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1310,7 +1310,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1335,7 +1335,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1353,7 +1353,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1371,7 +1371,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1380,7 +1380,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1388,7 +1388,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1397,12 +1397,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1422,11 +1422,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1434,8 +1433,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
"subtle",
|
||||
]
|
||||
@@ -1443,7 +1443,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1451,7 +1451,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1477,7 +1477,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1493,7 +1493,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1501,7 +1501,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1520,7 +1520,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1532,7 +1532,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1542,12 +1542,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1562,7 +1562,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1581,7 +1581,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1590,7 +1590,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1613,12 +1613,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1626,7 +1626,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1634,7 +1634,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1647,7 +1647,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
@@ -1675,7 +1675,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1702,7 +1702,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1720,7 +1720,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1728,7 +1728,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1739,7 +1739,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1754,7 +1754,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1768,7 +1768,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1786,7 +1786,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1798,7 +1798,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1809,7 +1809,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1819,7 +1819,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1835,7 +1835,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1846,7 +1846,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1858,7 +1858,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1889,7 +1889,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1898,7 +1898,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1922,7 +1922,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1933,7 +1933,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -1947,7 +1947,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1958,7 +1958,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1971,7 +1971,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1990,7 +1990,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2007,7 +2007,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2018,7 +2018,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2039,7 +2039,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2051,7 +2051,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2076,7 +2076,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2091,7 +2091,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2106,7 +2106,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2116,7 +2116,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2125,7 +2125,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2140,12 +2140,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2159,7 +2159,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -2175,7 +2175,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2213,7 +2213,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2224,7 +2224,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2242,7 +2242,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2263,7 +2263,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2284,7 +2284,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2303,7 +2303,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2335,7 +2335,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2346,7 +2346,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2356,7 +2356,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2367,7 +2367,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2375,7 +2375,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2407,7 +2407,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -3762,7 +3762,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -3771,7 +3771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3789,7 +3789,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3807,12 +3807,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4795,7 +4795,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4952,7 +4952,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
+35
-35
@@ -11,46 +11,46 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -193,13 +193,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
|
||||
@@ -174,6 +174,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -27,7 +27,7 @@ log = { 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 = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 121 KiB |
@@ -2626,6 +2626,83 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`.
|
||||
fn reach_at(nodes: &[Node], x: f64) -> f64 {
|
||||
let mut reach = 0.0f64;
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
|
||||
for i in 0..sp.segment_count() {
|
||||
let s = sp.segment(i);
|
||||
let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x);
|
||||
let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a);
|
||||
for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) {
|
||||
reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
reach
|
||||
}
|
||||
|
||||
/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
// One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where
|
||||
// the scale reaches 300 % (6 pt either side).
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak);
|
||||
// At the peak 300 %, half way up it 200 %, and 100 % on either side of it.
|
||||
for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn art_brush_width_from_the_pen_keeps_a_short_peak() {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
// 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt.
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak);
|
||||
for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's
|
||||
/// two ends do: samples that leave the scale on the same straight course are not split at.
|
||||
#[test]
|
||||
fn pen_samples_on_a_straight_ramp_add_no_anchors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 1000.0, 0.0);
|
||||
let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect());
|
||||
let anchors = |out: &[Node]| {
|
||||
let mut count = 0;
|
||||
for n in out {
|
||||
n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>()));
|
||||
}
|
||||
count
|
||||
};
|
||||
let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut art.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
for b in [&pattern, &art] {
|
||||
let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000)));
|
||||
assert_eq!(anchors(&many), anchors(&few), "{}", b.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
|
||||
/// recorded at the end of the stroke there, where the tile is drawn.
|
||||
#[test]
|
||||
|
||||
+152
-30
@@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32;
|
||||
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
|
||||
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
|
||||
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
|
||||
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
|
||||
/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask
|
||||
/// bends with the object it masks.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
|
||||
/// is longer than `max_du` along x, as it always was. Both routes also split the art where it
|
||||
/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over.
|
||||
/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are
|
||||
/// dropped. The art of a linked opacity mask bends with the object it masks.
|
||||
pub(crate) fn warp_node(
|
||||
n: &Node,
|
||||
f: &dyn Fn(Point) -> Point,
|
||||
flat_tol: f64,
|
||||
max_du: f64,
|
||||
doc_tol: f64,
|
||||
width_scale: f64,
|
||||
breaks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(width_scale);
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
let kids: Vec<Arc<Node>> =
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect();
|
||||
if kids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale));
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) {
|
||||
}
|
||||
|
||||
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
|
||||
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
|
||||
/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not
|
||||
/// finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData {
|
||||
let mut subs = vec![];
|
||||
for sp in &p.subpaths {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) {
|
||||
subs.push(fit);
|
||||
continue;
|
||||
}
|
||||
@@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6
|
||||
}
|
||||
|
||||
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
|
||||
/// x, in art space: the points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the
|
||||
/// points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
@@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut dense = vec![*pts.first()?];
|
||||
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
// The breaks the chord crosses, as parameters along it in order, go in among the even ones.
|
||||
let mut cuts: Vec<f64> = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect();
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
let mut cuts = cuts.into_iter().peekable();
|
||||
for j in 1..=k {
|
||||
let even = j as f64 / k as f64;
|
||||
while let Some(t) = cuts.next_if(|&t| t < even) {
|
||||
dense.push(a.lerp(b, t));
|
||||
}
|
||||
if sp.closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(a.lerp(b, j as f64 / k as f64));
|
||||
dense.push(a.lerp(b, even));
|
||||
}
|
||||
}
|
||||
Some(dense)
|
||||
}
|
||||
|
||||
/// The values of `breaks` (in order) strictly between `a` and `b`, either way round.
|
||||
fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
let from = breaks.partition_point(|&x| x <= lo);
|
||||
let to = from + breaks[from..].partition_point(|&x| x < hi);
|
||||
&breaks[from..to]
|
||||
}
|
||||
|
||||
/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`;
|
||||
/// `line` when `c` is a line with its handles at thirds, whose x runs evenly.
|
||||
fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec<f64> {
|
||||
let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x];
|
||||
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x)));
|
||||
let inside = crossed(breaks, lo, hi);
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let [a, b, cc, d] = xs;
|
||||
let mut ts: Vec<f64> = vec![];
|
||||
for &x in inside {
|
||||
if line {
|
||||
ts.push((x - a) / (d - a));
|
||||
} else {
|
||||
ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a));
|
||||
}
|
||||
}
|
||||
// Pieces are no shorter than the step the fit reads their ends' directions over.
|
||||
ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|t, prev| *t - *prev <= FIT_DT);
|
||||
ts
|
||||
}
|
||||
|
||||
/// Times an art segment is halved at most while looking for cubics that fit it.
|
||||
const FIT_DEPTH: u32 = 12;
|
||||
/// Parameter step of the finite differences that stand in for the bend's derivative.
|
||||
@@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 {
|
||||
/// bend at the same parameters, so the distance measured is never less than the true one. The
|
||||
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
|
||||
/// on a map that never fits; the depth and the anchor count bound this one.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
|
||||
///
|
||||
/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of
|
||||
/// the map there lands on an anchor rather than between the checked positions.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option<SubPath> {
|
||||
if !(tol.is_finite() && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op
|
||||
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
|
||||
let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c };
|
||||
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
|
||||
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
let mut t0 = 0.0;
|
||||
for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) {
|
||||
fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
t0 = t1;
|
||||
}
|
||||
}
|
||||
if sp.closed {
|
||||
bp.close_path();
|
||||
@@ -316,6 +375,16 @@ impl AlongMap {
|
||||
fn max_scale(&self) -> f64 {
|
||||
(0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max)
|
||||
}
|
||||
|
||||
/// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`,
|
||||
/// when a piece with width spans it.
|
||||
fn x_at(&self, s: f64) -> Option<f64> {
|
||||
(0..3).find_map(|i| {
|
||||
let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1]));
|
||||
let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1);
|
||||
spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The affine that reproduces `f` over `b` to within `tol`, if one does.
|
||||
@@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
{
|
||||
return affine_node(art, a, cross.abs());
|
||||
}
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &[])
|
||||
}
|
||||
|
||||
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
|
||||
/// of each object in the art take the factor at the middle of the object.
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// of each object in the art take the factor at the middle of the object. `marks` are the arc
|
||||
/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art
|
||||
/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]).
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option<Node> {
|
||||
let cy = b.center().y;
|
||||
let x0 = b.x0;
|
||||
let f = move |p: Point| {
|
||||
@@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
|
||||
let art = widen_strokes(art, &factor);
|
||||
let scale = along.max_scale().max(cross.abs()).max(1e-6);
|
||||
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
// A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across.
|
||||
let reach = b.height() / 2.0 * cross.abs();
|
||||
let mut breaks: Vec<f64> =
|
||||
pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect();
|
||||
breaks.sort_by(f64::total_cmp);
|
||||
breaks.dedup();
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks)
|
||||
}
|
||||
|
||||
/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split:
|
||||
/// those where `widen` is more than `tol` from the straight line between the ones kept on either
|
||||
/// side (the span's ends to begin with), chosen by splitting at the farthest one until every
|
||||
/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it
|
||||
/// is then within `tol` of the line between kept samples all along, and samples on a straight
|
||||
/// course add no splits.
|
||||
fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec<f64> {
|
||||
if !(s1 > s0 && tol > 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
let inside = {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
&marks[from..from + marks[from..].partition_point(|&s| s < s1)]
|
||||
};
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect();
|
||||
let mut keep = vec![false; pts.len()];
|
||||
let mut spans = vec![(0, pts.len() - 1)];
|
||||
while let Some((i, j)) = spans.pop() {
|
||||
let ((sa, wa), (sb, wb)) = (pts[i], pts[j]);
|
||||
let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs();
|
||||
let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((k, _)) = far {
|
||||
keep[k] = true;
|
||||
spans.extend([(i, k), (k, j)]);
|
||||
}
|
||||
}
|
||||
pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect()
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
@@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
bounds.windows(2).map(|w| (w[0], w[1])).collect()
|
||||
}
|
||||
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
|
||||
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks`
|
||||
/// as [`bend_widened`] takes them).
|
||||
fn art_on_run(
|
||||
t: &Track,
|
||||
(s0, s1): (f64, f64),
|
||||
a: &ArtBrush,
|
||||
(art, b): (&Node, Rect),
|
||||
cross: f64,
|
||||
widen: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let l = s1 - s0;
|
||||
if l <= 1e-9 {
|
||||
return None;
|
||||
@@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R
|
||||
}
|
||||
}
|
||||
};
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
bend_widened(t, art, b, along, cross, widen, marks)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
@@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let marks = match a.width_mode {
|
||||
Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l),
|
||||
_ => vec![],
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
for run in runs {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
@@ -671,7 +793,7 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64)
|
||||
if mid <= 0.0 || marks.is_none_or(even) {
|
||||
return tile_on(t, tile, s0, s1, mid);
|
||||
}
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid)
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The most side tiles a run of a pattern brush places.
|
||||
@@ -966,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
|
||||
}
|
||||
let s = if tw > 1e-9 { len / tw } else { 1.0 };
|
||||
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]);
|
||||
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
|
||||
let along = move |q: Point| {
|
||||
let (x, y) = local(q);
|
||||
@@ -1393,7 +1515,7 @@ mod tests {
|
||||
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
|
||||
let tol = tolerance(b.height().max(b.width()));
|
||||
let exact = traced(art, &f, 1000);
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let curves = traced(sp, &|p| p, 200);
|
||||
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
|
||||
// Checked at eight points a piece, so a little room between them.
|
||||
@@ -1419,7 +1541,7 @@ mod tests {
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5, &[]))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
@@ -1441,7 +1563,7 @@ mod tests {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
@@ -1491,7 +1613,7 @@ mod tests {
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was");
|
||||
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn");
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn");
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art");
|
||||
assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
|
||||
/// passes.
|
||||
const LIGHTNESS_SAMPLES: usize = 16;
|
||||
/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
|
||||
const LIGHTNESS_STEPS: usize = 32;
|
||||
/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
|
||||
/// which leave it within 1e-7 of the step.
|
||||
const PEAK_STEPS: usize = 32;
|
||||
/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
|
||||
/// single peak between them. `f` is called 34 times.
|
||||
pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
|
||||
let g = (5f64.sqrt() - 1.0) / 2.0;
|
||||
let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
|
||||
let (mut fa, mut fb) = (f(a), f(b));
|
||||
for _ in 0..PEAK_STEPS {
|
||||
if fa < fb {
|
||||
(lo, a, fa) = (a, b, fb);
|
||||
b = lo + g * (hi - lo);
|
||||
fb = f(b);
|
||||
} else {
|
||||
(hi, b, fb) = (b, a, fa);
|
||||
a = hi - g * (hi - lo);
|
||||
fa = f(a);
|
||||
}
|
||||
}
|
||||
if fa > fb { a } else { b }
|
||||
}
|
||||
|
||||
/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
|
||||
/// (<https://bottosson.github.io/posts/oklab/>) with the lightness raised or lowered, whichever
|
||||
/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
|
||||
/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
|
||||
/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
|
||||
/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
|
||||
/// so a color that passes only in a narrow band between white and black (as under a Difference
|
||||
/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
|
||||
/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
|
||||
/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
|
||||
/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
|
||||
/// steps before the first passing one is missed, and a farther color can be returned.
|
||||
pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
|
||||
let passes = |c: [f32; 3]| ratio(c) >= minimum;
|
||||
let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
if passes(srgb) {
|
||||
return Some(srgb);
|
||||
}
|
||||
let [l, c, h] = crate::oklab::to_oklch(srgb);
|
||||
let mut best: Option<(f64, [f32; 3])> = None;
|
||||
for end in [1.0, 0.0] {
|
||||
let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
|
||||
let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
|
||||
let ratios: Vec<f64> = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
|
||||
// `lo` fails and `hi` passes, the step before the first sample that passes.
|
||||
let found = match ratios.iter().position(|r| *r >= minimum) {
|
||||
Some(i) => Some((step(i), step(i + 1))),
|
||||
None => {
|
||||
// Every sample fails: look for a higher ratio around the highest one.
|
||||
let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
|
||||
let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
|
||||
let peak = peak_between(lo, hi, &|t| ratio(at(t)));
|
||||
passes(at(peak)).then_some((lo, peak))
|
||||
}
|
||||
};
|
||||
let Some((mut lo, mut hi)) = found else { continue };
|
||||
for _ in 0..LIGHTNESS_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if passes(at(mid)) { hi = mid } else { lo = mid }
|
||||
}
|
||||
let step = (end - l).abs() * hi;
|
||||
if best.is_none_or(|(d, _)| step < d) {
|
||||
best = Some((step, at(hi)));
|
||||
}
|
||||
}
|
||||
best.map(|(_, c)| c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -137,6 +214,80 @@ mod tests {
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
fn hue(srgb: [f32; 3]) -> f64 {
|
||||
let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
|
||||
let (fg, bg) = (hex("fdc96e"), hex("355f78"));
|
||||
let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
|
||||
let r = contrast_ratio(fix, bg);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
|
||||
// A color lighter than the background gets lighter.
|
||||
assert!(relative_luminance(fix) > relative_luminance(fg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_gray_on_white_is_a_darker_gray() {
|
||||
let white = [1.0; 3];
|
||||
let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
|
||||
let r = contrast_ratio(fix, white);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_that_passes_only_between_white_and_black_is_found() {
|
||||
// White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
|
||||
// mid gray draws black, 5.3:1.
|
||||
let gray = [0.5; 3];
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
|
||||
let r = contrast_ratio(difference(fix), gray);
|
||||
assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
|
||||
assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_band_between_the_samples_is_found() {
|
||||
// Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
|
||||
// for 3:1 (black reaches 3.04:1), and no even step from white lands there.
|
||||
let gray = hex("5a5a5a");
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
|
||||
let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
|
||||
let r = ratio(fix);
|
||||
assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
|
||||
}
|
||||
|
||||
/// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
|
||||
/// blue that needs a little more contrast keeps nearly all of its chroma.
|
||||
#[test]
|
||||
fn a_blue_that_darkens_a_little_keeps_its_chroma() {
|
||||
let gray = hex("b8b8b8");
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
|
||||
let blue = [0.0, 0.0, 1.0];
|
||||
assert!(ratio(blue) < 4.5, "{}", ratio(blue));
|
||||
let fix = closest_passing(blue, 4.5, &ratio).unwrap();
|
||||
let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
|
||||
assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
|
||||
assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
|
||||
let white = [1.0; 3];
|
||||
assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
|
||||
assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
|
||||
// Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
|
||||
let mid = hex("777777");
|
||||
assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
|
||||
assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
|
||||
@@ -314,8 +314,14 @@ impl Document {
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
/// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for
|
||||
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
|
||||
/// [`Document::index_path`] finds it.
|
||||
pub fn node(&self, id: NodeId) -> Option<&Node> {
|
||||
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
|
||||
crate::id_index::note_path_lookup();
|
||||
return Some(n);
|
||||
}
|
||||
self.index_path(id).and_then(|p| self.node_at(&p))
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ impl Paths {
|
||||
/// isn't in the table or it, or a node it is in, was removed.
|
||||
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
|
||||
let e = (*self.table.ids.get(id)?)?;
|
||||
note_path_copy();
|
||||
let mut path = Vec::new();
|
||||
let mut cur = e;
|
||||
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
|
||||
@@ -96,6 +97,29 @@ impl Paths {
|
||||
}
|
||||
Some(None)
|
||||
}
|
||||
/// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None`
|
||||
/// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there
|
||||
/// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does.
|
||||
pub(crate) fn node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
|
||||
let mut cur = (*self.table.ids.get(&id)?)?;
|
||||
let mut steps = [0u32; NODE_IN_DEPTH];
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let &(parent, i) = self.table.at.get(cur as usize)?;
|
||||
*steps.get_mut(depth)? = self.shifted(parent, i)?;
|
||||
depth += 1;
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
let mut path = steps[..depth].iter().rev();
|
||||
let mut node: &Node = layers.get(*path.next()? as usize)?;
|
||||
for &i in path {
|
||||
node = node.children()?.get(i as usize)?;
|
||||
}
|
||||
(node.id == id).then_some(node)
|
||||
}
|
||||
/// Where the table has `id` as it was built: its parent's entry and its index among its
|
||||
/// siblings then; `None` when the id isn't in the table or appears more than once.
|
||||
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
|
||||
@@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The deepest index path [`Paths::node_in`] follows without copying it.
|
||||
const NODE_IN_DEPTH: usize = 32;
|
||||
|
||||
thread_local! {
|
||||
/// [`path_copies`] of this thread.
|
||||
static PATH_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`]
|
||||
/// that it answered. [`crate::Document::node`] reads the node from the cache without one.
|
||||
pub fn path_copies() -> u64 {
|
||||
PATH_COPIES.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_copies`].
|
||||
fn note_path_copy() {
|
||||
PATH_COPIES.set(PATH_COPIES.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
|
||||
/// the lookups that missed it, and the nodes removed from the tree since it was built.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -24,7 +24,7 @@ mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod image_quad;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub use id_index::{path_copies, path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
|
||||
@@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() {
|
||||
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
|
||||
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
|
||||
}
|
||||
|
||||
/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after
|
||||
/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path.
|
||||
#[test]
|
||||
fn node_lookups_copy_no_index_path() {
|
||||
let (mut d, ids) = squares(10_000);
|
||||
let layer = d.layers[0].id;
|
||||
let mut nested = vec![];
|
||||
for g in 0..50 {
|
||||
let kids: Vec<Arc<Node>> = (0..4)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
nested.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
|
||||
})
|
||||
.collect();
|
||||
let (gid, inner) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap();
|
||||
}
|
||||
d.remove_many(&ids[..100]).unwrap();
|
||||
d.node(layer);
|
||||
let copies = path_copies();
|
||||
let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count();
|
||||
assert_eq!(found, ids.len() - 100 + nested.len());
|
||||
assert_eq!(path_copies() - copies, 0, "index paths copied");
|
||||
assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found");
|
||||
agree(&d, &ids[..200], "after remove_many");
|
||||
agree(&d, &nested, "nested");
|
||||
}
|
||||
@@ -851,11 +851,12 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
|
||||
@@ -151,7 +151,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Contrast",
|
||||
[],
|
||||
None,
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}",
|
||||
always,
|
||||
contrast
|
||||
),
|
||||
@@ -1032,7 +1032,229 @@ const BELOW_SIDE: f64 = 1.0;
|
||||
/// The pixels per point [`color_below`] renders at.
|
||||
const BELOW_SCALE: f64 = 4.0;
|
||||
|
||||
/// What `color.contrast` measures a color against: the background, and how the color is drawn over
|
||||
/// it (its row, object, groups and layer, each with its blend mode and opacity over the art below
|
||||
/// it). The Color Wheel panel's contrast lines measure many colors against one.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The background in display sRGB.
|
||||
against: [f32; 3],
|
||||
/// The background in working RGB, rounded to 8 bits, as the answer writes it.
|
||||
written: [u8; 3],
|
||||
/// The levels the color is drawn through, innermost first, without those that leave it as it is.
|
||||
passes: Vec<Pass>,
|
||||
/// The color and amount a fill stains the picked object of a dynamic symbol instance with.
|
||||
stain: Option<(Color, f32)>,
|
||||
/// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black).
|
||||
rich_black: bool,
|
||||
}
|
||||
|
||||
/// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color
|
||||
/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of
|
||||
/// the art below it inside the level around it, while a blending level lies further out.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Pass {
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
backdrop: ([f32; 3], f32),
|
||||
blends: bool,
|
||||
isolate: bool,
|
||||
inner: f32,
|
||||
}
|
||||
|
||||
/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next
|
||||
/// level out holds drawn alone.
|
||||
type Through = ([f32; 3], f32, f32);
|
||||
|
||||
impl Pass {
|
||||
/// What the level draws for color and alpha `x`, drawn over the art below it: a level that
|
||||
/// blends takes that art back out by `alone`, the alpha of what it holds drawn alone.
|
||||
fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) {
|
||||
if !self.blends {
|
||||
return x;
|
||||
}
|
||||
if alone <= 0.0 {
|
||||
return (x.0, 0.0);
|
||||
}
|
||||
let b = self.backdrop;
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
}
|
||||
|
||||
/// `d` drawn through the level. The level's opacity applies to what it holds, a level that
|
||||
/// isolates its blending carries out the alpha of what it holds composited on its own, and the
|
||||
/// art beside it in the level around it adds to the alpha once.
|
||||
fn draw(&self, (color, alpha, alone): Through) -> Through {
|
||||
let source = self.source((color, alpha), alone);
|
||||
let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0);
|
||||
let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop);
|
||||
(color, alpha, drawn + self.inner * (1.0 - drawn))
|
||||
}
|
||||
|
||||
/// The level with its opacity, the art below it and its alphas passed through `q`.
|
||||
fn with(&self, q: impl Fn(f32) -> f32) -> Pass {
|
||||
let (color, alpha) = self.backdrop;
|
||||
Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
|
||||
/// fill stains mixes its solid color towards the stain.
|
||||
pub fn drawn_color(&self, c: &Color) -> Color {
|
||||
match self.stain {
|
||||
Some((stain, amount)) => c.lerp(&stain, amount),
|
||||
None => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through
|
||||
/// `cms` and the Appearance of Black the backdrop was read with.
|
||||
pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] {
|
||||
shown_rgb(cms, self.rich_black, &self.drawn_color(c))
|
||||
}
|
||||
|
||||
/// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
|
||||
pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
|
||||
let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d));
|
||||
if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) }
|
||||
}
|
||||
|
||||
/// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
|
||||
/// the background.
|
||||
pub fn ratio(&self, shown: [f32; 3]) -> f64 {
|
||||
wcag::contrast_ratio(self.front(shown), self.against)
|
||||
}
|
||||
|
||||
/// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art
|
||||
/// below each level, the background, the opacities, and the color and alpha each level gives.
|
||||
fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 {
|
||||
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
|
||||
let painted = |c: [f32; 3]| c.map(eight);
|
||||
let against = painted(self.against);
|
||||
let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| {
|
||||
let (color, alpha, alone) = p.with(eight).draw(d);
|
||||
(painted(color), eight(alpha), eight(alone))
|
||||
});
|
||||
let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) };
|
||||
wcag::contrast_ratio(painted(front), against)
|
||||
}
|
||||
|
||||
/// The background as `#rrggbb` in working RGB, the form a color param takes.
|
||||
pub fn against_hex(&self) -> String {
|
||||
let [r, g, b] = self.written;
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
}
|
||||
|
||||
/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
|
||||
/// 100 % K alone shows as black.
|
||||
fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
|
||||
match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
|
||||
/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
|
||||
/// Gray color as gray.
|
||||
fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
|
||||
let [r, g, b] = cms.srgb_to_rgb(srgb);
|
||||
let rgb = Color::rgb(r, g, b);
|
||||
match like {
|
||||
Color::Rgb { .. } => rgb,
|
||||
Color::Cmyk { .. } => {
|
||||
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
|
||||
Color::cmyk(c, m, y, k)
|
||||
}
|
||||
Color::Lab { .. } => {
|
||||
let l = cms.lab(&rgb);
|
||||
Color::lab(l.l, l.a, l.b)
|
||||
}
|
||||
Color::Gray { .. } => keep_model(*like, rgb),
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
|
||||
/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
|
||||
/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8
|
||||
/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by
|
||||
/// [`Backdrop::ratio`], or when no lightness of its hue does.
|
||||
fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option<Color> {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let ratio = |srgb: [f32; 3]| {
|
||||
let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color));
|
||||
backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown))
|
||||
};
|
||||
if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum {
|
||||
return None;
|
||||
}
|
||||
let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?;
|
||||
Some(in_model_of(&cms, fix, color))
|
||||
}
|
||||
|
||||
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
contrast_measure(s, p).map(|(answer, _)| answer)
|
||||
}
|
||||
|
||||
/// `color.contrast`'s answer for params `p`, and what it measured the color against.
|
||||
pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
|
||||
const C: &str = "color.contrast";
|
||||
let category = match p.get("for") {
|
||||
None | Some(Value::Null) => Category::NormalText,
|
||||
Some(v) => {
|
||||
let key = "for";
|
||||
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
|
||||
v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
|
||||
}
|
||||
};
|
||||
let (color, backdrop) = contrast_backdrop(s, p)?;
|
||||
let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color));
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
}
|
||||
};
|
||||
let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) {
|
||||
Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
|
||||
None => Value::Null,
|
||||
};
|
||||
let fixes = match category.minimums() {
|
||||
(aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
|
||||
(aa, None) => json!({ "aa": fix(aa) }),
|
||||
};
|
||||
let answer = json!({
|
||||
"ratio": ratio,
|
||||
"against": backdrop.against_hex(),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
"for": category.id(),
|
||||
"fix": fixes,
|
||||
});
|
||||
Ok((answer, backdrop))
|
||||
}
|
||||
|
||||
/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
|
||||
/// what it measures it against.
|
||||
fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
|
||||
let (color, backdrop) = contrast_reading(s, p, true)?;
|
||||
let color = color.ok_or_else(|| bad("color.contrast", no_color()))?;
|
||||
Ok((color, backdrop))
|
||||
}
|
||||
|
||||
/// What a color picked for the active proxy would be measured against by `color.contrast` with
|
||||
/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the
|
||||
/// Color Wheel's contrast lines show where a pick would pass.
|
||||
pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result<Backdrop> {
|
||||
contrast_reading(s, p, false).map(|(_, backdrop)| backdrop)
|
||||
}
|
||||
|
||||
/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when
|
||||
/// `need_color`.
|
||||
fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option<Color>, Backdrop)> {
|
||||
const C: &str = "color.contrast";
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity").and_then(Value::as_f64) {
|
||||
@@ -1044,23 +1266,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
|
||||
let given = p.get("color").is_some_and(|v| !v.is_null());
|
||||
let (color, drawn) = match p.get("color") {
|
||||
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
|
||||
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
|
||||
Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
|
||||
};
|
||||
if need_color && color.is_none() {
|
||||
return Err(bad(C, no_color()));
|
||||
}
|
||||
let rich_black = s.prefs.black_on_screen == "rich";
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let shown = |c: &Color| match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
};
|
||||
let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
|
||||
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
// Whether the background read is one color across its pixels.
|
||||
let mut uniform = true;
|
||||
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
|
||||
let (against, written) = match p.get("against").filter(|_| !below) {
|
||||
None => {
|
||||
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
|
||||
// one the ratio uses, and giving it back answers the same ratio.
|
||||
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
|
||||
let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
|
||||
uniform &= one;
|
||||
let working = to_8bit(cms.srgb_to_rgb(sample));
|
||||
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
|
||||
}
|
||||
Some(v) => {
|
||||
@@ -1096,60 +1323,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
|
||||
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
|
||||
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
|
||||
// The alphas, the art below each level and `alone` do not depend on the color, so each level
|
||||
// is read once here and [`Backdrop::front`] draws any color through the levels.
|
||||
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
|
||||
let mut x = (shown(&color), 1.0f32);
|
||||
let mut passes = vec![];
|
||||
let mut alpha = 1.0f32;
|
||||
let mut alone = 1.0f32;
|
||||
// Whether a level so far read art that is not one color.
|
||||
let mut mixed = false;
|
||||
for (k, step) in steps.iter().enumerate() {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let above = &steps[k + 1..];
|
||||
let scope = above.iter().find(|a| a.isolate);
|
||||
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
|
||||
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
|
||||
let backdrop = match scope {
|
||||
Some(_) if !sampled => ([0.0; 3], 0.0),
|
||||
None if !sampled => (against, 1.0),
|
||||
let (backdrop, one) = match scope {
|
||||
Some(_) if !sampled => (([0.0; 3], 0.0), true),
|
||||
None if !sampled => ((against, 1.0), uniform),
|
||||
// The background itself, as the answer writes it.
|
||||
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
|
||||
None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
|
||||
_ => read(scope.map(|a| &a.within))?,
|
||||
};
|
||||
// The alpha of the art below the level inside the level around it, while a blending level
|
||||
// lies further out (none for a given background).
|
||||
let inner = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
|
||||
_ => 0.0,
|
||||
let (inner, inner_one) = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
|
||||
let ((_, a), one) = read(Some(&around.within))?;
|
||||
(a, one)
|
||||
}
|
||||
_ => (0.0, true),
|
||||
};
|
||||
let source = if !blends(step) {
|
||||
x
|
||||
} else if alone <= 0.0 {
|
||||
(x.0, 0.0)
|
||||
} else {
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
};
|
||||
// A level that isolates its blending carries out the alpha of what it holds composited on
|
||||
// its own.
|
||||
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
|
||||
x = composite(step.blend, source, step.opacity, backdrop);
|
||||
alone = drawn + inner * (1.0 - drawn);
|
||||
}
|
||||
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
|
||||
let ratio = wcag::contrast_ratio(front, against);
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
// A blend mode mixes the color with the art below it pixel by pixel, which one color read for
|
||||
// art of several colors does not stand for, also when that art reaches it through the levels
|
||||
// inside it.
|
||||
mixed |= !one || !inner_one;
|
||||
if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
|
||||
return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
|
||||
}
|
||||
};
|
||||
let [r, g, b] = written;
|
||||
Ok(json!({
|
||||
"ratio": ratio,
|
||||
"against": format!("#{r:02x}{g:02x}{b:02x}"),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
}))
|
||||
let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
|
||||
(_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
|
||||
passes.push(pass);
|
||||
}
|
||||
let stain = if given { None } else { stain_of(s, !need_color) };
|
||||
Ok((color, Backdrop { against, written, passes, stain, rich_black }))
|
||||
}
|
||||
|
||||
/// An object around the proxy's object: one in the document, or a group of the picked object's
|
||||
@@ -1232,7 +1450,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32;
|
||||
/// levels that change what they draw must be the same objects too, since the art below each one is
|
||||
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
|
||||
/// since the row draws over the object's rows below it and the object over the art behind it, and a
|
||||
/// row that blends or is translucent must lie over the same shown rows.
|
||||
/// row that blends or is translucent must lie over the same shown rows, and over a lower row that
|
||||
/// blends, with the same isolation.
|
||||
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
|
||||
let level = |x: &Level, y: &Level| {
|
||||
@@ -1248,10 +1467,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
|
||||
// A row that blends or lets art through draws over the rows below it, read at one point.
|
||||
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
|
||||
// A lower row that blends reads the art behind the object unless the object isolates its
|
||||
// blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending
|
||||
// row at no opacity does not show, nor does a fill row without effects under an opaque solid
|
||||
// Normal fill row without effects, which covers the same shape (a stroke reaches outside it).
|
||||
let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty();
|
||||
let covers = |i: &vectorcraft_doc::AppearanceItem| {
|
||||
plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. })
|
||||
};
|
||||
let over_blended = |d: &Drawn| {
|
||||
over_rows(d)
|
||||
&& d.lower
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers)))
|
||||
};
|
||||
row(a) == row(b)
|
||||
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
|
||||
&& a.blend == b.blend
|
||||
&& (row(a).is_none() || a.isolate == b.isolate)
|
||||
&& (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate)
|
||||
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
|
||||
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
|
||||
&& la.len() == lb.len()
|
||||
@@ -1263,8 +1498,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
|
||||
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
|
||||
/// objects in different translucent or blending groups or layers differ, since the art below each
|
||||
/// such level is read with it hidden.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
|
||||
/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern),
|
||||
/// and the drawing is then the one a solid color in its place would have.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option<Color>, Drawn), String> {
|
||||
let stroke = !s.fill_active;
|
||||
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
|
||||
if if stroke { stroke_mixed } else { fill_mixed } {
|
||||
@@ -1320,20 +1556,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
|
||||
} else {
|
||||
drawing = source()?.unwrap_or_default();
|
||||
}
|
||||
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
|
||||
match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
|
||||
let found = match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Some((color, drawing.clone())),
|
||||
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
|
||||
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity)))
|
||||
}
|
||||
Paint::Gradient(g) => {
|
||||
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity)))
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => Err(no_color()),
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => None,
|
||||
};
|
||||
Ok(match found {
|
||||
Some((color, drawn)) => (Some(color), drawn),
|
||||
None => (None, drawing),
|
||||
})
|
||||
}
|
||||
|
||||
/// The message for an active fill or stroke with no color to measure.
|
||||
fn no_color() -> String {
|
||||
"the active fill or stroke has no color: give `color`".to_string()
|
||||
}
|
||||
|
||||
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
|
||||
@@ -1398,19 +1642,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> s
|
||||
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
|
||||
}
|
||||
|
||||
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
|
||||
/// `color` itself otherwise.
|
||||
fn stained(s: &Session, color: Color) -> Color {
|
||||
let stain = s.active().and_then(|st| {
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
|
||||
});
|
||||
match stain {
|
||||
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
|
||||
None => color,
|
||||
/// The color and amount a fill stains the picked object of a dynamic symbol instance with
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
|
||||
/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None
|
||||
/// or a pattern counts too, as the pick puts a solid color in its place.
|
||||
fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> {
|
||||
let (fill, stroke) = s.proxy_paints();
|
||||
match if s.fill_active { fill } else { stroke } {
|
||||
Paint::Solid { .. } => {}
|
||||
Paint::None | Paint::Pattern { .. } if pick => {}
|
||||
_ => return None,
|
||||
}
|
||||
let st = s.active()?;
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
|
||||
@@ -1455,14 +1701,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
|
||||
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
|
||||
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
|
||||
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
|
||||
/// without artboards.
|
||||
/// without artboards. Also whether the square's pixels are all one color.
|
||||
fn color_below(
|
||||
s: &Session,
|
||||
rich_black: bool,
|
||||
hide: Option<&Part>,
|
||||
full: &[&Part],
|
||||
scope: Option<&Part>,
|
||||
) -> std::result::Result<([f32; 3], f32), String> {
|
||||
) -> std::result::Result<(([f32; 3], f32), bool), String> {
|
||||
super::has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let ids = st.selection.objects.clone();
|
||||
@@ -1591,8 +1837,10 @@ fn color_below(
|
||||
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
|
||||
let px = img.pixels.as_chunks::<4>().0;
|
||||
if px.is_empty() {
|
||||
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
|
||||
return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true));
|
||||
}
|
||||
// Whether the pixels are one color, to within one step of 255 per channel.
|
||||
let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1)));
|
||||
// The pixels are premultiplied: the average color is their sum over their alpha's.
|
||||
let mut sum = [0.0f64; 4];
|
||||
for p in px {
|
||||
@@ -1602,10 +1850,10 @@ fn color_below(
|
||||
}
|
||||
let alpha = sum[3] / (px.len() as f64 * 255.0);
|
||||
if alpha <= 0.0 {
|
||||
return Ok(([0.0; 3], 0.0));
|
||||
return Ok((([0.0; 3], 0.0), uniform));
|
||||
}
|
||||
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
|
||||
Ok((rgb, alpha as f32))
|
||||
Ok(((rgb, alpha as f32), uniform))
|
||||
}
|
||||
|
||||
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Three-Point Arc",
|
||||
[],
|
||||
None,
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`), join?: bool (default false)} → {id, cx, cy, radius, sweep, joined?}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. With `join`, an end of the arc on an end of an editable open path (inside the isolated group in isolation mode) joins the arc to that path, which keeps its look and, when one end joins, its direction (a path in the selection comes first); with both ends on open path ends the second path joins too, or the path closes when both are its own ends. The result then has `joined: true` and `id` is the joined path (or its compound path). A `join` that is not true or false is an error. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
three_point_arc
|
||||
),
|
||||
@@ -747,7 +747,8 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
|
||||
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
|
||||
/// leaving the end `at` names toward `toward`. With `join`, joined to the open paths whose ends
|
||||
/// its ends lie on ([`super::path::join_arc`]). One undo step, named as an Arc tool drag is.
|
||||
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.threePointArc";
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
|
||||
@@ -774,8 +775,32 @@ fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
|
||||
};
|
||||
let join = match p.get("join") {
|
||||
None => false,
|
||||
Some(Value::Bool(on)) => *on,
|
||||
Some(_) => return Err(bad(C, "`join` must be true or false")),
|
||||
};
|
||||
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
|
||||
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
|
||||
let ends = if join {
|
||||
let st = s.doc()?;
|
||||
let selected = st.selection.objects.clone();
|
||||
let find = |at| super::path::open_end_at(&st.doc, st.isolation, &selected, at);
|
||||
(find(start), find(end))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
if ends.0.is_some() || ends.1.is_some() {
|
||||
let sub = path.subpaths.first().cloned().ok_or_else(|| bad(C, "no arc fits these points"))?;
|
||||
let id = s.edit("Arc", |d, sel| {
|
||||
let id = super::path::join_arc(d, &sub, ends.0, ends.1)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
return Ok(
|
||||
json!({ "id": id.0, "joined": true, "cx": arc.center.x, "cy": arc.center.y, "radius": arc.radius, "sweep": arc.sweep.to_degrees() }),
|
||||
);
|
||||
}
|
||||
let look = s.new_art_look(
|
||||
vectorcraft_color::Paint::None,
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
|
||||
@@ -954,9 +954,43 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
Ok(selection_roots(s.doc()?))
|
||||
}
|
||||
|
||||
/// [`selected_roots`] of one document's selection.
|
||||
/// [`selected_roots`] of one document's selection, found once for each document version and set of selected
|
||||
/// objects and kept on this thread: the menus' enabled checks read it many times for one selection.
|
||||
pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
|
||||
roots_of(&st.doc, st.selection.in_paint_order(&st.doc))
|
||||
let at = Arc::as_ptr(&st.doc);
|
||||
ROOTS.with_borrow_mut(|kept| {
|
||||
if let Some((doc, objects, roots)) = kept.as_ref()
|
||||
&& doc.as_ptr() == at
|
||||
&& *objects == st.selection.objects
|
||||
{
|
||||
return roots.clone();
|
||||
}
|
||||
#[cfg(test)]
|
||||
ROOTS_FOUND.set(ROOTS_FOUND.get() + 1);
|
||||
let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
|
||||
*kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone()));
|
||||
roots
|
||||
})
|
||||
}
|
||||
|
||||
/// The selected objects and roots of the last [`selection_roots`], with the document version they belong to. It is
|
||||
/// held weakly, so its address is not reused while it is kept, and an edit in place moves it.
|
||||
type KeptRoots = Option<(std::sync::Weak<Document>, Vec<NodeId>, Vec<NodeId>)>;
|
||||
|
||||
thread_local! {
|
||||
static ROOTS: std::cell::RefCell<KeptRoots> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`selection_roots`] found the roots on this thread.
|
||||
static ROOTS_FOUND: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`selection_roots`] has found the roots on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn roots_found() -> u64 {
|
||||
ROOTS_FOUND.get()
|
||||
}
|
||||
|
||||
/// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected:
|
||||
|
||||
@@ -347,3 +347,26 @@ fn direct_selection_cut_timing() {
|
||||
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected roots are found once for a document version and its selected objects, however many enabled checks
|
||||
/// read them, and found again after the selection changes, after an edit, and for another selection.
|
||||
#[test]
|
||||
fn selected_roots_are_found_once_for_each_document_and_selection() {
|
||||
let mut s = session(30, square);
|
||||
let all = selected_roots(&s).unwrap();
|
||||
assert_eq!(all.len(), 30);
|
||||
let before = roots_found();
|
||||
for _ in 0..20 {
|
||||
assert_eq!(selected_roots(&s).unwrap(), all);
|
||||
}
|
||||
assert_eq!(roots_found() - before, 0, "reading the same selection again finds nothing");
|
||||
s.execute("select.set", &json!({"ids": [all[3].0, all[7].0]})).unwrap();
|
||||
assert_eq!(selected_roots(&s).unwrap(), vec![all[3], all[7]]);
|
||||
assert_eq!(roots_found() - before, 1, "a new selection is found once");
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let grouped = selected_roots(&s).unwrap();
|
||||
assert_eq!(grouped.len(), 1, "the group is the one root: {grouped:?}");
|
||||
assert_ne!(grouped, vec![all[3], all[7]]);
|
||||
selected_roots(&s).unwrap();
|
||||
assert_eq!(roots_found() - before, 2, "an edit finds the roots once again");
|
||||
}
|
||||
@@ -268,16 +268,22 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
|
||||
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
}
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts))
|
||||
// A placeholder page's fonts aren't the art's.
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts, Default::default()))
|
||||
}
|
||||
|
||||
/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it
|
||||
/// can't be decoded.
|
||||
fn editing_copy_alone(decoded: &std::result::Result<Vec<u8>, String>, opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
/// can't be decoded, with `widths`, the widths the file's PDF part gives the characters of its
|
||||
/// fonts, which tell installed copies of a font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]).
|
||||
fn editing_copy_alone(
|
||||
decoded: &std::result::Result<Vec<u8>, String>,
|
||||
opts: &LoadOptions,
|
||||
widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>)> {
|
||||
decoded
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names))
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names, widths))
|
||||
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
|
||||
}
|
||||
|
||||
@@ -473,6 +479,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
Err(e) => Err(err(e)),
|
||||
};
|
||||
let mut read = restore_or_import(editing, || {
|
||||
// The widths the PDF part gives the characters of its fonts, which tell installed
|
||||
// copies of a font apart: read once, when the editing copy is.
|
||||
let page_widths = std::cell::OnceCell::new();
|
||||
let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone();
|
||||
// Type all from the text document and nothing that needs the PDF part: the layers
|
||||
// alone, the PDF part not imported. Else what was read of the layers is kept for
|
||||
// reading them with the PDF part.
|
||||
@@ -480,7 +490,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
|
||||
{
|
||||
let pages = o.trim_pages();
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names) {
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) {
|
||||
Ok((mut doc, warnings)) => {
|
||||
doc.setup.bleed = pages.bleed;
|
||||
editing_data = true;
|
||||
@@ -502,9 +512,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// decoded draws nothing either): its notes are at most the page's own.
|
||||
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
|
||||
let copy_alone = || match &private {
|
||||
Some(private) => Some(editing_copy_alone(private, opts)),
|
||||
Some(private) => Some(editing_copy_alone(private, opts, widths())),
|
||||
None if layers.is_some() => {
|
||||
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
|
||||
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -516,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => {
|
||||
let layers = layers.or_else(|| private.map(vectorcraft_eps::AiLayers::decoded));
|
||||
let layers = layers.or_else(|| private.map(|p| vectorcraft_eps::AiLayers::decoded(p).with_page_widths(widths())));
|
||||
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2234,3 +2234,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() {
|
||||
assert_eq!(r["restored"], json!(true), "{r}");
|
||||
assert_eq!(open_rows(&s).1, ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the
|
||||
/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in
|
||||
/// a subset of that font that gives each character the width `width` gives it, in thousandths of an
|
||||
/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is
|
||||
/// 200 × 100 pt, and the page `page_width` × 100.
|
||||
fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec<u8> {
|
||||
let story = "Hamburg";
|
||||
let n = story.chars().count() + 1;
|
||||
let document = format!(
|
||||
"/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
|
||||
/1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
|
||||
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \
|
||||
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
|
||||
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n"
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n";
|
||||
let (art, drawn) =
|
||||
if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") };
|
||||
let body = format!(
|
||||
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
|
||||
ai::layer("Art", &art),
|
||||
lines.join("\n")
|
||||
);
|
||||
let data = ai::editing_data(200.0, 100.0, &body);
|
||||
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect();
|
||||
let page = PdfPage {
|
||||
resources: format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
|
||||
widths.join(" ")
|
||||
),
|
||||
entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)),
|
||||
// A page that is only type, with its art box, isn't a placeholder.
|
||||
art: Some([0.0, 0.0, page_width, 100.0]),
|
||||
..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET"))
|
||||
};
|
||||
pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None)
|
||||
}
|
||||
|
||||
/// Type from the text document of a `.ai` whose font record keeps no version, where two installed
|
||||
/// copies of the font share its PostScript name, family and style and differ in their widths, is
|
||||
/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether
|
||||
/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF
|
||||
/// part is only type (read after the layers alone, on a page of another size, were not used).
|
||||
#[test]
|
||||
fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() {
|
||||
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular"));
|
||||
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
|
||||
// (a square beside the type, the page's width, the options, whether the PDF part is imported)
|
||||
let cases = [
|
||||
(true, 200.0, &LoadOptions::default(), false),
|
||||
(true, 200.0, &trim, true),
|
||||
(false, 200.0, &LoadOptions::default(), false),
|
||||
(false, 200.0, &trim, true),
|
||||
(false, 260.0, &LoadOptions::default(), true),
|
||||
];
|
||||
for (square, page_width, opts, imported) in cases {
|
||||
let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width);
|
||||
let before = vectorcraft_pdf::imports_of(&file);
|
||||
let loaded = load_with("copies.ai", &file, opts).unwrap();
|
||||
let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings);
|
||||
assert!(loaded.editing_data, "{case}");
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}");
|
||||
let art = loaded.doc.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), 1 + usize::from(square), "{case}");
|
||||
let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") };
|
||||
assert_eq!(t.plain_text(), "Hamburg");
|
||||
assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded
|
||||
/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives.
|
||||
fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
for (inter, version) in [(true, "1.0"), (false, "1.1")] {
|
||||
let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap();
|
||||
assert_eq!(db.add_font(font), 1);
|
||||
}
|
||||
let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap();
|
||||
move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em()
|
||||
}
|
||||
|
||||
/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that
|
||||
/// copy's version in its font record, so it opens in the same copy again, from the editing copy
|
||||
/// alone as from the whole file.
|
||||
#[test]
|
||||
fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() {
|
||||
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular"));
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap();
|
||||
let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let versions = |doc: &vectorcraft_doc::Document| -> Vec<String> {
|
||||
let art = doc.layers[0].children().unwrap();
|
||||
art.iter()
|
||||
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None })
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}");
|
||||
let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings);
|
||||
let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap();
|
||||
assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]);
|
||||
}
|
||||
@@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD
|
||||
/// file with many more pixels keeps its corners when the image is tiny: the new image's transform
|
||||
/// is the old one scaled down to the new pixel size, which is invertible however small it is.
|
||||
#[test]
|
||||
fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted");
|
||||
let plane = vec![255u8; 2000 * 2000];
|
||||
let zero = vec![0u8; 2000 * 2000];
|
||||
let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero]));
|
||||
let cut = write_file(&dir, "big.psd", &big);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
|
||||
let r = s
|
||||
.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]}))
|
||||
.unwrap();
|
||||
let old = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [old.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted");
|
||||
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap();
|
||||
let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
|
||||
assert!(image.is_distorted_image());
|
||||
assert_eq!(image.image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort
|
||||
/// by a DCS file keeps the image's corners: the DCS file's image fills them.
|
||||
#[test]
|
||||
fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates());
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap();
|
||||
let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
|
||||
assert!(new.is_distorted_image(), "the DCS file's image takes the corners");
|
||||
assert_eq!(new.image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
|
||||
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
|
||||
|
||||
@@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes
|
||||
/// its corners, and its slices cover what the corners put their part of the pixels on.
|
||||
#[test]
|
||||
fn slices_placed_over_a_distorted_image_follow_its_corners() {
|
||||
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
|
||||
s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap();
|
||||
assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
assert!(image.is_distorted_image());
|
||||
let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") };
|
||||
// The top left quarter of the 20 × 20 px canvas.
|
||||
let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0);
|
||||
let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap();
|
||||
let got = slices(&s)[0].0;
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_files_are_placed_without_their_slices() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
|
||||
|
||||
@@ -1314,7 +1314,7 @@ fn refill_distorted(
|
||||
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
|
||||
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
|
||||
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
|
||||
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
pub(super) fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
|
||||
let apply = |p: vectorcraft_geom::Point| {
|
||||
let w = g * p.x + h * p.y + i;
|
||||
|
||||
@@ -2000,6 +2000,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
Some(ids) => ids,
|
||||
None => super::edit::selected_roots(s)?,
|
||||
};
|
||||
// Read before the default is recolored, so that a bad `target` or `aligned` is refused with nothing selected too.
|
||||
let item = item_target(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
let def = if stroke { &mut s.paint.stroke } else { &mut s.paint.fill };
|
||||
let changed = super::colorcmds::map_paint(def, f);
|
||||
@@ -2007,7 +2009,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
s.remember_paint(&shown);
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
let item = item.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handles",
|
||||
[],
|
||||
None,
|
||||
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
|
||||
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
|
||||
has_doc,
|
||||
move_handles
|
||||
),
|
||||
@@ -643,8 +643,9 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A move by nothing changes only the kind of anchors that become corners: those with both
|
||||
// handles listed, or every listed one with `independent`.
|
||||
// The other anchors are left out, so a live shape that only they lie on is not expanded.
|
||||
if d == Vec2::ZERO {
|
||||
let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| {
|
||||
anchors.retain(|&(id, si, ai), &mut (inn, out)| {
|
||||
(independent || (inn && out))
|
||||
&& doc
|
||||
.node(id)
|
||||
@@ -652,7 +653,7 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
|
||||
.is_some_and(|a| a.kind != AnchorKind::Corner)
|
||||
});
|
||||
if !corners {
|
||||
if anchors.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
@@ -1593,6 +1594,91 @@ fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize
|
||||
Ok(compound_or_self(d, a))
|
||||
}
|
||||
|
||||
/// An end of an open subpath of an editable path (not a guide) at `at`: the path, the subpath and
|
||||
/// whether the end is the subpath's first anchor. In isolation mode (`scope`), only a path inside
|
||||
/// the isolated node counts. Among several, one in or inside the selection `selected` comes first,
|
||||
/// then the last in paint order.
|
||||
pub(super) fn open_end_at(d: &Document, scope: Option<NodeId>, selected: &[NodeId], at: Point) -> Option<(NodeId, usize, bool)> {
|
||||
let editable = d.editable();
|
||||
let mut found: Option<((NodeId, usize, bool), bool)> = None;
|
||||
d.walk(|n| {
|
||||
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
|
||||
if !editable(n.id) {
|
||||
return;
|
||||
}
|
||||
let chain = d.ancestry(n.id).unwrap_or_default();
|
||||
if scope.is_some_and(|s| !chain.contains(&s)) {
|
||||
return;
|
||||
}
|
||||
let chosen = chain.iter().any(|id| selected.contains(id));
|
||||
for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed) {
|
||||
let Some((first, last)) = end_points(sp) else { continue };
|
||||
let end = if last.distance(at) < 1e-6 {
|
||||
false
|
||||
} else if first.distance(at) < 1e-6 {
|
||||
true
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if found.is_none_or(|(_, was)| chosen || !was) {
|
||||
found = Some(((n.id, si, end), chosen));
|
||||
}
|
||||
}
|
||||
});
|
||||
found.map(|(end, _)| end)
|
||||
}
|
||||
|
||||
/// `sp`, an open subpath whose end (its first anchor when `at_first`) lies on an end of `arc`
|
||||
/// (its first anchor when `arc_at_start`), with `arc` added there: one subpath running the way
|
||||
/// `sp` runs. The anchor where they meet is `sp`'s, with its handle on the arc's side taken from
|
||||
/// the arc.
|
||||
fn splice(sp: &SubPath, at_first: bool, arc: &SubPath, arc_at_start: bool) -> SubPath {
|
||||
let mut arc = arc.clone();
|
||||
if arc_at_start == at_first {
|
||||
arc.reverse();
|
||||
}
|
||||
let mut out = sp.clone();
|
||||
if at_first {
|
||||
let meet = arc.anchors.pop();
|
||||
if let (Some(meet), Some(first)) = (meet, out.anchors.first_mut()) {
|
||||
first.h_in = meet.h_in;
|
||||
}
|
||||
arc.anchors.extend(out.anchors);
|
||||
out.anchors = arc.anchors;
|
||||
} else {
|
||||
if !arc.anchors.is_empty() {
|
||||
let meet = arc.anchors.remove(0);
|
||||
if let Some(last) = out.anchors.last_mut() {
|
||||
last.h_out = meet.h_out;
|
||||
}
|
||||
}
|
||||
out.anchors.extend(arc.anchors);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The arc `arc` joined to the open path ends `start` (at its first anchor) and `end` (at its
|
||||
/// last), as [`open_end_at`] gives them, at least one of them. The arc joins the path at `start`
|
||||
/// first, keeping that path's direction and look, and then, when `end` is an end of another open
|
||||
/// subpath, that subpath joins it as Join joins two paths; when `end` is the other end of the same
|
||||
/// subpath, the subpath closes. Returns what to select: the joined path, or its compound path.
|
||||
pub(super) fn join_arc(d: &mut Document, arc: &SubPath, start: Option<(NodeId, usize, bool)>, end: Option<(NodeId, usize, bool)>) -> Result<NodeId> {
|
||||
let err = || EngineError::Other("join needs open paths".into());
|
||||
let ((id, si, at_first), arc_at_start, rest) = match (start, end) {
|
||||
(Some(s), e) => (s, true, e),
|
||||
(None, Some(e)) => (e, false, None),
|
||||
(None, None) => return Err(err()),
|
||||
};
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).filter(|sp| !sp.closed && !sp.anchors.is_empty()).ok_or_else(err)?;
|
||||
*sp = splice(sp, at_first, arc, arc_at_start);
|
||||
match rest {
|
||||
// The arc's far end is the first anchor of the joined subpath when it was added before it.
|
||||
Some((other, osi, other_first)) => join_pair(d, (id, si), (other, osi), (at_first, !other_first), None),
|
||||
None => Ok(compound_or_self(d, id)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>;
|
||||
|
||||
pub(super) fn anchor_targets(s: &Session) -> Result<AnchorTargets> {
|
||||
|
||||
@@ -57,7 +57,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
use super::fileio::{self, Format, RasterImage};
|
||||
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 12
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
|
||||
|
||||
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
|
||||
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by
|
||||
/// its file's clipping path or not (`new_image`); other objects keep their centre.
|
||||
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
|
||||
let image = replace_measured(d, old, new_image);
|
||||
@@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
|
||||
let full = Affine::scale_non_uniform(sx, sy);
|
||||
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
|
||||
if im.xf.determinant().abs() > 1e-12 {
|
||||
if Homography::affine_is_invertible(im.xf) {
|
||||
return im.xf * full.inverse() * Affine::translate(centre - natural.center());
|
||||
}
|
||||
}
|
||||
@@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
}
|
||||
|
||||
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
|
||||
/// image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a
|
||||
/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
|
||||
match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
|
||||
@@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod
|
||||
}
|
||||
}
|
||||
|
||||
/// What Replace does when the image it measures, `old`, is distorted and the art placed is a
|
||||
/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s
|
||||
/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and
|
||||
/// the map from the art's natural box to the page through those corners, which a PSD file's slices
|
||||
/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't
|
||||
/// fill ([`Node::set_image_corners`]).
|
||||
fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> {
|
||||
let NodeKind::Image(im) = &old.kind else { return None };
|
||||
let q = old.image_quad()?;
|
||||
let (pixels, width, height) = match art {
|
||||
Art::Image(img, _) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
(Affine::scale_non_uniform(sx, sy), img.width, img.height)
|
||||
}
|
||||
Art::Dcs(a) => (a.xf, a.img.width, a.img.height),
|
||||
_ => return None,
|
||||
};
|
||||
if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) {
|
||||
return None;
|
||||
}
|
||||
let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height));
|
||||
let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new)));
|
||||
probe.set_image_corners(q).ok()?;
|
||||
let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?;
|
||||
Some((xf * pixels.inverse(), q, page))
|
||||
}
|
||||
|
||||
/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as
|
||||
/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping
|
||||
/// path is drawn through them as the pixels are. `None` when the corners can't hold the image.
|
||||
fn with_corners(mut node: Node, q: [Point; 4]) -> Option<Node> {
|
||||
match &mut node.kind {
|
||||
NodeKind::Image(_) => node.set_image_corners(q).ok()?,
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let [path, image] = &mut children[..] else { return None };
|
||||
let image = Arc::make_mut(image);
|
||||
let NodeKind::Image(im) = &image.kind else { return None };
|
||||
if !Homography::affine_is_invertible(im.xf) {
|
||||
return None;
|
||||
}
|
||||
// The clipping path in the image's pixels, which its transform placed on the page.
|
||||
let to_pixels = im.xf.inverse();
|
||||
image.set_image_corners(q).ok()?;
|
||||
let map = image.image_map()?;
|
||||
let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None };
|
||||
p.transform(to_pixels);
|
||||
*p = super::links::warped(p, &map)?;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
/// `rect` fitted with `natural`'s aspect, centred.
|
||||
fn fit(natural: Rect, r: Rect) -> Affine {
|
||||
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
|
||||
@@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
|
||||
}
|
||||
let natural = loaded.natural;
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`), which a
|
||||
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
|
||||
// bounds of what it replaces, so a distorted image there is not refused.
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`). When that image
|
||||
// is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other
|
||||
// art is refused. Type, and any other object it measures, is placed by the bounds of what it
|
||||
// replaces, so a distorted image there is not refused.
|
||||
let mut distorted = None;
|
||||
let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..));
|
||||
if let Some(o) = old_node
|
||||
&& !is_text
|
||||
{
|
||||
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
|
||||
let image = replace_measured(&st.doc, o, new_image);
|
||||
if image.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(PLACE, image.id));
|
||||
let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?;
|
||||
distorted = Some((image.id, fit));
|
||||
}
|
||||
}
|
||||
let m = match (old_node, rect) {
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
|
||||
(Some(_), _) if let Some((_, (m, ..))) = distorted => m,
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image),
|
||||
(None, Some(r)) => fit(natural, r),
|
||||
// Its artboard's bottom-left corner on the target's.
|
||||
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
|
||||
@@ -908,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
if let Art::Dcs(a) = &loaded.art {
|
||||
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
|
||||
}
|
||||
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
|
||||
// A PSD file's slices move and scale with its art, through a distorted image's corners when
|
||||
// it takes them; one that would leave the canvas is left out.
|
||||
let read_count = read_slices.len();
|
||||
let slices: Slices = read_slices
|
||||
.into_iter()
|
||||
.filter_map(|(r, o)| {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
|
||||
let placed = match distorted {
|
||||
Some((_, (_, _, page))) => page.map_rect_bbox(r)?,
|
||||
None => {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c))
|
||||
}
|
||||
};
|
||||
super::slices::slice_rect_ok(placed).then_some((placed, o))
|
||||
})
|
||||
.collect();
|
||||
@@ -924,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
|
||||
let (into, index) = match old {
|
||||
Some(old) => {
|
||||
|
||||
@@ -1468,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A heavy plug-in is installed once a person agrees.
|
||||
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
|
||||
plugin.manifest().name
|
||||
"“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1615,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !refused.is_empty() {
|
||||
v["refusedCommands"] = json!(refused);
|
||||
}
|
||||
let translations = &plugin.manifest().translations;
|
||||
if !translations.is_empty() {
|
||||
v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null);
|
||||
}
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -2447,7 +2451,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
|
||||
@@ -682,6 +682,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"text.thread.info",
|
||||
"text.thread.releaseSelection",
|
||||
"text.thread.remove",
|
||||
"text.thread.setNeighbor",
|
||||
"text.touchType",
|
||||
"threeD.addGraphic",
|
||||
"threeD.mapArt",
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::script;
|
||||
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
|
||||
|
||||
/// The extensions of the scripts `script.run` takes as a file, in any case.
|
||||
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
|
||||
pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"];
|
||||
|
||||
/// Does `path` name a file `script.run` takes?
|
||||
pub fn runs(path: &str) -> bool {
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Installed Scripts",
|
||||
[],
|
||||
None,
|
||||
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
"{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
@@ -195,8 +195,10 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
if s.script_frames && !answers.is_empty() {
|
||||
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
|
||||
}
|
||||
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
|
||||
let fuel = max_fuel(p)?;
|
||||
let installed = switch_or(p, "installed", false, "script.run")?;
|
||||
let module = switch_or(p, "module", script::include::module_script(path), "script.run")?;
|
||||
let mut checked_real = None;
|
||||
let text = match (path, source) {
|
||||
(Some(""), None) => return Err(param("`path` is empty")),
|
||||
@@ -212,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
return Err(EngineError::Other(COMPILED.to_string()));
|
||||
}
|
||||
if !runs(path) {
|
||||
return Err(param("`path` must name a .js or .jsx file"));
|
||||
return Err(param("`path` must name a .js, .mjs or .jsx file"));
|
||||
}
|
||||
// One byte more than a script may have shows that the file is too large.
|
||||
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
|
||||
@@ -241,6 +243,8 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
module,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -442,6 +446,8 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
module: script::include::module_script(path.to_str()),
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
self.script_start(request).map_err(|e| {
|
||||
|
||||
@@ -148,8 +148,11 @@ macro_rules! style_cmds {
|
||||
};
|
||||
}
|
||||
|
||||
/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes.
|
||||
pub const MAX_LOAD_BYTES: usize = 64 << 20;
|
||||
|
||||
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = style_cmds!(
|
||||
@@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
|
||||
_ => "textStyle.loadAll".to_string(),
|
||||
};
|
||||
let path = str_param(p, "path");
|
||||
let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => super::fileio::read_file(path)?,
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?,
|
||||
let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20));
|
||||
let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(),
|
||||
(None, Some(text), _) => text.as_bytes().into(),
|
||||
(None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(),
|
||||
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_LOAD_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let file = str_param(p, "name").or(path).unwrap_or("Styles");
|
||||
let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?;
|
||||
if src.preview_only {
|
||||
|
||||
@@ -896,6 +896,27 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit.
|
||||
#[test]
|
||||
fn loading_refuses_a_file_larger_than_64_mb() {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Big.vectorcraft");
|
||||
std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()}));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8);
|
||||
let r = s.execute("paraStyle.load", &json!({"dataBase64": b64}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
let text = " ".repeat(MAX_LOAD_BYTES + 1);
|
||||
let r = s.execute("textStyle.loadAll", &json!({"data": text}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or
|
||||
/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped.
|
||||
#[test]
|
||||
|
||||
@@ -59,6 +59,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
break_thread
|
||||
),
|
||||
cmd!(
|
||||
"text.thread.setNeighbor",
|
||||
"Thread Text",
|
||||
[],
|
||||
None,
|
||||
"{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}",
|
||||
has_doc,
|
||||
set_neighbor
|
||||
),
|
||||
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
|
||||
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
|
||||
}),
|
||||
@@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on
|
||||
/// a path, each once, or `id` alone when it is in no thread.
|
||||
fn chain_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(d, id);
|
||||
let mut seen = Ids::default();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
fn chain_ids(chains: &[&[NodeId]]) -> Value {
|
||||
json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link.
|
||||
fn set_neighbor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.thread.setNeighbor";
|
||||
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
|
||||
let next = match p.get("side").and_then(Value::as_str) {
|
||||
Some("next") => true,
|
||||
Some("previous") => false,
|
||||
_ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")),
|
||||
};
|
||||
let neighbor = match p.get("neighbor") {
|
||||
None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(checked_id(s, v, C)?),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if text_of(d, id).is_none() {
|
||||
return Err(bad(C, "`id` must be area type or type on a path"));
|
||||
}
|
||||
let locked = |frames: &[NodeId]| {
|
||||
let editable = d.editable();
|
||||
frames.iter().any(|f| !editable(*f))
|
||||
};
|
||||
let chain = chain_of(d, id);
|
||||
let Some(n) = neighbor else {
|
||||
// Break the link on that side: the frames before it and the frames after it.
|
||||
let i = chain.iter().position(|f| *f == id).unwrap_or(0);
|
||||
let at = if next { i + 1 } else { i };
|
||||
if at == 0 || at >= chain.len() {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])}));
|
||||
}
|
||||
if locked(&chain) {
|
||||
return Err(bad(C, "a frame of the story is hidden or locked"));
|
||||
}
|
||||
let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec());
|
||||
let cut: Ids = chain.iter().copied().collect();
|
||||
s.edit("Break Thread", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f)));
|
||||
for part in [&head, &tail] {
|
||||
if part.len() >= 2 {
|
||||
d.text_threads.push(part.clone());
|
||||
}
|
||||
}
|
||||
// The first frame after the break starts its story, which flows again on this edit so
|
||||
// that its numbered paragraphs count from 1.
|
||||
if let Some(f) = tail.first() {
|
||||
touch(d, *f);
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues
|
||||
{
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])}));
|
||||
};
|
||||
if n == id {
|
||||
return Err(bad(C, "a frame cannot be linked to itself"));
|
||||
}
|
||||
if text_of(d, n).is_none() {
|
||||
return Err(bad(C, "`neighbor` must be area type or type on a path"));
|
||||
}
|
||||
// `first` is to flow into `second`.
|
||||
let (first, second) = if next { (id, n) } else { (n, id) };
|
||||
let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) };
|
||||
if a.contains(&second) {
|
||||
if a.windows(2).any(|w| w == [first, second]) {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&a])}));
|
||||
}
|
||||
return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it"));
|
||||
}
|
||||
if a.last() != Some(&first) {
|
||||
return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0)));
|
||||
}
|
||||
if b.first() != Some(&second) {
|
||||
return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0)));
|
||||
}
|
||||
if locked(&a) || locked(&b) {
|
||||
return Err(bad(C, "a frame of either story is hidden or locked"));
|
||||
}
|
||||
let joined: Vec<NodeId> = a.iter().chain(&b).copied().collect();
|
||||
let affected: Ids = joined.iter().copied().collect();
|
||||
s.edit("Thread Text", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f)));
|
||||
d.text_threads.push(joined.clone());
|
||||
// Force a re-flow of the joined story on this edit.
|
||||
touch(d, first);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"changed": true, "threads": chain_ids(&[&joined])}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -715,6 +715,15 @@ impl ScriptScope {
|
||||
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
match self.read_unless(path, max, |_| false)? {
|
||||
(real, Some(bytes)) => Ok((real, bytes)),
|
||||
(_, None) => Err(ScriptRead::Failed("the file was not read".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened:
|
||||
/// → its real path and no bytes.
|
||||
pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option<Vec<u8>>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
@@ -730,6 +739,9 @@ impl ScriptScope {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
if known(&real) {
|
||||
return Ok((real, None));
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
if !meta.is_file() {
|
||||
@@ -747,7 +759,7 @@ impl ScriptScope {
|
||||
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok((real, bytes))
|
||||
Ok((real, Some(bytes)))
|
||||
}
|
||||
|
||||
/// The first granted folder, as people read it (`None` for a script given as text).
|
||||
@@ -966,6 +978,21 @@ mod tests {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A file the caller already has is not opened: its size is not checked and no byte is read.
|
||||
#[test]
|
||||
fn a_known_script_file_is_not_read_again() {
|
||||
let (base, _) = folders("known");
|
||||
std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap();
|
||||
let scope = ScriptScope::of_folder(&base.join("in"));
|
||||
let path = base.join("in/big.js");
|
||||
assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge));
|
||||
let real = std::fs::canonicalize(&path).unwrap();
|
||||
assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None)));
|
||||
assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64)));
|
||||
assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind
|
||||
/// only one grants is not granted.
|
||||
#[test]
|
||||
|
||||
@@ -127,6 +127,12 @@ impl HistoryEntry {
|
||||
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
|
||||
}
|
||||
|
||||
/// A number no other step takes ([`History::step`]). Undo and Redo make the step they move
|
||||
/// with a new number, and so does an edit merged into the newest step.
|
||||
pub fn serial(&self) -> u64 {
|
||||
self.serial
|
||||
}
|
||||
|
||||
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
|
||||
/// document before the undo, whose next state is now `now` (that step's document). Its figures
|
||||
/// are that step's the other way round when `doc` is still the document they were taken
|
||||
|
||||
@@ -373,6 +373,9 @@ pub struct Session {
|
||||
pub(crate) startup_failures: Vec<(String, String)>,
|
||||
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
|
||||
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
|
||||
/// The styles the steps of a batch a script runs removed or renamed and the documents they
|
||||
/// reverted ([`script::note_style_lists`]).
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// The desktop app supplies each window by (document uid, runtime window identity) while a
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
|
||||
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
|
||||
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
|
||||
//!
|
||||
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
|
||||
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
|
||||
//! they are the Actions panel's.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference does not state:
|
||||
//! - The action and its set are matched by their exact names; a name that matches no action, or
|
||||
//! more than one, throws before any step runs.
|
||||
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
|
||||
//! the run's transaction and its one undo step for each changed document, it is counted as a host
|
||||
//! call, it reads and writes files only where the script may, and a step that fails is put back
|
||||
//! and throws an error that names the step and the action, while the steps before it stay done.
|
||||
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
|
||||
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
|
||||
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
|
||||
//! another action, so it cannot play itself.
|
||||
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
|
||||
//! changes nothing.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostMember};
|
||||
|
||||
use super::{Host, Link, command, current, refused_to_scripts};
|
||||
|
||||
/// The most actions a run's request may carry.
|
||||
pub const MAX_ACTIONS: usize = 4096;
|
||||
/// The most steps one action may have, after a `command.batch` step gives its own steps.
|
||||
pub const MAX_ACTION_STEPS: usize = 10_000;
|
||||
/// The most steps the actions of one request may have in all.
|
||||
pub const MAX_ALL_STEPS: usize = 100_000;
|
||||
/// The most bytes of the request's actions, as JSON.
|
||||
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
|
||||
/// The longest name of an action or a set, in bytes.
|
||||
pub const MAX_NAME_BYTES: usize = 1024;
|
||||
/// The longest command id of a step, in bytes.
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
/// The command id of a stop, which waits for the person in the Actions panel.
|
||||
pub const STOP_STEP: &str = "action.stop";
|
||||
|
||||
/// An action a run can play: its set's name, its name and the steps playback runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Playable {
|
||||
set: String,
|
||||
name: String,
|
||||
steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
|
||||
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
|
||||
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Step {
|
||||
place: String,
|
||||
id: String,
|
||||
params: Value,
|
||||
bytes: u64,
|
||||
artboard: Option<u64>,
|
||||
}
|
||||
|
||||
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
|
||||
/// step's place in the action (1 for the first; default its place in the list), within the limits
|
||||
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
|
||||
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
|
||||
let Some(v) = v else { return Ok(Vec::new()) };
|
||||
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
|
||||
if list.len() > MAX_ACTIONS {
|
||||
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
|
||||
}
|
||||
if let Some(place) = super::too_deep(v) {
|
||||
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
|
||||
}
|
||||
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
|
||||
return Err("`actions` is larger than 16 MiB".into());
|
||||
}
|
||||
let mut all = 0usize;
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for (i, a) in list.iter().enumerate() {
|
||||
let at = format!("`actions[{i}]`");
|
||||
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(a, &["set", "name", "steps"], &at)?;
|
||||
let set = name_of(a, "set", &at)?;
|
||||
let name = name_of(a, "name", &at)?;
|
||||
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
|
||||
let mut steps = Vec::new();
|
||||
for (j, s) in given.iter().enumerate() {
|
||||
let at = format!("{at}.steps[{j}]");
|
||||
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(s, &["command", "params", "step"], &at)?;
|
||||
let place = match s.get("step") {
|
||||
None => (j + 1).to_string(),
|
||||
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
|
||||
Some(n) => n.to_string(),
|
||||
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
|
||||
},
|
||||
};
|
||||
let (id, params) = command_of(s, &at)?;
|
||||
match params.get("commands") {
|
||||
Some(Value::Array(inner)) if id == "command.batch" => {
|
||||
// The batch's `artboard`, for its steps that act on the active artboard, as
|
||||
// `command.batch` reads it.
|
||||
let artboard = params.get("artboard").and_then(Value::as_u64);
|
||||
for (k, c) in inner.iter().enumerate() {
|
||||
let at = format!("{at}.params.commands[{k}]");
|
||||
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
|
||||
let (id, params) = command_of(c, &at)?;
|
||||
if id == "command.batch" {
|
||||
return Err(format!("{at} is a command.batch inside a command.batch"));
|
||||
}
|
||||
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
|
||||
}
|
||||
}
|
||||
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
|
||||
_ => steps.push(step(place, id, params, None)),
|
||||
}
|
||||
if steps.len() > MAX_ACTION_STEPS {
|
||||
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
|
||||
}
|
||||
}
|
||||
all += steps.len();
|
||||
if all > MAX_ALL_STEPS {
|
||||
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
|
||||
}
|
||||
out.push(Playable { set, name, steps });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Playable {
|
||||
/// The steps the action runs.
|
||||
pub fn len(&self) -> usize {
|
||||
self.steps.len()
|
||||
}
|
||||
|
||||
/// Whether the action runs no step.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.steps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
|
||||
match o.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
|
||||
match o.get(key) {
|
||||
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
|
||||
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
|
||||
_ => Err(format!("{at}.{key} must be a string")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A step's `command` and `params` (default `{}`).
|
||||
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
|
||||
let id = match o.get("command") {
|
||||
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
|
||||
_ => return Err(format!("{at}.command must be a command id")),
|
||||
};
|
||||
let params = match o.get("params") {
|
||||
None => json!({}),
|
||||
Some(p @ Value::Object(_)) => p.clone(),
|
||||
Some(_) => return Err(format!("{at}.params must be an object")),
|
||||
};
|
||||
Ok((id, params))
|
||||
}
|
||||
|
||||
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
|
||||
let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64);
|
||||
Step { place, id, params, bytes, artboard }
|
||||
}
|
||||
|
||||
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
|
||||
/// as U+FFFD.
|
||||
fn shown(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
|
||||
if text.chars().nth(MAX).is_some() {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The members of `app` this module adds.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
|
||||
let l = link.clone();
|
||||
let play = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
do_script(&h, &a)
|
||||
});
|
||||
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
|
||||
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
|
||||
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
|
||||
members
|
||||
}
|
||||
|
||||
fn arg(a: &[Data], i: usize) -> &Data {
|
||||
a.get(i).unwrap_or(&Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
|
||||
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if a.len() > 4 {
|
||||
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
|
||||
}
|
||||
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
|
||||
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
|
||||
};
|
||||
if action.is_empty() || set.is_empty() {
|
||||
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
|
||||
}
|
||||
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
|
||||
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
|
||||
}
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
|
||||
// they were.
|
||||
for s in &p.steps {
|
||||
if let Some((place, id)) = refused_step(s) {
|
||||
let name = shown(&p.name);
|
||||
return Err(HostError::Error(if id == STOP_STEP {
|
||||
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
|
||||
} else {
|
||||
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
|
||||
}));
|
||||
}
|
||||
}
|
||||
for s in &p.steps {
|
||||
// A run asked to stop runs no further step; the realm ends it at its next instruction and
|
||||
// puts the documents back.
|
||||
if h.session.borrow().script_stop.is_set() {
|
||||
break;
|
||||
}
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
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 {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The place and command of the first command step `s` would run that a script may not run: the
|
||||
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
|
||||
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
|
||||
/// engine does not have are refused.
|
||||
fn refused_step(s: &Step) -> Option<(String, String)> {
|
||||
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
|
||||
if refused(&s.id) {
|
||||
return Some((s.place.clone(), s.id.clone()));
|
||||
}
|
||||
if s.id != "action.batch" {
|
||||
return None;
|
||||
}
|
||||
let commands = s.params.get("commands").and_then(Value::as_array)?;
|
||||
commands.iter().enumerate().find_map(|(k, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `params` of step `id`, with the active artboard of the active document added as a
|
||||
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
|
||||
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
|
||||
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
|
||||
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
|
||||
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
|
||||
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
|
||||
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
|
||||
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
|
||||
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
|
||||
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
|
||||
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
|
||||
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
|
||||
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
|
||||
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
|
||||
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
|
||||
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
|
||||
let mut params = params.clone();
|
||||
let Some(st) = s.active() else { return params };
|
||||
let n = st.doc.artboards.len();
|
||||
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
|
||||
(Some(_), _) if n == 0 => return params,
|
||||
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
|
||||
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
|
||||
(None, None) => super::dom::active_artboard(st),
|
||||
};
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let fit_art = id == "artboard.fitToArt";
|
||||
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"artboard"
|
||||
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"index"
|
||||
} else {
|
||||
return params;
|
||||
};
|
||||
let Some(p) = params.as_object_mut() else { return params };
|
||||
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
|
||||
return params;
|
||||
}
|
||||
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
|
||||
let kept: Vec<usize> = match start.picks {
|
||||
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
|
||||
list.iter().copied().filter(|i| *i < n).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if kept.len() >= 2 {
|
||||
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
|
||||
} else if picks.is_empty() {
|
||||
p.insert(key.into(), json!(active));
|
||||
} else if fit_art {
|
||||
p.insert("indices".into(), json!(picks));
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
|
||||
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
|
||||
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
|
||||
pub(crate) struct Start<'a> {
|
||||
pub active: &'a [(u64, usize)],
|
||||
pub picks: Option<&'a (u64, Vec<usize>)>,
|
||||
pub batch: Option<u64>,
|
||||
}
|
||||
+116
-32
@@ -44,6 +44,9 @@
|
||||
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
|
||||
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
//! - `app.activeDocument` with no document open throws `No active document`.
|
||||
//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run
|
||||
//! made; with no such step they change nothing, and with no document open they throw
|
||||
//! `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
@@ -92,6 +95,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod tags;
|
||||
mod text;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -167,6 +171,7 @@ pub(super) struct State {
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
text: text::TextState,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
@@ -194,19 +199,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
h.dom.saving.set(true);
|
||||
let r = f(h);
|
||||
h.dom.saving.set(false);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else {
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
return r;
|
||||
}
|
||||
h.put_growth_back(mark);
|
||||
if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
@@ -291,7 +301,7 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
@@ -299,15 +309,15 @@ fn typed(data_type: &str) -> MemberInfo {
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it,
|
||||
/// so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
|
||||
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -317,9 +327,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" => {
|
||||
"PageItem" | "TextFrame" => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"TextRange" => {
|
||||
text::check_range(&h, arg(&a, 0))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Err(HostError::Error(message.clone()))
|
||||
@@ -566,7 +579,7 @@ struct Frame {
|
||||
}
|
||||
|
||||
/// The index of the active artboard of `st`, as the view keeps it.
|
||||
fn active_artboard(st: &DocState) -> usize {
|
||||
pub(super) fn active_artboard(st: &DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
@@ -781,6 +794,11 @@ fn on_doc<T>(
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
|
||||
@@ -812,6 +830,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach
|
||||
/// only the steps the run made. With no step to undo or redo they change nothing.
|
||||
fn app_history(h: &Host, id: &str, redo: bool) -> Answer {
|
||||
let has_step = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
|
||||
if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() }
|
||||
};
|
||||
if has_step {
|
||||
command(h, id, &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn app_undo(h: &Host, _: &[Data]) -> Answer {
|
||||
app_history(h, "edit.undo", false)
|
||||
}
|
||||
|
||||
fn app_redo(h: &Host, _: &[Data]) -> Answer {
|
||||
app_history(h, "edit.redo", true)
|
||||
}
|
||||
|
||||
fn app_selection(h: &Host, _: &[Data]) -> Answer {
|
||||
let uid = h.session.borrow().active().map(|st| st.uid);
|
||||
match uid {
|
||||
@@ -946,11 +986,19 @@ fn front_docs(s: &Session) -> impl Iterator<Item = &DocState> {
|
||||
s.front_order().into_iter().map(|i| &s.documents()[i])
|
||||
}
|
||||
|
||||
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
|
||||
/// `documents[i]`, and `documents["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 document has it.
|
||||
fn docs_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let s = h.session.borrow();
|
||||
let at = match arg(a, 1) {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => front_docs(&s).nth(i),
|
||||
None => {
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
front_docs(&s).find(|d| d.title() == name)
|
||||
}
|
||||
},
|
||||
Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
|
||||
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
|
||||
found => found,
|
||||
@@ -970,10 +1018,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn docs_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => docs_by_name(h, a),
|
||||
Data::Number(_) => match docs_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let s = h.session.borrow();
|
||||
let st = position(*n).and_then(|i| front_docs(&s).nth(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
|
||||
Ok(doc_ref(h, st.uid))
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -1722,6 +1771,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
d => vec![d],
|
||||
};
|
||||
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
|
||||
// The ids listed so far; `ids` keeps them in the order they were first listed.
|
||||
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
|
||||
// The document is read once for every object: nothing changes it while the list is checked.
|
||||
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
|
||||
@@ -1815,27 +1865,49 @@ fn probing(a: &[Data]) -> bool {
|
||||
matches!(arg(a, 2), Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
|
||||
/// 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())
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
let doc = items_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match items_by_name(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::Number(n) => match position(*n) {
|
||||
Some(i) => Ok(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,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
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) };
|
||||
Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
/// The object at position `i` of `pageItems`, or `undefined` past the end.
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
|
||||
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(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)
|
||||
}
|
||||
|
||||
/// The first object of `pageItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
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()));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -1843,10 +1915,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(_) => match items_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match position(*n).map(|i| item_at(h, doc, i)) {
|
||||
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -2279,7 +2354,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
|
||||
/// The error of `move` and `duplicate` given an object of another document.
|
||||
pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available";
|
||||
@@ -2598,6 +2673,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link`
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
@@ -2627,10 +2703,14 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
("redo", method(l, app_redo), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
@@ -2698,12 +2778,15 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
@@ -2806,7 +2889,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,802 @@
|
||||
//! Character and paragraph styles in the script object model: `document.characterStyles` and
|
||||
//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
|
||||
//! of a `TextRange` uses, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A document's collection lists its Normal style first, then its other styles in the order the
|
||||
//! panel lists them.
|
||||
//! - A style object names its style for the rest of the run, also after the script renames it
|
||||
//! through `name`. Once the style is removed, or renamed or removed other than through the object
|
||||
//! model, or its document is closed or reverted with File › Revert, every member throws
|
||||
//! `Stale style`; a style added later under the same name is another style.
|
||||
//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
|
||||
//! characters.
|
||||
//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
|
||||
//! style does not set. Setting one redefines the style: text in the style takes the new value
|
||||
//! where it had the style's old one and keeps its other changes.
|
||||
//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
|
||||
//! or paragraphs of one, in the style's document. A character style styles exactly that text and
|
||||
//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
|
||||
//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
|
||||
//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
|
||||
//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
|
||||
//! no other style. They do not add or remove styles.
|
||||
//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
|
||||
//! look and is in the Normal style after.
|
||||
//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
|
||||
//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::{
|
||||
ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
|
||||
function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
|
||||
text_of, this_range, typename_of, usize_of, whole_span, with_doc,
|
||||
};
|
||||
use crate::DocState;
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
|
||||
use crate::script::dom::{Described, returns, typed};
|
||||
|
||||
/// The error of a style object whose style is gone.
|
||||
pub const STALE_STYLE: &str = "Stale style";
|
||||
/// The longest style name, in characters, after trimming.
|
||||
pub const MAX_STYLE_NAME: usize = 256;
|
||||
/// The most styles one run's style objects name.
|
||||
pub const MAX_HELD: usize = 4096;
|
||||
|
||||
/// A style that a run's style objects name: its document and the document's revert count then, its
|
||||
/// kind and its name now.
|
||||
struct Slot {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
para: bool,
|
||||
name: String,
|
||||
live: bool,
|
||||
}
|
||||
|
||||
/// A document's uid and its character and paragraph style lists when the slots were last checked.
|
||||
type Seen = (u64, Shared<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
|
||||
|
||||
/// The styles a run's style objects name; an object holds its slot's number.
|
||||
#[derive(Default)]
|
||||
pub(super) struct StyleState {
|
||||
slots: RefCell<Vec<Slot>>,
|
||||
seen: RefCell<Vec<Seen>>,
|
||||
}
|
||||
|
||||
/// Marks stale each style object whose style the command just run removed or renamed, so a style
|
||||
/// removed and made again under its name by later commands, or by later steps of the same batch,
|
||||
/// is another style. A document whose style lists did not change is not checked again. A live
|
||||
/// slot's style was in its document's list when the command started, so a step that removed or
|
||||
/// renamed it is in the trail's removed names.
|
||||
pub(in crate::script) fn after_command(h: &Host) {
|
||||
let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
if !slots.iter().any(|s| s.live) {
|
||||
return;
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if trail.reverted.contains(&slot.uid)
|
||||
|| (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone())))
|
||||
{
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut seen = h.dom.text.styles.seen.borrow_mut();
|
||||
seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
|
||||
for st in s.documents() {
|
||||
let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
|
||||
if same {
|
||||
continue;
|
||||
}
|
||||
seen.retain(|(uid, ..)| *uid != st.uid);
|
||||
seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
|
||||
for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
|
||||
slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name);
|
||||
}
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if !s.documents().iter().any(|d| d.uid == slot.uid) {
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style objects' state when a savepoint was taken: each slot's name and whether it was
|
||||
/// live, and the style lists last checked.
|
||||
pub(in crate::script) struct Mark {
|
||||
slots: Vec<(String, bool)>,
|
||||
seen: Vec<Seen>,
|
||||
}
|
||||
|
||||
/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored.
|
||||
pub(in crate::script) fn mark(h: &Host) -> Mark {
|
||||
let styles = &h.dom.text.styles;
|
||||
let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect();
|
||||
Mark { slots, seen: styles.seen.borrow().clone() }
|
||||
}
|
||||
|
||||
/// Puts the style objects back as they were at `mark`, after the documents were put back to the
|
||||
/// savepoint taken with it. A slot added since then stays live only while its document has the
|
||||
/// style and no older live slot names it.
|
||||
pub(in crate::script) fn put_back(h: &Host, mark: Mark) {
|
||||
let styles = &h.dom.text.styles;
|
||||
let mut slots = styles.slots.borrow_mut();
|
||||
let kept = mark.slots.len();
|
||||
for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) {
|
||||
slot.name = name;
|
||||
slot.live = live;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
for i in kept..slots.len() {
|
||||
let (older, newer) = slots.split_at_mut(i);
|
||||
let Some(slot) = newer.first_mut() else { break };
|
||||
let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name);
|
||||
slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name));
|
||||
}
|
||||
*styles.seen.borrow_mut() = mark.seen;
|
||||
}
|
||||
|
||||
fn normal(para: bool) -> &'static str {
|
||||
if para { NORMAL_PARA } else { NORMAL_CHAR }
|
||||
}
|
||||
|
||||
fn cmd(para: bool, verb: &str) -> String {
|
||||
format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
|
||||
}
|
||||
|
||||
fn style_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyle" } else { "CharacterStyle" }
|
||||
}
|
||||
|
||||
fn list_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyles" } else { "CharacterStyles" }
|
||||
}
|
||||
|
||||
fn defs(st: &DocState, para: bool) -> &Vec<TextStyleDef> {
|
||||
if para { &st.doc.para_styles } else { &st.doc.char_styles }
|
||||
}
|
||||
|
||||
/// The document's style names of a kind, the Normal style first.
|
||||
fn names(st: &DocState, para: bool) -> Vec<String> {
|
||||
let mut out = vec![normal(para).to_string()];
|
||||
out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
|
||||
out
|
||||
}
|
||||
|
||||
fn has_style(st: &DocState, para: bool, name: &str) -> bool {
|
||||
name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_STYLE.into())
|
||||
}
|
||||
|
||||
fn held_too_many() -> HostError {
|
||||
HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))
|
||||
}
|
||||
|
||||
/// The style object for the style `name` of the document `uid`: the same slot as every other
|
||||
/// object naming it in this run.
|
||||
fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
if slots.len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true });
|
||||
slots.len() - 1
|
||||
}
|
||||
};
|
||||
Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
|
||||
}
|
||||
|
||||
/// A style a style object names.
|
||||
struct Style {
|
||||
doc: Doc,
|
||||
para: bool,
|
||||
slot: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
|
||||
fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result<Style, HostError> {
|
||||
let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para)));
|
||||
let Some((handle, para)) = found else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0))));
|
||||
};
|
||||
let [run, uid, slot] = handle.as_slice() else { return Err(stale()) };
|
||||
let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?;
|
||||
let slot = usize_of(*slot).ok_or_else(stale)?;
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?;
|
||||
if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) {
|
||||
s.live = false;
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(Style { doc, para, slot, name: s.name.clone() })
|
||||
}
|
||||
|
||||
fn this_style(h: &Host, a: &[Data]) -> std::result::Result<Style, HostError> {
|
||||
style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)])
|
||||
}
|
||||
|
||||
/// Marks the slots of the styles `names` of the document `uid` as removed.
|
||||
fn forget(h: &Host, uid: u64, para: bool, names: &[String]) {
|
||||
for s in h.dom.text.styles.slots.borrow_mut().iter_mut() {
|
||||
if s.uid == uid && s.para == para && names.contains(&s.name) {
|
||||
s.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A style name a script gave, trimmed.
|
||||
fn style_name(v: &Data) -> std::result::Result<String, HostError> {
|
||||
let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) };
|
||||
if s.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return Err(HostError::Range("a style name must not be empty".into()));
|
||||
}
|
||||
if t.chars().count() > MAX_STYLE_NAME {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
if t.chars().any(char::is_control) {
|
||||
return Err(HostError::Range("a style name must not hold control characters".into()));
|
||||
}
|
||||
Ok(t.to_string())
|
||||
}
|
||||
|
||||
/// Runs the style command `verb` of the kind on the document of `doc`.
|
||||
fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params))
|
||||
}
|
||||
|
||||
// ---- CharacterStyle and ParagraphStyle ----
|
||||
|
||||
fn style_name_get(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_style(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = …`: renames the style; the Normal style keeps its name.
|
||||
fn style_name_set(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let to = style_name(arg(a, 1))?;
|
||||
if to == style.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be renamed", style.name)));
|
||||
}
|
||||
if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) {
|
||||
return Err(HostError::Error(format!("a style named {to} already exists")));
|
||||
}
|
||||
run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?;
|
||||
forget(h, style.doc.uid, style.para, std::slice::from_ref(&to));
|
||||
if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) {
|
||||
s.name = to;
|
||||
s.live = true;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn style_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, this_style(h, a)?.doc.uid))
|
||||
}
|
||||
|
||||
fn style_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(style_class(this_style(h, a)?.para)))
|
||||
}
|
||||
|
||||
fn attributes(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)]))
|
||||
}
|
||||
|
||||
fn style_character_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "CharacterStyleAttributes")
|
||||
}
|
||||
|
||||
fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "ParagraphStyleAttributes")
|
||||
}
|
||||
|
||||
/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after.
|
||||
fn style_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be removed", style.name)));
|
||||
}
|
||||
run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?;
|
||||
forget(h, style.doc.uid, style.para, &[style.name]);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The text a style is applied to: a text range, a text frame, or the characters, words or
|
||||
/// paragraphs of one.
|
||||
fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
|
||||
if handle_of(d, "TextFrame").is_some() {
|
||||
return Ok(whole_span(h, item_of(h, d)?)?.1);
|
||||
}
|
||||
const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"];
|
||||
if !TEXT.iter().any(|c| handle_of(d, c).is_some()) {
|
||||
return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into()));
|
||||
}
|
||||
span_of(h, d, &TEXT)
|
||||
}
|
||||
|
||||
/// `applyTo(textItem, clearingOverrides?)`.
|
||||
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let target = target_span(h, arg(a, 1))?;
|
||||
let clear = match arg(a, 2) {
|
||||
Data::Undefined => false,
|
||||
Data::Bool(b) => *b,
|
||||
_ => return Err(HostError::Type("clearingOverrides must be true or false".into())),
|
||||
};
|
||||
if target.item.doc.uid != style.doc.uid {
|
||||
return Err(HostError::Error("the text is in another document than the style".into()));
|
||||
}
|
||||
let (index, s, e, _) = resolve(h, target)?;
|
||||
h.charge_call(16 + (e - s) as u64)?;
|
||||
let (start, end) = if style.para {
|
||||
let (_, ba, bb) = para_range(&index, s, e);
|
||||
(ba, bb)
|
||||
} else {
|
||||
// An empty range inside text changes nothing; empty text takes the style on its runs.
|
||||
if s == e && index.len() > 0 {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
(index.byte(s, false), index.byte(e, true))
|
||||
};
|
||||
let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end});
|
||||
run(h, style.doc, style.para, "apply", &p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- the attributes of a style ----
|
||||
|
||||
/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets.
|
||||
const CHAR_KEYS: [(&str, &str); 11] = [
|
||||
("size", "size"),
|
||||
("leading", "leading"),
|
||||
("tracking", "tracking"),
|
||||
("baselineShift", "baseline_shift"),
|
||||
("hScale", "h_scale"),
|
||||
("vScale", "v_scale"),
|
||||
("rotation", "rotation"),
|
||||
("underline", "underline"),
|
||||
("strikethrough", "strikethrough"),
|
||||
("font", "font_family"),
|
||||
("style", "font_style"),
|
||||
];
|
||||
|
||||
/// The script's `Justification` members and the alignments a paragraph style stores.
|
||||
const JUSTIFY: [(&str, &str); 7] = [
|
||||
("LEFT", "Left"),
|
||||
("CENTER", "Center"),
|
||||
("RIGHT", "Right"),
|
||||
("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"),
|
||||
("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"),
|
||||
("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"),
|
||||
("FULLJUSTIFY", "JustifyAll"),
|
||||
];
|
||||
|
||||
/// The style an attributes object belongs to and the attributes it sets.
|
||||
fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map<String, Value>), HostError> {
|
||||
let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" };
|
||||
let style = style_of(h, arg(a, 0), &[(class, para)])?;
|
||||
let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?;
|
||||
Ok((style, attrs))
|
||||
}
|
||||
|
||||
fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
|
||||
let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num);
|
||||
let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool);
|
||||
match attr {
|
||||
Attr::Size => n("size"),
|
||||
Attr::Leading => n("leading"),
|
||||
Attr::AutoLeading => match m.get("leading") {
|
||||
Some(Value::Null) => Data::Bool(true),
|
||||
Some(v) if v.is_number() => Data::Bool(false),
|
||||
_ => Data::Undefined,
|
||||
},
|
||||
Attr::Tracking => n("tracking"),
|
||||
Attr::BaselineShift => n("baseline_shift"),
|
||||
Attr::HorizontalScale => n("h_scale"),
|
||||
Attr::VerticalScale => n("v_scale"),
|
||||
Attr::Rotation => n("rotation"),
|
||||
Attr::Underline => b("underline"),
|
||||
Attr::StrikeThrough => b("strikethrough"),
|
||||
Attr::TextFont => match m.get("font_family").and_then(Value::as_str) {
|
||||
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `characterAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, false)?;
|
||||
Ok(text("CharacterAttributes"))
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, true)?;
|
||||
Ok(text("ParagraphAttributes"))
|
||||
}
|
||||
|
||||
fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, false)?;
|
||||
Ok(char_value(h, attr, &m))
|
||||
}
|
||||
|
||||
/// Redefines the style with `attrs`, unless they are what it has.
|
||||
fn redefine(h: &Host, style: &Style, old: &Map<String, Value>, attrs: Map<String, Value>) -> Answer {
|
||||
if attrs == *old {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, false)?;
|
||||
// `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph
|
||||
// with the default justification.
|
||||
let base = CharStyle::default();
|
||||
let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size);
|
||||
let leading = old.get("leading").and_then(Value::as_f64);
|
||||
let sample = CharStyle { size, leading, ..base };
|
||||
let t = TextObject::point(Point::default(), "", sample.clone());
|
||||
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?;
|
||||
let mut attrs = old.clone();
|
||||
for (k, v) in param.as_object().into_iter().flatten() {
|
||||
let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue };
|
||||
let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() };
|
||||
attrs.insert((*key).to_string(), v);
|
||||
}
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
fn para_key(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "justify",
|
||||
ParaAttr::FirstLineIndent => "first_line_indent",
|
||||
ParaAttr::LeftIndent => "left_indent",
|
||||
ParaAttr::RightIndent => "right_indent",
|
||||
ParaAttr::SpaceBefore => "space_before",
|
||||
ParaAttr::SpaceAfter => "space_after",
|
||||
}
|
||||
}
|
||||
|
||||
fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, true)?;
|
||||
let v = m.get(para_key(attr));
|
||||
Ok(match attr {
|
||||
ParaAttr::Justification => match v.and_then(Value::as_str) {
|
||||
Some("Auto") => text("Justification.LEFT"),
|
||||
Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
_ => v.and_then(Value::as_f64).map_or(Data::Undefined, num),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, true)?;
|
||||
let (_, _, wants) = para_param(attr, name, arg(a, 1))?;
|
||||
let value = match (&wants, attr) {
|
||||
(Data::String(s), ParaAttr::Justification) => {
|
||||
let m = s.strip_prefix("Justification.").unwrap_or(s);
|
||||
let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j);
|
||||
json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?)
|
||||
}
|
||||
(Data::Number(n), _) => json!(n),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a finite number"))),
|
||||
};
|
||||
let mut attrs = old.clone();
|
||||
attrs.insert(para_key(attr).to_string(), value);
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
/// The body of a member that captures what it reads or sets.
|
||||
type Body = Rc<dyn Fn(&Host, &[Data]) -> Answer>;
|
||||
|
||||
/// Members whose getter and setter each charge the call, as [`function`] does.
|
||||
fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember {
|
||||
let wrap = |f: Body| -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::super::current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
|
||||
f(&h, &a)
|
||||
})
|
||||
};
|
||||
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
|
||||
}
|
||||
|
||||
fn char_members(link: &Link) -> Vec<Described> {
|
||||
ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
(name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn para_members(link: &Link) -> Vec<Described> {
|
||||
PARA_ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
(name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---- CharacterStyles and ParagraphStyles ----
|
||||
|
||||
/// What a collection of styles lists: a document's styles, or those a text range uses.
|
||||
enum Of {
|
||||
Doc(Doc),
|
||||
Range(Span),
|
||||
}
|
||||
|
||||
fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> {
|
||||
let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) {
|
||||
(Some(_), _) => false,
|
||||
(_, Some(_)) => true,
|
||||
_ => return Err(HostError::Type("this is not a CharacterStyles".into())),
|
||||
};
|
||||
let class = list_class(para);
|
||||
let len = handle_of(d, class).map_or(0, |v| v.len());
|
||||
Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para))
|
||||
}
|
||||
|
||||
/// The document and the names of the styles a collection lists.
|
||||
fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec<String>), HostError> {
|
||||
match of {
|
||||
Of::Doc(doc) => {
|
||||
let names = with_doc(h, *doc, |_, st| names(st, para));
|
||||
h.charge_call(names.len() as u64)?;
|
||||
Ok((*doc, names))
|
||||
}
|
||||
Of::Range(r) => {
|
||||
let (index, s, e, _) = resolve(h, *r)?;
|
||||
let used = with_doc(h, r.item.doc, |_, st| {
|
||||
let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let used: Vec<Option<String>> = if para {
|
||||
let (paras, _, _) = para_range(&index, s, e);
|
||||
paras.map(|i| t.para_at(i).style_name.clone()).collect()
|
||||
} else {
|
||||
styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect()
|
||||
};
|
||||
h.charge_call(used.len() as u64)?;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for n in used {
|
||||
let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string());
|
||||
if !out.contains(&n) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(normal(para).to_string());
|
||||
}
|
||||
Ok::<_, HostError>(out)
|
||||
})?;
|
||||
Ok((r.item.doc, used))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
Ok(num(float(listed(h, &of, para)?.1.len() as u64)))
|
||||
}
|
||||
|
||||
fn list_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, _) = list_of(h, arg(a, 0))?;
|
||||
match of {
|
||||
Of::Doc(doc) => Ok(doc_ref(h, doc.uid)),
|
||||
Of::Range(r) => {
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, "TextRange"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let found = match &of {
|
||||
Of::Doc(doc) => with_doc(h, *doc, |_, st| match i {
|
||||
0 => Some(normal(para).to_string()),
|
||||
_ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(),
|
||||
})
|
||||
.map(|n| (*doc, n)),
|
||||
Of::Range(_) => {
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
names.get(i).cloned().map(|n| (doc, n))
|
||||
}
|
||||
};
|
||||
match found {
|
||||
Some((doc, name)) => style_ref(h, doc.uid, para, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
if name.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
match names.iter().find(|n| *n == name) {
|
||||
Some(n) => style_ref(h, doc.uid, para, n),
|
||||
None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => list_by_name(h, a),
|
||||
Data::Number(_) => match list_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a document's collection; a range's collection cannot be changed.
|
||||
fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> {
|
||||
match list_of(h, arg(a, 0))? {
|
||||
(Of::Doc(doc), para) => Ok((doc, para)),
|
||||
(Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `add(name)`: a new style that sets no attributes.
|
||||
fn list_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let name = style_name(arg(a, 1))?;
|
||||
if with_doc(h, doc, |_, st| has_style(st, para, &name)) {
|
||||
return Err(HostError::Error(format!("a style named {name} already exists")));
|
||||
}
|
||||
// The new style needs a slot of its own: a run that names as many styles as it may adds none.
|
||||
if h.dom.text.styles.slots.borrow().len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?;
|
||||
// An object of a removed style of this name stays stale.
|
||||
forget(h, doc.uid, para, std::slice::from_ref(&name));
|
||||
style_ref(h, doc.uid, para, &name)
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every style but the Normal style, in one command.
|
||||
fn list_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let gone: Vec<String> = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect();
|
||||
if gone.is_empty() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, doc, para, "delete", &json!({"names": gone}))?;
|
||||
forget(h, doc.uid, para, &gone);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer {
|
||||
let r = this_range(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, list_class(para)))
|
||||
}
|
||||
|
||||
fn range_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, false)
|
||||
}
|
||||
|
||||
fn range_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, true)
|
||||
}
|
||||
|
||||
/// `document.characterStyles` and `document.paragraphStyles`.
|
||||
pub(in crate::script) fn doc_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.characterStyles` and `TextRange.paragraphStyles`.
|
||||
pub(super) fn range_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// The style classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let style = |para: bool| {
|
||||
let mut members = named(vec![
|
||||
("typename", get(l, style_typename), typed("string")),
|
||||
("name", property(l, style_name_get, style_name_set), typed("string")),
|
||||
("parent", get(l, style_parent), typed("Document")),
|
||||
("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])),
|
||||
("remove", method(l, style_remove), returns("undefined", &[])),
|
||||
]);
|
||||
if para {
|
||||
members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes")));
|
||||
members.push(super::super::later(l, "ParagraphStyle", "characterAttributes"));
|
||||
} else {
|
||||
members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes")));
|
||||
}
|
||||
class(style_class(para), None, members, None)
|
||||
};
|
||||
let list = |para: bool| {
|
||||
let name = list_class(para);
|
||||
let item = style_class(para);
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of(name), typed("string")),
|
||||
("length", get(l, list_length), typed("number")),
|
||||
("parent", get(l, list_parent), typed("*")),
|
||||
("index", method(l, list_index), returns(item, &[("itemKey", "*")])),
|
||||
("getByName", method(l, list_by_name), returns(item, &[("name", "string")])),
|
||||
("add", method(l, list_add), returns(item, &[("name", "string")])),
|
||||
("removeAll", method(l, list_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, list_at)),
|
||||
)
|
||||
};
|
||||
let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]);
|
||||
chars.extend(char_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
style(false),
|
||||
style(true),
|
||||
list(false),
|
||||
list(true),
|
||||
class("CharacterStyleAttributes", None, chars, None),
|
||||
class("ParagraphStyleAttributes", None, paras, None),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,829 @@
|
||||
//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and
|
||||
//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Story/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Stories/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story,
|
||||
//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null`
|
||||
//! breaks that link, and no text moves across it. Point type, a frame of another
|
||||
//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden
|
||||
//! or locked frame in either story are refused with nothing changed. Assigning the frame that is
|
||||
//! already linked, or `null` where there is no link, changes nothing.
|
||||
//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the
|
||||
//! frame is deleted, it throws `Stale story`.
|
||||
//! - `document.stories` lists one story for each type object in no thread and one for each thread,
|
||||
//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose
|
||||
//! first frame has that name.
|
||||
//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep
|
||||
//! their place through edits made through them, as a frame's ranges do, and are stale after any
|
||||
//! other change to the story's text and after File › Revert. A story of one frame gives that
|
||||
//! frame's own ranges.
|
||||
//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when
|
||||
//! `postFix` is false; `postFix` is true when it is left out.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::TextKind;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::super::{
|
||||
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get,
|
||||
handle_of, id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, returns, text, typed, whole, with_doc,
|
||||
};
|
||||
use super::{
|
||||
ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched,
|
||||
usize_of, whole_span,
|
||||
};
|
||||
use crate::cmd::threads::story_of;
|
||||
use crate::{DocState, Document, NodeId};
|
||||
|
||||
/// The error of a `Story` whose frame was deleted, or that came from an earlier run.
|
||||
pub const STALE_STORY: &str = "Stale story";
|
||||
|
||||
/// A document's uid, the document, and the first frame of each of its stories then.
|
||||
type StoryList = (u64, Weak<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The story state of one run: the text of each story of two or more frames that a range was made
|
||||
/// of, by document and the frame the `Story` was read from, and the last list of stories.
|
||||
#[derive(Default)]
|
||||
pub(in crate::script) struct StoryState {
|
||||
logs: RefCell<HashMap<(u64, u64), Log>>,
|
||||
list: RefCell<Option<StoryList>>,
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone.
|
||||
fn frames_of(st: &DocState, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(&st.doc, id);
|
||||
let mut seen = HashSet::new();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, charged to the run.
|
||||
fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
h.charge_call(st.doc.text_threads.len() as u64)?;
|
||||
let frames = frames_of(st, id);
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// Whether type object `id` is area type or type on a path.
|
||||
fn threadable(st: &DocState, id: NodeId) -> bool {
|
||||
text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point))
|
||||
}
|
||||
|
||||
// ---- nextFrame and previousFrame ----
|
||||
|
||||
fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f)))
|
||||
})
|
||||
}
|
||||
|
||||
fn next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`.
|
||||
fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let name = if next { "nextFrame" } else { "previousFrame" };
|
||||
let item = this_frame(h, a)?;
|
||||
let other = match arg(a, 1) {
|
||||
Data::Null => None,
|
||||
d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))),
|
||||
};
|
||||
if other.is_some_and(|o| o.doc.uid != item.doc.uid) {
|
||||
return Err(HostError::Error(format!("{name}: the two frames are in different documents")));
|
||||
}
|
||||
let now = with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) {
|
||||
return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded")));
|
||||
}
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(current.copied())
|
||||
})?;
|
||||
if now == other.map(|o| o.id) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let side = if next { "next" } else { "previous" };
|
||||
let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)});
|
||||
edit_item(h, item, "text.thread.setNeighbor", ¶ms).map_err(|e| match e {
|
||||
HostError::Error(m) => HostError::Error(format!("{name}: {m}")),
|
||||
e => e,
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
set_neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn set_previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
set_neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// `TextFrame.story`.
|
||||
fn frame_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
Ok(story_ref(h, item))
|
||||
}
|
||||
|
||||
/// `TextRange.story`: the story of the range's frame.
|
||||
fn range_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = super::this_range(h, a)?;
|
||||
super::resolve(h, r)?;
|
||||
Ok(story_ref(h, r.item))
|
||||
}
|
||||
|
||||
// ---- creating a frame threaded to another ----
|
||||
|
||||
/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame
|
||||
/// is made: the frame to thread the new one to, and whether the new one goes after it.
|
||||
pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result<Option<(Item, bool)>, HostError> {
|
||||
if matches!(base, Data::Undefined | Data::Null) {
|
||||
return Ok(None);
|
||||
}
|
||||
if handle_of(base, "TextFrame").is_none() {
|
||||
return Err(HostError::Type("baseFrame must be a TextFrame".into()));
|
||||
}
|
||||
let item = item_of(h, base)?;
|
||||
if item.doc.uid != doc.uid {
|
||||
return Err(HostError::Error("baseFrame: the frame is in another document".into()));
|
||||
}
|
||||
let postfix = match post {
|
||||
Data::Undefined => true,
|
||||
d => boolean(d, "postFix")?,
|
||||
};
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) {
|
||||
return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into()));
|
||||
}
|
||||
let editable = st.doc.editable();
|
||||
if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) {
|
||||
return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Some((item, postfix)))
|
||||
}
|
||||
|
||||
/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type:
|
||||
/// `text.thread.add` does not thread type there.
|
||||
pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> {
|
||||
if in_compound(h, path) {
|
||||
return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Threads the new frame `id` after `base`, or before it when `postfix` is false.
|
||||
pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> {
|
||||
edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Story ----
|
||||
|
||||
fn story_ref(h: &Host, item: Item) -> Data {
|
||||
let [high, low] = id_parts(item.id);
|
||||
host_ref("Story", &[float(h.run), float(item.doc.uid), high, low])
|
||||
}
|
||||
|
||||
/// The frame the story `d` was read from, which must still be a type object.
|
||||
fn story_of_data(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
match with_doc(h, doc, |_, st| text_of(st, id).is_some()) {
|
||||
true => Ok(Item { doc, id }),
|
||||
false => Err(HostError::Error(STALE_STORY.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn this_story(h: &Host, a: &[Data]) -> std::result::Result<Item, HostError> {
|
||||
story_of_data(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn story_frames(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect())))
|
||||
}
|
||||
|
||||
fn story_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
Ok(doc_ref(h, story.doc.uid))
|
||||
}
|
||||
|
||||
/// The story's one frame, or `None` for a story of two or more frames.
|
||||
fn single(h: &Host, story: Item) -> std::result::Result<Option<Item>, HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
Ok(match frames[..] {
|
||||
[one] => Some(Item { doc: story.doc, id: one }),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn story_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(num(float(index.len() as u64)))
|
||||
}
|
||||
|
||||
/// A range or a collection of the whole story, as `frame_class` for a story of one frame and
|
||||
/// `story_class` for a longer one.
|
||||
fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
if let Some(frame) = single(h, story)? {
|
||||
let (_, r) = whole_span(h, frame)?;
|
||||
return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class));
|
||||
}
|
||||
let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(span_ref(h, story, 0, index.len(), stamp, story_class))
|
||||
}
|
||||
|
||||
fn story_text_range(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "TextRange", "StoryRange")
|
||||
}
|
||||
|
||||
fn story_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Characters", "StoryCharacters")
|
||||
}
|
||||
|
||||
fn story_words(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Words", "StoryWords")
|
||||
}
|
||||
|
||||
fn story_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Paragraphs", "StoryParagraphs")
|
||||
}
|
||||
|
||||
// ---- the text of a story of two or more frames ----
|
||||
|
||||
/// The frames of the story and the text of each, in thread order.
|
||||
fn story_text(st: &DocState, frames: &[NodeId]) -> String {
|
||||
frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect()
|
||||
}
|
||||
|
||||
/// The story's index and its generation now, read again when its document changed. The stories
|
||||
/// read from the frames of one story share one index of its text while the document is unchanged.
|
||||
fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc<Index>, u64), HostError> {
|
||||
if text_of(st, anchor).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let key = (st.uid, anchor.0);
|
||||
let now = Arc::as_ptr(&st.doc);
|
||||
let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts;
|
||||
if !logs.get(&key).is_some_and(current) {
|
||||
let frames = charged_frames(h, st, anchor)?;
|
||||
// Another frame of the same story read at this state of the document has the same text;
|
||||
// a frame listed in two threads can belong to another story, so its frames must match.
|
||||
let mut shared = None;
|
||||
if frames.len() > 1 {
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
if let Some((f, l)) =
|
||||
frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l)))
|
||||
&& charged_frames(h, st, f)? == frames
|
||||
{
|
||||
shared = Some(l.index.clone());
|
||||
}
|
||||
}
|
||||
let index = match shared {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let text = story_text(st, &frames);
|
||||
// Joining the frames' text costs its length, as rebuilding the index does elsewhere.
|
||||
h.charge_call(text.len() as u64)?;
|
||||
match logs.get(&key) {
|
||||
Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(),
|
||||
_ => Rc::new(Index::new(text)),
|
||||
}
|
||||
}
|
||||
};
|
||||
match logs.get_mut(&key) {
|
||||
Some(l) => {
|
||||
if l.reverts != st.reverts || index.text != l.index.text {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index;
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
None => {
|
||||
logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
Ok((l.index.clone(), l.stamp))
|
||||
}
|
||||
|
||||
/// A range of a story: the frame the story was read from, its span in UTF-16 units and the
|
||||
/// generation it was made at.
|
||||
#[derive(Clone, Copy)]
|
||||
struct StorySpan {
|
||||
story: Item,
|
||||
start: usize,
|
||||
end: usize,
|
||||
stamp: u64,
|
||||
}
|
||||
|
||||
const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)];
|
||||
|
||||
fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data {
|
||||
let [high, low] = id_parts(story.id);
|
||||
host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)])
|
||||
}
|
||||
|
||||
/// The story span `d` names, when it is an object of one of `classes`.
|
||||
fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<StorySpan, HostError> {
|
||||
let handle = classes.iter().find_map(|c| handle_of(d, c));
|
||||
let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange"))));
|
||||
};
|
||||
let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?;
|
||||
let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
Ok(StorySpan { story, start, end, stamp })
|
||||
}
|
||||
|
||||
fn this_span(h: &Host, a: &[Data]) -> std::result::Result<StorySpan, HostError> {
|
||||
span_of(h, arg(a, 0), &["StoryRange"])
|
||||
}
|
||||
|
||||
/// The span and index of `r` now.
|
||||
fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc<Index>, usize, usize, u64), HostError> {
|
||||
with_doc(h, r.story.doc, |_, st| {
|
||||
let (index, stamp) = observe(h, st, r.story.id)?;
|
||||
let logs = h.dom.text.stories.logs.borrow();
|
||||
let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?;
|
||||
if r.stamp < l.floor || r.stamp > l.stamp {
|
||||
return Err(HostError::Error(STALE_RANGE.into()));
|
||||
}
|
||||
let (mut s, mut e) = (r.start, r.end);
|
||||
let from = l.edits.partition_point(|x| x.stamp <= r.stamp);
|
||||
for x in l.edits.range(from..) {
|
||||
let moved = |v: usize| v - x.removed + x.inserted;
|
||||
s = if s <= x.at {
|
||||
s
|
||||
} else if s >= x.at + x.removed {
|
||||
moved(s)
|
||||
} else {
|
||||
x.at
|
||||
};
|
||||
// An end inside the removed text goes to the end of the new text.
|
||||
e = if e < x.at || (e == x.at && x.removed > 0) {
|
||||
e
|
||||
} else if e >= x.at + x.removed {
|
||||
moved(e)
|
||||
} else {
|
||||
x.at + x.inserted
|
||||
};
|
||||
}
|
||||
let e = e.min(index.len());
|
||||
Ok((index, s.min(e), e, stamp))
|
||||
})
|
||||
}
|
||||
|
||||
/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`.
|
||||
/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the
|
||||
/// same story read from its other frames record the edit too, when they knew the text before it.
|
||||
fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
let now = story_text(st, &frames);
|
||||
let (a, b) = (before.byte(at, false), before.byte(at + removed, true));
|
||||
let expected = before.text.len() - (b - a) + inserted.len() == now.len()
|
||||
&& now.as_bytes().starts_with(&before.text.as_bytes()[..a])
|
||||
&& now.as_bytes().ends_with(&before.text.as_bytes()[b..])
|
||||
&& now.get(a..a + inserted.len()) == Some(inserted);
|
||||
let members: HashSet<u64> = frames.iter().map(|f| f.0).collect();
|
||||
let index = Rc::new(Index::new(now));
|
||||
let inserted = inserted.encode_utf16().count();
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let mut found = false;
|
||||
for (&(uid, anchor), l) in logs.iter_mut() {
|
||||
if uid != st.uid || !members.contains(&anchor) {
|
||||
continue;
|
||||
}
|
||||
let own = anchor == story.id.0;
|
||||
let current = l.reverts == st.reverts;
|
||||
if !own {
|
||||
h.charge_call(l.index.text.len() as u64)?;
|
||||
if !expected || !current || l.index.text != before.text {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
found |= own;
|
||||
if expected && current {
|
||||
l.push(at, removed, inserted);
|
||||
} else {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index.clone();
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with
|
||||
/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in
|
||||
/// place while the frames after it flow again.
|
||||
fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> {
|
||||
loop {
|
||||
let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut at = 0;
|
||||
let spans = charged_frames(h, st, story.id)?
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum());
|
||||
at += n;
|
||||
(f, at - n, at)
|
||||
})
|
||||
.collect();
|
||||
Ok(spans)
|
||||
})?;
|
||||
let target =
|
||||
if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) };
|
||||
let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
let item = Item { doc: story.doc, id: f };
|
||||
if x <= a {
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?;
|
||||
return Ok(());
|
||||
}
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?;
|
||||
b = x;
|
||||
}
|
||||
}
|
||||
|
||||
fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer {
|
||||
let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) };
|
||||
let insert = from_script(v);
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
let (a, b) = (index.byte(s, false), index.byte(e, true));
|
||||
if index.text[a..b] == insert {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
|
||||
replace(h, r.story, a, b, &insert)?;
|
||||
record(h, r.story, &index, s, e - s, &insert)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn span_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let (x, y) = (index.byte(s, false), index.byte(e, true));
|
||||
Ok(text(to_script(&index.text[x..y])))
|
||||
}
|
||||
|
||||
fn span_set_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, arg(a, 1))
|
||||
}
|
||||
|
||||
fn span_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, &text(""))
|
||||
}
|
||||
|
||||
fn span_start(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, _, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(s as u64)))
|
||||
}
|
||||
|
||||
fn span_end(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(e as u64)))
|
||||
}
|
||||
|
||||
fn span_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float((e - s) as u64)))
|
||||
}
|
||||
|
||||
fn span_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(story_ref(h, r.story))
|
||||
}
|
||||
|
||||
fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x);
|
||||
Ok(num(float(p as u64)))
|
||||
}
|
||||
|
||||
fn span_part(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, class))
|
||||
}
|
||||
|
||||
fn span_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryCharacters")
|
||||
}
|
||||
|
||||
fn span_words(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryWords")
|
||||
}
|
||||
|
||||
fn span_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryParagraphs")
|
||||
}
|
||||
|
||||
fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> {
|
||||
let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p);
|
||||
let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?;
|
||||
Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part))
|
||||
}
|
||||
|
||||
fn part_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(text(match part {
|
||||
Part::Characters => "Characters",
|
||||
Part::Words => "Words",
|
||||
Part::Paragraphs => "Paragraphs",
|
||||
}))
|
||||
}
|
||||
|
||||
fn span_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
resolve(h, this_span(h, a)?)?;
|
||||
Ok(text("TextRange"))
|
||||
}
|
||||
|
||||
fn story_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_story(h, a)?;
|
||||
Ok(text("Story"))
|
||||
}
|
||||
|
||||
fn part_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
Ok(num(float(part_spans(&index, part, s, e).0.len() as u64)))
|
||||
}
|
||||
|
||||
fn part_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, _) = this_part(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, "StoryRange"))
|
||||
}
|
||||
|
||||
fn part_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let (index, s, e, stamp) = resolve(h, r)?;
|
||||
let (items, spans) = part_spans(&index, part, s, e);
|
||||
let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) };
|
||||
let span = match spans {
|
||||
None => index.char_span(k),
|
||||
Some(list) => list.get(k).copied(),
|
||||
};
|
||||
Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange")))
|
||||
}
|
||||
|
||||
// ---- Stories ----
|
||||
|
||||
fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("Stories", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `document.stories`.
|
||||
pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember {
|
||||
get(link, doc_stories_impl)
|
||||
}
|
||||
|
||||
/// The first frame of each story of the document in paint order, kept while the document is
|
||||
/// unchanged.
|
||||
fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
let mut seen = HashSet::new();
|
||||
for thread in &st.doc.text_threads {
|
||||
let live: Vec<NodeId> = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect();
|
||||
if live.len() >= 2 {
|
||||
first.insert(live[0]);
|
||||
threaded.extend(live);
|
||||
}
|
||||
}
|
||||
let heads: Vec<NodeId> = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect();
|
||||
let heads = Rc::new(heads);
|
||||
*h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone()));
|
||||
Ok(heads)
|
||||
}
|
||||
|
||||
fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Stories")
|
||||
}
|
||||
|
||||
fn stories_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn stories_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
stories_doc(h, a)?;
|
||||
Ok(text("Stories"))
|
||||
}
|
||||
|
||||
fn stories_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn stories_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?;
|
||||
Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id })))
|
||||
}
|
||||
|
||||
/// `stories.index(key)`: by number, or by the name of a story's first frame.
|
||||
fn stories_index(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::Number(_) => match stories_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::String(name) => {
|
||||
let id = with_doc(h, doc, |_, st| {
|
||||
let list = heads(h, st)?;
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())))
|
||||
})?;
|
||||
id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- classes ----
|
||||
|
||||
/// A member of the range of a story of two or more frames that is not available yet: reading or
|
||||
/// assigning it throws, after the check that the range is still there, and `reflect` leaves it out.
|
||||
fn range_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("TextRange.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
resolve(&h, this_span(&h, &a)?)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// A member of `Story` that is not available yet: reading or assigning it throws, after the check
|
||||
/// that the story is still there, and `reflect` leaves it out.
|
||||
fn story_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("Story.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
this_story(&h, &a)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// The members of `TextFrame` this module adds.
|
||||
pub(super) fn frame_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("nextFrame", property(l, next_frame, set_next_frame), typed("TextFrame")),
|
||||
("previousFrame", property(l, previous_frame, set_previous_frame), typed("TextFrame")),
|
||||
("story", get(l, frame_story), typed("Story")),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.story`.
|
||||
pub(super) fn range_member(l: &Link) -> Described {
|
||||
("story".into(), get(l, range_story), typed("Story"))
|
||||
}
|
||||
|
||||
/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut story = named(vec![
|
||||
("typename", get(l, story_typename), typed("string")),
|
||||
("parent", get(l, story_parent), typed("Document")),
|
||||
("length", get(l, story_length), typed("number")),
|
||||
("textFrames", get(l, story_frames), typed("Array")),
|
||||
("textRange", get(l, story_text_range), typed("*")),
|
||||
("characters", get(l, story_characters), collection("*")),
|
||||
("words", get(l, story_words), collection("*")),
|
||||
("paragraphs", get(l, story_paragraphs), collection("*")),
|
||||
]);
|
||||
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m)));
|
||||
let mut range = named(vec![
|
||||
("typename", get(l, span_typename), typed("string")),
|
||||
("parent", get(l, span_story), typed("Story")),
|
||||
("story", get(l, span_story), typed("Story")),
|
||||
("contents", property(l, span_contents, span_set_contents), typed("string")),
|
||||
("start", read_only(l, span_start, "TextRange", "start"), typed("number")),
|
||||
("end", read_only(l, span_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, span_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", read_only(l, span_length, "TextRange", "length"), typed("number")),
|
||||
("characters", get(l, span_characters), collection("StoryCharacters")),
|
||||
("words", get(l, span_words), collection("StoryWords")),
|
||||
("paragraphs", get(l, span_paragraphs), collection("StoryParagraphs")),
|
||||
("getParagraphLength", method(l, span_paragraph_length), returns("number", &[])),
|
||||
("remove", method(l, span_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"characterAttributes",
|
||||
"paragraphAttributes",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
"deSelect",
|
||||
"duplicate",
|
||||
"move",
|
||||
"getTextRunLength",
|
||||
"getLocalCharOverridesJSON",
|
||||
"getLocalParaOverridesJSON",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ATTRS.iter().map(|(n, _)| *n))
|
||||
.map(|m| range_later(l, m)),
|
||||
);
|
||||
let part = |name: &'static str| {
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("StoryRange")),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
class("Story", None, story, None),
|
||||
class("StoryRange", None, range, None),
|
||||
part("StoryCharacters"),
|
||||
part("StoryWords"),
|
||||
part("StoryParagraphs"),
|
||||
class(
|
||||
"Stories",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, stories_typename), typed("string")),
|
||||
("length", get(l, stories_length), typed("number")),
|
||||
("parent", get(l, stories_parent), typed("Document")),
|
||||
("index", method(l, stories_index), returns("number", &[("itemKey", "*")])),
|
||||
]),
|
||||
Some(function(l, stories_at)),
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
|
||||
//!
|
||||
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
|
||||
@@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
|
||||
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
|
||||
}
|
||||
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most
|
||||
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
|
||||
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
|
||||
pub fn holds(root: &Path, path: &Path) -> bool {
|
||||
|
||||
@@ -37,11 +37,21 @@
|
||||
//!
|
||||
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
|
||||
//! the file it is in.
|
||||
//!
|
||||
//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules
|
||||
//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing
|
||||
//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL
|
||||
//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would
|
||||
//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`],
|
||||
//! so a link that leads out of the script's folder is refused as well. Module files count against
|
||||
//! the same limits as included files, and the paths of one file (two spellings, a link, or names
|
||||
//! that differ only in letter case on Windows) give one module.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_js::{DirectiveName, Options};
|
||||
use vectorcraft_js::{DirectiveName, LoadError, Options};
|
||||
|
||||
use crate::file_access::{ScriptRead, ScriptScope};
|
||||
|
||||
@@ -219,13 +229,65 @@ pub(crate) struct Files {
|
||||
frames: Vec<Frame>,
|
||||
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
|
||||
es2015: bool,
|
||||
/// The modules a module run has read, by key ([`module_key`]): the names of the folders each
|
||||
/// is in, below the script's folder.
|
||||
module_dirs: HashMap<String, Vec<String>>,
|
||||
/// The key of each module path read, below the script's folder.
|
||||
module_paths: HashMap<String, String>,
|
||||
/// The key [`Files::module_entry`] gave the script, in a module run.
|
||||
entry_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
|
||||
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
|
||||
/// ECMAScript 5.1 with the ExtendScript extensions.
|
||||
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
|
||||
/// run as ECMAScript 5.1 with the ExtendScript extensions.
|
||||
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
|
||||
/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case).
|
||||
pub(crate) fn module_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
|
||||
/// What names the file at the real path `real` among a run's modules: on Unix its device and file
|
||||
/// number, so two paths to one file give one module; elsewhere its real path, which on Windows
|
||||
/// spells each name in the letter case the folder stores it in, so two spellings of one file in a
|
||||
/// folder that ignores case give one module and two files in a folder that does not stay two.
|
||||
fn module_key(real: &Path) -> String {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if let Ok(m) = std::fs::metadata(real) {
|
||||
return format!("{}:{}", m.dev(), m.ino());
|
||||
}
|
||||
}
|
||||
display(real).to_string()
|
||||
}
|
||||
|
||||
/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is
|
||||
/// not `root` or below it, or has a name that is not Unicode.
|
||||
fn names_below(root: &Path, dir: &Path) -> Option<Vec<String>> {
|
||||
dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between
|
||||
/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error.
|
||||
fn specifier_names(specifier: &str) -> Result<Vec<&str>, LoadError> {
|
||||
let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}")));
|
||||
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
|
||||
return wrong("must start with './' or '../'");
|
||||
}
|
||||
if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) {
|
||||
return wrong("must not contain \\, : or control characters");
|
||||
}
|
||||
let names: Vec<&str> = specifier.split('/').collect();
|
||||
let file = names.last().copied().unwrap_or_default();
|
||||
let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default();
|
||||
if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) {
|
||||
return wrong("must name a .mjs or .js file");
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
|
||||
@@ -321,9 +383,91 @@ impl Files {
|
||||
levels: 0,
|
||||
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
|
||||
es2015: es2015_script(path),
|
||||
module_dirs: HashMap::new(),
|
||||
module_paths: HashMap::new(),
|
||||
entry_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the run's files read ECMAScript 2015, as a module run given as text does.
|
||||
pub(crate) fn read_es2015(&mut self) {
|
||||
self.es2015 = true;
|
||||
}
|
||||
|
||||
/// The module `text`, the script's own, as a source of one file. → its key and the source.
|
||||
pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> {
|
||||
self.bytes = self.bytes.saturating_add(text.len());
|
||||
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
|
||||
let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default();
|
||||
self.module_dirs.insert(key.clone(), Vec::new());
|
||||
self.entry_key = Some(key.clone());
|
||||
let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
|
||||
Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None }))
|
||||
}
|
||||
|
||||
/// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or
|
||||
/// this function gave). → the module's key, with its text and source map the first time the
|
||||
/// run reads it.
|
||||
pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> {
|
||||
let names = specifier_names(specifier)?;
|
||||
let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?;
|
||||
for name in names {
|
||||
match name {
|
||||
"" | "." => {}
|
||||
".." => {
|
||||
if path.pop().is_none() {
|
||||
return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'")));
|
||||
}
|
||||
}
|
||||
name => path.push(name.to_string()),
|
||||
}
|
||||
}
|
||||
let relative = path.join("/");
|
||||
if let Some(key) = self.module_paths.get(&relative) {
|
||||
return Ok((key.clone(), None));
|
||||
}
|
||||
let root =
|
||||
self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?;
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached")));
|
||||
}
|
||||
let candidate = path.iter().fold(root.clone(), |p, name| p.join(name));
|
||||
// Another path to a module already read gives that module: the file is not read again, and
|
||||
// its text is not counted again.
|
||||
let loaded = &self.module_dirs;
|
||||
let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real)));
|
||||
let (real, bytes) = match read {
|
||||
Ok(found) => found,
|
||||
Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))),
|
||||
Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))),
|
||||
Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))),
|
||||
Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))),
|
||||
};
|
||||
let key = module_key(&real);
|
||||
let Some(bytes) = bytes else {
|
||||
self.module_paths.insert(relative, key.clone());
|
||||
return Ok((key, None));
|
||||
};
|
||||
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
|
||||
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
|
||||
}
|
||||
if self.files >= MAX_FILES {
|
||||
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
|
||||
}
|
||||
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
|
||||
self.bytes += bytes.len();
|
||||
self.files += 1;
|
||||
self.module_paths.insert(relative, key.clone());
|
||||
// The module's relative imports start from the folder the file is in, whichever path to it
|
||||
// was read first; the path as written stands in when that folder is not below the script's.
|
||||
path.pop();
|
||||
let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path);
|
||||
self.module_dirs.insert(key.clone(), dir);
|
||||
let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
|
||||
Ok((key, Some((text, map))))
|
||||
}
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
@@ -362,12 +506,26 @@ impl Files {
|
||||
self.expand(shown, dir, text, true)
|
||||
}
|
||||
|
||||
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
|
||||
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
|
||||
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
|
||||
/// The folder of the module `key` ([`Files::module`] gave it), from the script's folder.
|
||||
pub(crate) fn module_dir(&self, key: &str) -> Option<PathBuf> {
|
||||
let names = self.module_dirs.get(key)?;
|
||||
let root = self.frames.first().and_then(|f| f.dir.clone())?;
|
||||
Some(names.iter().fold(root, |p, name| p.join(name)))
|
||||
}
|
||||
|
||||
/// The script's folder when the run is a module run ([`Files::module_entry`] read the script),
|
||||
/// or `None` for a script run.
|
||||
pub(crate) fn entry_module_dir(&self) -> Option<PathBuf> {
|
||||
self.module_dir(self.entry_key.as_deref()?)
|
||||
}
|
||||
|
||||
/// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder
|
||||
/// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It
|
||||
/// becomes the file being run until [`Files::end_eval`].
|
||||
pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option<PathBuf>) -> Result<Expanded, Failure> {
|
||||
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
|
||||
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
|
||||
let dir = self.frames.last().and_then(|f| f.dir.clone());
|
||||
let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone()));
|
||||
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
|
||||
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
|
||||
let shown = display(&real);
|
||||
|
||||
+162
-10
@@ -48,6 +48,7 @@
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
|
||||
pub mod actions;
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
@@ -65,7 +66,8 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{
|
||||
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
|
||||
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
|
||||
Realm, RunError, RunErrorKind,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
@@ -206,6 +208,10 @@ pub(crate) struct Request {
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
|
||||
pub module: bool,
|
||||
/// The actions `app.doScript` can play.
|
||||
pub actions: Vec<actions::Playable>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -781,6 +787,9 @@ struct Host {
|
||||
script_map: RefCell<include::SourceMap>,
|
||||
/// The same for each source `$.evalFile` gave, in order.
|
||||
eval_maps: RefCell<Vec<include::SourceMap>>,
|
||||
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
|
||||
/// module's, by its index there.
|
||||
module_maps: RefCell<HashMap<usize, String>>,
|
||||
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
|
||||
/// order: the error's mark ([`HostError::Marked`]) is its index.
|
||||
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
|
||||
@@ -806,6 +815,15 @@ struct Host {
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// The actions `app.doScript` can play.
|
||||
actions: Vec<actions::Playable>,
|
||||
/// The index of each open document's active artboard as the run starts, by document uid. The
|
||||
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
|
||||
active_artboards: Vec<(u64, usize)>,
|
||||
/// The artboards the Artboard tool had selected in the active document as the run starts (two or
|
||||
/// more), with that document's uid. The run gives the tool fresh state, which drops them, so the
|
||||
/// steps `app.doScript` plays read them here.
|
||||
artboard_picks: Option<(u64, Vec<usize>)>,
|
||||
/// The documents open when the run began as the person last left them, each with its own file
|
||||
/// and the file it was read from ([`crate::DocState::as_person_left`],
|
||||
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
|
||||
@@ -967,6 +985,22 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
|
||||
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
|
||||
/// run).
|
||||
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
|
||||
let script = self.script_tag.get();
|
||||
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
|
||||
return None;
|
||||
}
|
||||
let n = tag.checked_sub(script)?;
|
||||
if n == 0 {
|
||||
return self.files.borrow().entry_module_dir();
|
||||
}
|
||||
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
|
||||
self.files.borrow().module_dir(&key)
|
||||
}
|
||||
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
@@ -1283,6 +1317,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);
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
|
||||
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
|
||||
@@ -1330,6 +1365,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();
|
||||
if let Some(save) = save
|
||||
&& !save.restore(s)
|
||||
{
|
||||
@@ -1408,9 +1444,76 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
}
|
||||
}
|
||||
dom::after_command(host, before);
|
||||
// Style objects follow only a command that is kept.
|
||||
if crossed.is_ok() {
|
||||
dom::after_kept_command(host);
|
||||
} else {
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
}
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
/// A document's uid, revert count, and character and paragraph style lists.
|
||||
pub(crate) type StyleLists =
|
||||
(u64, u64, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>);
|
||||
|
||||
/// 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)]
|
||||
pub(crate) struct StyleTrail {
|
||||
lists: Vec<StyleLists>,
|
||||
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
|
||||
pub(crate) reverted: Vec<u64>,
|
||||
}
|
||||
|
||||
impl StyleTrail {
|
||||
/// A trail that starts from the documents' style lists now.
|
||||
fn start(s: &Session) -> 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() }
|
||||
}
|
||||
}
|
||||
|
||||
/// After a step of a batch a script runs: notes the styles the step removed or renamed and the
|
||||
/// documents it reverted, so the style objects see a style the batch removed and made again under
|
||||
/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open
|
||||
/// document's lists, however many steps change them.
|
||||
pub(crate) fn note_style_lists(s: &mut Session) {
|
||||
let trail = &mut s.script_style_trail;
|
||||
trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid));
|
||||
for st in &s.docs {
|
||||
let (c, p) = (&st.doc.char_styles, &st.doc.para_styles);
|
||||
let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else {
|
||||
trail.lists.push((st.uid, st.reverts, c.clone(), p.clone()));
|
||||
continue;
|
||||
};
|
||||
if last.1 != st.reverts {
|
||||
if !trail.reverted.contains(&st.uid) {
|
||||
trail.reverted.push(st.uid);
|
||||
}
|
||||
} else {
|
||||
for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] {
|
||||
if vectorcraft_doc::Shared::ptr_eq(old, new) {
|
||||
continue;
|
||||
}
|
||||
let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect();
|
||||
for d in old.iter().filter(|d| !names.contains(d.name.as_str())) {
|
||||
trail.gone.insert((st.uid, para, d.name.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
*last = (st.uid, st.reverts, c.clone(), p.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn retained_style_lists(s: &Session) -> usize {
|
||||
s.script_style_trail.lists.len()
|
||||
}
|
||||
|
||||
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
|
||||
/// of a crossing throws a `RangeError`.
|
||||
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
|
||||
@@ -1515,6 +1618,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
}
|
||||
}),
|
||||
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
|
||||
site: true,
|
||||
}
|
||||
};
|
||||
let mut items = vec![
|
||||
@@ -1529,9 +1633,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
}
|
||||
|
||||
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
|
||||
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
|
||||
/// milliseconds, is taken and not waited on: the file is read at once.
|
||||
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
|
||||
/// run (for a call in a module the script imported, that module's file), with its preprocessor
|
||||
/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not
|
||||
/// waited on: the file is read at once. `args` starts with the call's place, as
|
||||
/// [`HostItem::Evaluator`] gives it with `site`.
|
||||
fn eval_file(host: &Host, mut args: Vec<Data>) -> std::result::Result<Data, HostError> {
|
||||
let tag = match args.first() {
|
||||
Some(Data::Number(n)) if args.len() >= 3 => *n as u32,
|
||||
_ => vectorcraft_js::UNKNOWN_SOURCE,
|
||||
};
|
||||
args.drain(..3.min(args.len()));
|
||||
let module_dir = host.module_dir_at(tag);
|
||||
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
|
||||
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
|
||||
};
|
||||
@@ -1545,7 +1657,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
|
||||
}
|
||||
host.charge_call(path.len() as u64 + 2)?;
|
||||
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
|
||||
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
|
||||
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
|
||||
let error = match f.kind {
|
||||
include::FailKind::Limit => HostError::Abort(message),
|
||||
@@ -1655,6 +1767,22 @@ fn explained(e: &RunError) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
|
||||
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
|
||||
/// the modules are read, which is the order of their sources' tags.
|
||||
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
|
||||
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
|
||||
let source = read.map(|(text, map)| {
|
||||
let mut maps = host.eval_maps.borrow_mut();
|
||||
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
|
||||
maps.push(map);
|
||||
drop(maps);
|
||||
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
|
||||
text
|
||||
});
|
||||
Ok(LoadedModule { key, source })
|
||||
}
|
||||
|
||||
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
|
||||
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
let (kind, message) = match f.kind {
|
||||
@@ -2063,13 +2191,28 @@ impl Session {
|
||||
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
|
||||
return Err(EngineError::Other(NO_RECOVERY_COPY.to_string()));
|
||||
}
|
||||
// The Artboard tool's selection, which the fresh tool state below drops.
|
||||
let picks = cmd::artboard_tool_picks(self);
|
||||
let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks));
|
||||
self.reset_tool();
|
||||
let open: Vec<u64> = self.docs.iter().map(|d| d.uid).collect();
|
||||
self.script_high_water.retain(|uid, _| open.contains(uid));
|
||||
self.script_stop.clear();
|
||||
self.script_report = None;
|
||||
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
|
||||
let expanded = files.expand_script(&request.source);
|
||||
if request.module {
|
||||
files.read_es2015();
|
||||
}
|
||||
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
|
||||
// `module_key` names it among the modules it imports.
|
||||
let (expanded, module_key) = if request.module {
|
||||
match files.module_entry(&request.source) {
|
||||
Ok((key, expanded)) => (Ok(expanded), Some(key)),
|
||||
Err(f) => (Err(f), None),
|
||||
}
|
||||
} else {
|
||||
(files.expand_script(&request.source), None)
|
||||
};
|
||||
let name = match &expanded {
|
||||
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
|
||||
_ => request.name,
|
||||
@@ -2100,9 +2243,8 @@ impl Session {
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
|
||||
// `.js` run that names it, and keeps it as it keeps its globals.
|
||||
let es2015 = include::es2015_script(request.file.as_deref());
|
||||
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
|
||||
let es2015 = request.module || include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
@@ -2171,6 +2313,7 @@ impl Session {
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
module_maps: RefCell::default(),
|
||||
eval_failures: RefCell::default(),
|
||||
script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE),
|
||||
report_name: Arc::from(name.as_str()),
|
||||
@@ -2182,6 +2325,9 @@ impl Session {
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
actions: request.actions,
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
@@ -2232,7 +2378,13 @@ impl Session {
|
||||
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
|
||||
.and_then(|()| {
|
||||
let r = realm.start(&expanded.source);
|
||||
let r = match &module_key {
|
||||
None => realm.start(&expanded.source),
|
||||
Some(key) => {
|
||||
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
|
||||
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
|
||||
}
|
||||
};
|
||||
// Source that does not compile defines no code, so its map is not kept.
|
||||
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
|
||||
host.script_tag.set(realm.script_tag());
|
||||
|
||||
@@ -189,6 +189,7 @@ impl Session {
|
||||
startup_loading: None,
|
||||
startup_failures: vec![],
|
||||
script_high_water: Default::default(),
|
||||
script_style_trail: Default::default(),
|
||||
script_in_run: false,
|
||||
window_views: vec![],
|
||||
script_copy_first: cfg!(target_arch = "wasm32"),
|
||||
|
||||
@@ -129,6 +129,9 @@ impl Session {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
self.reading = outer;
|
||||
if self.script_in_run && self.depth > 0 && r.is_ok() {
|
||||
crate::script::note_style_lists(self);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ mod css;
|
||||
mod curvature_circle;
|
||||
mod cut;
|
||||
mod dashalign;
|
||||
mod dcs;
|
||||
pub(super) mod dcs;
|
||||
mod delete_keeps_joined;
|
||||
mod distort;
|
||||
mod docsetup;
|
||||
@@ -175,6 +175,7 @@ mod repeat_edit;
|
||||
mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_actions;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
@@ -183,9 +184,13 @@ mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_run;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
mod script_tags;
|
||||
mod script_text;
|
||||
mod script_threads;
|
||||
mod script_variables;
|
||||
mod script_xmp;
|
||||
mod scripts;
|
||||
@@ -5167,6 +5172,36 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() {
|
||||
assert!(!s.doc().unwrap().selection.contains(b));
|
||||
}
|
||||
|
||||
/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With
|
||||
/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that
|
||||
/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked
|
||||
/// adds its corner. A Ctrl/Cmd-click (the Selection tool, lent) leaves the picks as they are.
|
||||
#[test]
|
||||
fn corner_widgets_pick_corners_across_paths_through_the_session() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
let all = json!([[0, 0], [0, 1], [0, 2], [0, 3]]);
|
||||
let start = json!({"items": [{"id": a.0, "anchors": [[0, 0]]}, {"id": b.0, "anchors": all}]});
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64, mods: vectorcraft_tools::Mods| {
|
||||
s.execute("select.anchorsMany", &start).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y).with_mods(mods), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(mods), v).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.contains(a) && sel.contains(b), "both stay selected");
|
||||
(sel.partial(a).cloned(), sel.partial(b).cloned())
|
||||
};
|
||||
let shift = vectorcraft_tools::Mods { shift: true, ..Default::default() };
|
||||
// The top-right widget of b.
|
||||
assert_eq!(click(&mut s, 390.0, 110.0, shift), (Some([(0, 0)].into()), Some([(0, 0), (0, 2), (0, 3)].into())));
|
||||
// The top-right widget of a, not picked.
|
||||
assert_eq!(click(&mut s, 190.0, 110.0, shift), (Some([(0, 0), (0, 1)].into()), None));
|
||||
let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
|
||||
assert_eq!(click(&mut s, 190.0, 110.0, cmd), (Some([(0, 0)].into()), None), "a Ctrl/Cmd-click leaves the picks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_commands_reject_bad_anchors_before_modifying_geometry() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4046,6 +4046,26 @@ fn live_paint_bucket_refuses_a_bad_target_or_aligned() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With nothing selected, Invert and Complement refuse a bad `target` or `aligned` and leave the
|
||||
/// default fill and stroke as they are.
|
||||
#[test]
|
||||
fn invert_and_complement_refuse_a_bad_target_or_aligned_with_nothing_selected() {
|
||||
let mut s = session();
|
||||
s.execute("paint.setFill", &json!({"color": "#336699", "defaultsOnly": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = (s.paint.fill.clone(), s.paint.stroke.clone());
|
||||
for cmd in ["paint.invert", "paint.complement"] {
|
||||
for p in
|
||||
[json!({"stroke": false, "target": "content"}), json!({"stroke": false, "aligned": "yes"}), json!({"stroke": true, "target": "bogus"})]
|
||||
{
|
||||
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
|
||||
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), before, "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
s.execute("paint.invert", &json!({"stroke": false})).unwrap();
|
||||
assert_ne!(s.paint.fill, before.0, "a good call still inverts the default");
|
||||
}
|
||||
|
||||
/// While the Live Paint Bucket is active, each preview of a paint command in one interaction starts
|
||||
/// from the colors the interaction began with, so previewing a swap twice and committing swaps once.
|
||||
#[test]
|
||||
|
||||
@@ -776,6 +776,33 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
|
||||
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
|
||||
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
|
||||
// The fix is the color to store: the stain mixes it half way to black again, and the result
|
||||
// just meets AA against white.
|
||||
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
|
||||
assert_eq!(r["normalText"]["aa"], false, "{r}");
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
|
||||
let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
|
||||
assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}");
|
||||
}
|
||||
|
||||
/// A pick for a picked symbol object with a fill of None puts a solid color there, which the
|
||||
/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained.
|
||||
#[test]
|
||||
fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() {
|
||||
let mut s = picked_symbol_part();
|
||||
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
|
||||
s.active_mut().unwrap().selection.symbol_part = None;
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
|
||||
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
|
||||
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap();
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0)));
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
|
||||
assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -877,3 +904,309 @@ fn a_fill_of_none_has_no_color_to_measure() {
|
||||
assert!(e.contains("has no color"), "{e}");
|
||||
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
|
||||
}
|
||||
|
||||
fn fix_color(v: &Value) -> vectorcraft_color::Color {
|
||||
crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
|
||||
}
|
||||
|
||||
fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
|
||||
let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
|
||||
assert_eq!(r["for"], "normalText");
|
||||
let aa = fix_color(&r["fix"]["aa"]);
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
|
||||
let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
|
||||
assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
|
||||
assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
|
||||
// White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
|
||||
assert!(r["fix"]["aaa"].is_null(), "{r}");
|
||||
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
|
||||
let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
|
||||
}
|
||||
|
||||
/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too:
|
||||
/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again,
|
||||
/// and the fix has to paint as #767676 (4.54:1) or darker.
|
||||
#[test]
|
||||
fn a_fix_passes_as_the_canvas_paints_it() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
|
||||
let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]);
|
||||
assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}");
|
||||
// The fix is the closest one: the gray one 8-bit step lighter fails.
|
||||
let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0));
|
||||
assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
|
||||
}
|
||||
|
||||
/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black,
|
||||
/// so the Color Wheel's contrast lines use the same color.
|
||||
#[test]
|
||||
fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() {
|
||||
let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let mut s = Session::new();
|
||||
let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"});
|
||||
let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
|
||||
assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]);
|
||||
s.prefs.black_on_screen = "rich".into();
|
||||
let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
|
||||
assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]);
|
||||
assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}");
|
||||
}
|
||||
|
||||
/// A translucent fix also meets the minimum with the color, the opacity, the background and the
|
||||
/// composited pixel rounded to 8 bits per channel.
|
||||
#[test]
|
||||
fn a_translucent_fix_passes_at_eight_bits() {
|
||||
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
|
||||
let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| {
|
||||
let (a, b) = (eight(opacity), eight(against));
|
||||
let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a)));
|
||||
vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3])
|
||||
};
|
||||
let mut s = Session::new();
|
||||
// A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at
|
||||
// 232 / 255 its pixel is #747474 (4.49:1).
|
||||
let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}");
|
||||
// #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is
|
||||
// 4.4965:1.
|
||||
let bg = 137.51 / 255.0;
|
||||
let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}");
|
||||
// Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray
|
||||
// at that opacity gets a fix.
|
||||
let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
assert_eq!(r["graphics"]["aa"], false, "{r}");
|
||||
assert!(r["fix"]["aa"].is_null(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
|
||||
assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
|
||||
let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
|
||||
assert_eq!(g["for"], "graphics");
|
||||
let fix = g["fix"].as_object().unwrap();
|
||||
assert_eq!(fix.keys().collect::<Vec<_>>(), ["aa"], "{g}");
|
||||
let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
|
||||
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
|
||||
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
|
||||
assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
|
||||
assert!(!large["fix"]["aaa"].is_null(), "{large}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_color_answers_a_cmyk_fix() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
|
||||
assert_eq!(r["normalText"]["aa"], false, "{r}");
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
|
||||
assert!(ratio(&back) >= 4.5, "{back}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
|
||||
let mut s = Session::new();
|
||||
// #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
|
||||
// meets large text AA (3:1) but not AAA (4.5:1).
|
||||
let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
assert_eq!(r["largeText"]["aa"], false, "{r}");
|
||||
assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
|
||||
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
|
||||
}
|
||||
|
||||
/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a
|
||||
/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws
|
||||
/// as it is, on the canvas and in the answer, for each blend mode of the object.
|
||||
#[test]
|
||||
fn isolation_leaves_a_translucent_normal_row_as_it_draws() {
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
for blend in ["normal", "multiply", "screen", "difference", "overlay"] {
|
||||
for fill in ["#808080", "#ffffff", "#2040a0"] {
|
||||
for lower in [false, true] {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
if lower {
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
}
|
||||
let st = s.active().unwrap();
|
||||
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
|
||||
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap();
|
||||
if lower {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [n]})).unwrap();
|
||||
}
|
||||
let plain = s.execute("color.contrast", &json!({})).unwrap();
|
||||
let (p, drawn) = canvas_ratio(&s, &plain);
|
||||
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
|
||||
let isolated = s.execute("color.contrast", &json!({})).unwrap();
|
||||
let (q, _) = canvas_ratio(&s, &isolated);
|
||||
let case = format!("{blend} {fill} lower row and group: {lower}");
|
||||
assert_eq!(p, q, "the canvas draws the same: {case}");
|
||||
assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}");
|
||||
assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one
|
||||
/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the
|
||||
/// other, so the white draws over different rows and there is no one answer. A given background
|
||||
/// stands for the rows below and answers.
|
||||
#[test]
|
||||
fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() {
|
||||
let mut s = session();
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let square = |s: &mut Session, x: i32, isolate: bool| {
|
||||
let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
|
||||
let top = items.iter().rposition(|i| i.is_fill()).unwrap();
|
||||
let lower = items.iter().position(|i| i.is_fill()).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
if isolate {
|
||||
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
|
||||
}
|
||||
n
|
||||
};
|
||||
let a = square(&mut s, 30, false);
|
||||
let b = square(&mut s, 120, true);
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}");
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("the selected objects' colors differ"), "{e}");
|
||||
s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
|
||||
// A blending row at no opacity does not show, so the isolation no longer changes the answer.
|
||||
for n in [a, b] {
|
||||
let st = s.active().unwrap();
|
||||
let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap();
|
||||
}
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// A Difference square centered on the edge between locked black and white art: the art behind it
|
||||
/// is not one color where it is read, so no one color stands for it; a given background answers,
|
||||
/// and over one color the background is read as before.
|
||||
#[test]
|
||||
fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
// Without the default stroke, which would cover the edge.
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}");
|
||||
let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
|
||||
assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}");
|
||||
// In Normal mode the color is drawn as it is, over the background read as one color.
|
||||
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
// Moved over the white art alone, the square blends with one color again.
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap();
|
||||
let r = s.execute("color.contrast", &json!({})).unwrap();
|
||||
assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
|
||||
}
|
||||
|
||||
/// A Difference square over a white square in a 50 % group that isolates its blending, over the
|
||||
/// edge between black and white art: the square blends only with the white inside the group, so
|
||||
/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
|
||||
#[test]
|
||||
fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
|
||||
let mut s = session();
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [square]})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
|
||||
/// contrast lines show where a solid color in its place passes.
|
||||
#[test]
|
||||
fn a_pick_for_a_fill_of_none_is_measured_against_the_background() {
|
||||
let mut s = blended_over_red("normal");
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
|
||||
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap();
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]);
|
||||
assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}");
|
||||
assert_eq!(backdrop.against_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_takes_only_the_three_categories() {
|
||||
let mut s = Session::new();
|
||||
for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
|
||||
let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column.
|
||||
fn two_plates() -> Vec<u8> {
|
||||
pub(crate) fn two_plates() -> Vec<u8> {
|
||||
single_file(
|
||||
&[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))],
|
||||
"%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n",
|
||||
@@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts
|
||||
/// the file's image between the corners and draws its clipping path through them.
|
||||
#[test]
|
||||
fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() {
|
||||
let dir = temp_dir("replace-distorted-clip");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
|
||||
let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap();
|
||||
let old = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
|
||||
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = NodeId(r["image"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(node.is_distorted_image());
|
||||
assert_eq!(node.image_corners().unwrap(), corners);
|
||||
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
|
||||
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
|
||||
let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect();
|
||||
// The left half of the 2 × 2 pixels, where the corners put it.
|
||||
let map = node.image_map().unwrap();
|
||||
let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
|
||||
assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
|
||||
let dir = temp_dir("update-gained-clip");
|
||||
|
||||
@@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step:
|
||||
/// the new file's pixels fill them, the new image is linked to that file, and its transform is the
|
||||
/// old image's scaled to the new pixel size. Undo brings the old image back between the same
|
||||
/// corners.
|
||||
#[test]
|
||||
fn place_with_replace_keeps_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-place-replace");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Around the artboard's center, where `centre_colour` looks.
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned();
|
||||
let before = node(&s, id).unwrap().image_corners().unwrap();
|
||||
let old_xf = image(&s, id).xf;
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let undo = undo_len(&s);
|
||||
|
||||
let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap();
|
||||
let new = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(node(&s, id).is_none(), "the old image is replaced");
|
||||
let n = node(&s, new).unwrap();
|
||||
assert!(n.is_distorted_image());
|
||||
assert_eq!(n.image_corners().unwrap(), before);
|
||||
let im = image(&s, new);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
|
||||
let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0);
|
||||
assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, new).is_none());
|
||||
assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
|
||||
|
||||
@@ -3195,6 +3195,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() {
|
||||
assert!(install(&mut s, DESATURATE).get("budget").is_none());
|
||||
}
|
||||
|
||||
/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its
|
||||
/// name is escaped, so it can't reorder the message around it.
|
||||
#[test]
|
||||
fn a_heavy_filter_refusal_escapes_its_name() {
|
||||
let mut s = session();
|
||||
// The override as a JSON escape in the manifest.
|
||||
let rlo = format!("\\u{:04X}", 0x202E);
|
||||
let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#);
|
||||
let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap();
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string();
|
||||
assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}");
|
||||
}
|
||||
|
||||
/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed
|
||||
/// without any of its code running: its start function traps and its `vc_manifest` export loops.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
//! `app.doScript`: a script plays an action of `script.run`'s `actions`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions}))
|
||||
}
|
||||
|
||||
fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec<Value> {
|
||||
let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The error message a `try` around `call` logs, or `"ok"`.
|
||||
fn caught(s: &mut Session, call: &str, actions: &Value) -> String {
|
||||
let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}");
|
||||
log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
|
||||
}
|
||||
|
||||
fn undo_labels(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
|
||||
}
|
||||
|
||||
fn rect(x: i64) -> Value {
|
||||
json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}})
|
||||
}
|
||||
|
||||
/// One set, `Set`, with the actions given as (name, steps).
|
||||
fn set(actions: &[(&str, Vec<Value>)]) -> Value {
|
||||
Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_script_plays_every_step_as_one_undo_step_with_the_script() {
|
||||
let mut s = doc();
|
||||
let before = undo_labels(&s);
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions);
|
||||
assert_eq!(out, vec![Value::Null], "doScript returns undefined");
|
||||
assert_eq!(objects(&s), 3);
|
||||
let after = undo_labels(&s);
|
||||
assert_eq!(after.len(), before.len() + 1, "{after:?}");
|
||||
assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL));
|
||||
// The steps of a recorded `command.batch` run one by one, each counted as a host call.
|
||||
let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]);
|
||||
let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap();
|
||||
assert_eq!(objects(&s), 6);
|
||||
let r0 = run_with(&mut s, "1;", &batch).unwrap();
|
||||
assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_throw_puts_back_what_the_action_did() {
|
||||
let mut s = doc();
|
||||
let before = (objects(&s), undo_labels(&s));
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains("late"), "{e}");
|
||||
assert_eq!((objects(&s), undo_labels(&s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_step_is_put_back_and_the_steps_before_it_stay() {
|
||||
let mut s = doc();
|
||||
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
|
||||
let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]);
|
||||
let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}");
|
||||
assert_eq!(objects(&s), 1, "the first step stays done and the third never runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_matched_exactly_and_must_be_one_action() {
|
||||
let mut s = doc();
|
||||
let actions = json!([
|
||||
{"set": "Set", "name": "One", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Empty", "steps": []},
|
||||
]);
|
||||
assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”");
|
||||
assert_eq!(objects(&s), 0);
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok");
|
||||
assert_eq!(objects(&s), 1);
|
||||
assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet");
|
||||
assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_change_nothing() {
|
||||
let mut s = doc();
|
||||
let actions = set(&[("One", vec![rect(0)])]);
|
||||
for (call, want) in [
|
||||
("app.doScript()", "TypeError"),
|
||||
("app.doScript(1, 'Set')", "TypeError"),
|
||||
("app.doScript('One', {})", "TypeError"),
|
||||
("app.doScript('One', 'Set', 'yes')", "TypeError"),
|
||||
("app.doScript('One', 'Set', 1)", "TypeError"),
|
||||
("app.doScript('One', 'Set', false, 4)", "TypeError"),
|
||||
("app.doScript('', 'Set')", "Error"),
|
||||
("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"),
|
||||
] {
|
||||
let m = caught(&mut s, call, &actions);
|
||||
assert!(m.starts_with(&format!("{want}:")), "{call}: {m}");
|
||||
}
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_a_script_may_not_run_stop_the_action_before_any_step() {
|
||||
let mut s = doc();
|
||||
s.prefs.show_external_script_warning = true;
|
||||
let steps = [
|
||||
(json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"),
|
||||
(json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"),
|
||||
(json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"),
|
||||
(json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"),
|
||||
(json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"),
|
||||
(json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"),
|
||||
];
|
||||
for (bad, want) in steps {
|
||||
let actions = set(&[("Loop", vec![rect(0), bad.clone()])]);
|
||||
let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}");
|
||||
assert_eq!(objects(&s), 0, "{bad}: no step ran");
|
||||
}
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
// A refused command inside a recorded batch is refused too.
|
||||
let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]);
|
||||
let m = caught(&mut s, "app.doScript('B', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
// So is one among the commands a Batch step plays on each file, before the steps ahead of it run.
|
||||
let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}});
|
||||
let batch = set(&[("F", vec![rect(0), files])]);
|
||||
let m = caught(&mut s, "app.doScript('F', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_step_keeps_the_scripts_file_gate() {
|
||||
let mut s = doc();
|
||||
let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}});
|
||||
let actions = set(&[("Export", vec![export])]);
|
||||
let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions);
|
||||
assert!(m.contains("Script file access denied"), "{m}");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_action_is_held_to_the_host_call_limit() {
|
||||
let mut s = doc();
|
||||
// Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the
|
||||
// steps of one call cannot pass the limit.
|
||||
let calls = |s: &mut Session, steps: usize| {
|
||||
let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]);
|
||||
run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap()
|
||||
};
|
||||
let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001));
|
||||
assert!(many >= one + 2000, "{one} {many}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_action_lists_are_refused_before_the_script_runs() {
|
||||
let mut s = doc();
|
||||
let step = || json!({"command": "select.none"});
|
||||
let cases = [
|
||||
(json!({}), "`actions` must be a list"),
|
||||
(json!([1]), "`actions[0]` must be an object"),
|
||||
(json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"),
|
||||
(json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"),
|
||||
(
|
||||
json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]),
|
||||
"a command.batch inside a command.batch",
|
||||
),
|
||||
(json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"),
|
||||
(Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"),
|
||||
(json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"),
|
||||
];
|
||||
for (actions, want) in cases {
|
||||
let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{want}: {e}");
|
||||
}
|
||||
let many: Vec<Value> = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect();
|
||||
let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 100000 steps in all"), "{e}");
|
||||
assert_eq!(objects(&s), 0, "no run started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() {
|
||||
let mut s = doc();
|
||||
let first = set(&[("One", vec![rect(0)])]);
|
||||
log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first);
|
||||
assert_eq!(objects(&s), 0);
|
||||
// The next run has no actions: the function kept from the first run finds none.
|
||||
let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }";
|
||||
assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]);
|
||||
let two = set(&[("One", vec![rect(0), rect(30)])]);
|
||||
assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]);
|
||||
assert_eq!(objects(&s), 2);
|
||||
}
|
||||
|
||||
/// Makes artboard `index` of the active document the view's active one, as the app does before each
|
||||
/// command.
|
||||
fn make_active(s: &mut Session, index: usize) {
|
||||
let id = s.active().unwrap().doc.artboards[index].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(id);
|
||||
}
|
||||
|
||||
/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected
|
||||
/// Art, acts on the active artboard's index as the run started; after the script deletes that
|
||||
/// artboard, the last one. A step that names its artboard keeps it.
|
||||
#[test]
|
||||
fn steps_act_on_the_artboard_active_as_they_run() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let was = boards(&s);
|
||||
make_active(&mut s, 2);
|
||||
let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}});
|
||||
let mut first = align(json!(0));
|
||||
first["params"].as_object_mut().unwrap().remove("artboard");
|
||||
let actions = set(&[
|
||||
("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]),
|
||||
("Align 1", vec![align(json!(0))]),
|
||||
("Fit", vec![json!({"command": "artboard.fitToSelection"})]),
|
||||
]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions);
|
||||
let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was");
|
||||
assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other");
|
||||
log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
make_active(&mut s, 1);
|
||||
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
|
||||
let mut own = align.clone();
|
||||
own["params"]["artboard"] = json!(1);
|
||||
let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}});
|
||||
let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "app.doScript('First', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "the batch's artboard 0");
|
||||
log_with(&mut s, "app.doScript('Past', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one");
|
||||
log_with(&mut s, "app.doScript('Own', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it");
|
||||
}
|
||||
|
||||
/// The active artboard a step gets is the index it had as the run started: after a step deletes an
|
||||
/// artboard before it, the artboard now at that index, as the view shows it.
|
||||
#[test]
|
||||
fn steps_keep_the_active_artboards_index() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None };
|
||||
let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({}));
|
||||
assert_eq!(add(&s), json!({"artboard": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1");
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one");
|
||||
}
|
||||
|
||||
/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its
|
||||
/// `indices` fits those.
|
||||
#[test]
|
||||
fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
make_active(&mut s, 1);
|
||||
let actions = set(&[
|
||||
("Fit", vec![json!({"command": "artboard.fitToArt"})]),
|
||||
("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]),
|
||||
]);
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art");
|
||||
log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), art, "the step's own indices");
|
||||
}
|
||||
|
||||
/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it
|
||||
/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps
|
||||
/// still get the active one.
|
||||
#[test]
|
||||
fn paste_and_fit_steps_keep_the_artboard_tools_selection() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
let start = script::actions::Start { active: &[], picks: None, batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
assert_eq!(add(&s, id), json!({}), "{id}");
|
||||
}
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
assert_eq!(add(&s, "object.align"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "shape.rectangle"), json!({}));
|
||||
}
|
||||
|
||||
/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays,
|
||||
/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to
|
||||
/// Artwork Bounds step fits them.
|
||||
#[test]
|
||||
fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
|
||||
// Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2.
|
||||
let setup = || {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
(s, was, art)
|
||||
};
|
||||
let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]);
|
||||
let (mut s, ..) = setup();
|
||||
let before = objects(&s);
|
||||
log_with(&mut s, "app.doScript('Paste', 'Set');", &actions);
|
||||
assert_eq!(objects(&s), before + 2, "one copy on each selected artboard");
|
||||
let (mut s, was, art) = setup();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
|
||||
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
|
||||
let (mut s, ..) = setup();
|
||||
s.reset_tool();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let kept = (uid, vec![0, 2]);
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
}
|
||||
@@ -356,6 +356,37 @@ fn page_item_properties_join_one_undo_step() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one
|
||||
/// undo step. They change nothing past the run's first edit or its last undone one.
|
||||
#[test]
|
||||
fn app_undo_and_redo_step_through_the_runs_edits() {
|
||||
let (mut s, a, b) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\
|
||||
app.undo(); app.redo();\
|
||||
i.name = 'first'; i.opacity = 40;\
|
||||
app.undo(); vc.log([i.name, i.opacity]);\
|
||||
app.redo(); vc.log(i.opacity);\
|
||||
app.redo(); vc.log(i.opacity);\
|
||||
app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\
|
||||
vc.log(typeof app.undo());\
|
||||
d.pageItems[1].name = 'kept';",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
let st = s.active().unwrap();
|
||||
let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect();
|
||||
assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run");
|
||||
let mut s = Session::new();
|
||||
assert!(failure(&mut s, "app.undo();").contains("No active document"));
|
||||
assert!(failure(&mut s, "app.redo();").contains("No active document"));
|
||||
}
|
||||
|
||||
/// An opacity a graph mark already has still replaces the opacity another mark of its series left on
|
||||
/// the graph, as `object.setProps` does.
|
||||
#[test]
|
||||
@@ -1767,6 +1798,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() {
|
||||
assert_eq!(out, vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}");
|
||||
assert!(s.active().unwrap().doc.node(t).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_duplicate_refuse_art_on_a_locked_artboard() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -2232,6 +2280,36 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
|
||||
}
|
||||
|
||||
/// A collection read with a name that is the text of a number but not an array index, such as `-1`
|
||||
/// or `1.5`, gives the object of that name, and `undefined` when nothing has it; array indices stay
|
||||
/// positions, and `index` still takes a number as a position.
|
||||
#[test]
|
||||
fn a_collection_read_with_a_number_name_that_is_not_an_index_gives_the_named_object() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "name": "NaN"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, m = [];\
|
||||
vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p.NaN === p.getByName('NaN'), 'NaN' in p]);\
|
||||
vc.log([p['1.5'] === undefined, '1.5' in p, p[0].name, p['1'].name]);\
|
||||
try { p.index(-1); } catch (e) { m.push(e.message); }\
|
||||
var t = new DocumentPreset(); t.title = '1.5'; var d = app.documents.addDocument('Print', t);\
|
||||
var ds = app.documents; vc.log([ds['1.5'] === d, '1.5' in ds, ds[1.5] === d, ds['-1'] === undefined, '-1' in ds]);\
|
||||
try { ds.index(1.5); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!([true, true, true, true, true]),
|
||||
json!([true, false, "NaN", "-1"]),
|
||||
json!([true, true, true, true, false]),
|
||||
json!(["Not found", "Not found"]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or
|
||||
/// locked layer throw and the run changes nothing, while its name and note still change; an object
|
||||
/// that is hidden or locked itself takes them.
|
||||
|
||||
@@ -376,6 +376,8 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
module: false,
|
||||
actions: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of
|
||||
//! specifiers and paths, the run's limits, and errors at the file they are in.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// Runs `main/<file>` in `base`, with the text `text`.
|
||||
fn run_file(base: &Path, file: &str, text: &str) -> (Result<Value>, Session) {
|
||||
let main = base.join("main").join(file);
|
||||
write(&main, text);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()}));
|
||||
(r, s)
|
||||
}
|
||||
|
||||
fn run(base: &Path, text: &str) -> Result<Value> {
|
||||
run_file(base, "main.mjs", text).0
|
||||
}
|
||||
|
||||
/// The report of the run of `main/main.mjs` that failed.
|
||||
fn failed(base: &Path, text: &str) -> Value {
|
||||
let (r, s) = run_file(base, "main.mjs", text);
|
||||
assert!(r.is_err(), "the run failed: {r:?}");
|
||||
s.script_report().unwrap().clone()
|
||||
}
|
||||
|
||||
fn message(report: &Value) -> &str {
|
||||
report["message"].as_str().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_imports_from_its_folder_and_below() {
|
||||
let base = folder("imports");
|
||||
write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';");
|
||||
write(
|
||||
&base.join("main/lib/use.mjs"),
|
||||
"import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();",
|
||||
);
|
||||
let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);";
|
||||
let r = run(&base, text).unwrap();
|
||||
// count.mjs ran once: use.mjs and the script share its binding.
|
||||
assert_eq!(r["log"], json!([[2, "lib", true, true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_two_modules_import_each_other() {
|
||||
let base = folder("cycle");
|
||||
write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }");
|
||||
write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();");
|
||||
let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap();
|
||||
assert_eq!(r["log"], json!([["ab", "ab"]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_path_above_the_script_folder_is_refused() {
|
||||
let base = folder("above");
|
||||
write(&base.join("outside.mjs"), "export var leaked = 1;");
|
||||
let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';");
|
||||
assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}");
|
||||
// `..` names that stay inside are read by name.
|
||||
write(&base.join("main/sub/x.mjs"), "export var x = 'x';");
|
||||
let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap();
|
||||
assert_eq!(r["log"], json!(["x"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_missing_file_is_named() {
|
||||
let base = folder("missing");
|
||||
write(&base.join("main/a.mjs"), "import './nope.mjs';");
|
||||
let report = failed(&base, "import './a.mjs';");
|
||||
assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}");
|
||||
assert_eq!(report["line"], 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() {
|
||||
let base = folder("specifiers");
|
||||
// The specifier as the script writes it, as the error names it, and why it is refused.
|
||||
for (written, shown, why) in [
|
||||
("lib", "lib", "must start with './' or '../'"),
|
||||
("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"),
|
||||
("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"),
|
||||
("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"),
|
||||
("./C:x.mjs", "./C:x.mjs", "must not contain"),
|
||||
("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"),
|
||||
("./x.txt", "./x.txt", "must name a .mjs or .js file"),
|
||||
("./x", "./x", "must name a .mjs or .js file"),
|
||||
] {
|
||||
let report = failed(&base, &format!("import '{written}';"));
|
||||
let expected = format!("SyntaxError: module specifier '{shown}' {why}");
|
||||
assert!(message(&report).starts_with(&expected), "{written}: {report}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_errors_are_at_the_file_they_are_in() {
|
||||
let base = folder("errors");
|
||||
write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;");
|
||||
let report = failed(&base, "import { a } from './bad.mjs';");
|
||||
assert_eq!(report["kind"], "syntax", "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}");
|
||||
assert_eq!(report["line"], 2);
|
||||
write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');");
|
||||
let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}");
|
||||
let report = failed(&base, "import { b } from './thrower.mjs';");
|
||||
assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_preprocessor_lines_and_scripts_differ_by_extension() {
|
||||
let base = folder("kinds");
|
||||
write(&base.join("main/lib.jsxinc"), "var included = 1;");
|
||||
// A module has no preprocessor lines.
|
||||
let report = failed(&base, "#include \"lib.jsxinc\"\n");
|
||||
assert_eq!(report["kind"], "syntax", "{report}");
|
||||
// A .js or .jsx script does not read import or export.
|
||||
for file in ["main.js", "main.jsx"] {
|
||||
let (r, s) = run_file(&base, file, "import { a } from './a.mjs';");
|
||||
assert!(r.is_err(), "{file}");
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_files_count_against_the_include_limits() {
|
||||
let base = folder("limits");
|
||||
for i in 0..70 {
|
||||
write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1));
|
||||
}
|
||||
let report = failed(&base, "import './m0.mjs';");
|
||||
assert!(message(&report).contains("limit"), "{report}");
|
||||
assert_eq!(report["log"], json!([]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_paths_of_one_file_give_one_module() {
|
||||
let base = folder("same");
|
||||
write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;");
|
||||
let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string();
|
||||
// Windows file names ignore letter case.
|
||||
if cfg!(windows) {
|
||||
text.push_str("import { v as u } from './ONCE.mjs';\n");
|
||||
}
|
||||
let r = run(&base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["ran"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere.
|
||||
/// `false` when the system does not allow it here.
|
||||
fn link_folder(target: &Path, link: &Path) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
|
||||
made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok()
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, link).is_ok()
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = (target, link);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_link_out_of_the_folder_is_refused() {
|
||||
let base = folder("link");
|
||||
write(&base.join("outside/x.mjs"), "export var leaked = 1;");
|
||||
if !link_folder(&base.join("outside"), &base.join("main").join("away")) {
|
||||
eprintln!("skipped: a folder link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);");
|
||||
assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_is_listed_and_taken_by_path() {
|
||||
assert!(cmd::scripts::runs("tool.MJS"));
|
||||
let base = folder("text");
|
||||
let root = base.join("Scripts");
|
||||
write(&root.join("tool.mjs"), "export var a = 1;");
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
let listed = s.execute("script.listInstalled", &json!({})).unwrap();
|
||||
assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}]));
|
||||
// A script given as text is not a module, whatever its name.
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"}));
|
||||
assert!(r.is_err());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_is_chosen_by_the_module_param() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap();
|
||||
assert_eq!(r["log"], json!([[1, true]]));
|
||||
// A source run as a module imports no files.
|
||||
let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true}));
|
||||
assert!(r.is_err());
|
||||
assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report());
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
|
||||
// `module: false` runs a .mjs file as a script, where `export` is a syntax error.
|
||||
let base = folder("param");
|
||||
let main = base.join("main").join("main.mjs");
|
||||
write(&main, "export var a = 1;");
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false}));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_read_again_through_another_path_is_not_counted_again() {
|
||||
let base = folder("budget");
|
||||
// 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run.
|
||||
let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024));
|
||||
write(&base.join("main/lib/big.mjs"), &big);
|
||||
let mut text = String::new();
|
||||
for i in 0..5 {
|
||||
if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) {
|
||||
eprintln!("skipped: a folder link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n"));
|
||||
}
|
||||
text.push_str("vc.log(v0 + v4);");
|
||||
let r = run(&base, &text);
|
||||
assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2])));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_imports_are_read_from_the_folder_the_file_is_in() {
|
||||
let base = folder("realdir");
|
||||
write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;");
|
||||
write(&base.join("main/real/dep.mjs"), "export const d = 'real';");
|
||||
write(&base.join("main/other/dep.mjs"), "export const d = 'other';");
|
||||
#[cfg(unix)]
|
||||
let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
|
||||
#[cfg(windows)]
|
||||
let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let linked = false;
|
||||
if !linked {
|
||||
eprintln!("skipped: a file link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap();
|
||||
assert_eq!(r["log"], json!(["real"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_eval_file_reads_beside_the_module_that_calls_it() {
|
||||
let base = folder("evalfile");
|
||||
write(&base.join("main/helper.jsx"), "'top'");
|
||||
write(&base.join("main/sub/helper.jsx"), "'sub'");
|
||||
write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');");
|
||||
let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap();
|
||||
assert_eq!(r["log"], json!([["sub", "top"]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() {
|
||||
let base = folder("evalfile-entry");
|
||||
write(&base.join("main/helper.jsx"), "'top'");
|
||||
write(&base.join("main/sub/helper.jsx"), "'sub'");
|
||||
// The file in `sub` calls the script's function while it is the file being run.
|
||||
write(&base.join("main/sub/caller.jsx"), "$.global.load()");
|
||||
let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));";
|
||||
let r = run(&base, text).unwrap();
|
||||
assert_eq!(r["log"], json!(["top"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() {
|
||||
("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"),
|
||||
("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"),
|
||||
("throw 'invalid array length';", "thrown", "invalid array length", "script"),
|
||||
("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"),
|
||||
("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"),
|
||||
("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"),
|
||||
("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"),
|
||||
("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"),
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
//! Character and paragraph styles in the script object model.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{TextObject, TextStyleDef};
|
||||
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA};
|
||||
use crate::script::TEST_RESULT_BYTES;
|
||||
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 undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with point type holding `text`.
|
||||
fn doc_with(text: &str) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
(s, NodeId(id))
|
||||
}
|
||||
|
||||
fn text_of(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each run's text, style name, size and underline.
|
||||
fn runs(s: &Session, id: NodeId) -> Vec<(String, Option<String>, f64, bool)> {
|
||||
text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect()
|
||||
}
|
||||
|
||||
fn char_names(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect()
|
||||
}
|
||||
|
||||
const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];";
|
||||
|
||||
#[test]
|
||||
fn style_collections_list_the_normal_style_first_and_add_find_and_remove() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\
|
||||
var b = cs.add('Body'); var p = ps.add('Lead');\
|
||||
vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\
|
||||
vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\
|
||||
cs.add('Other'); cs.removeAll(); ps.removeAll();\
|
||||
vc.log([cs.length, ps.length, cs[0].name]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"]));
|
||||
assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"]));
|
||||
assert_eq!(out[2], json!([2, "Lead", true]));
|
||||
assert_eq!(out[3], json!([1, 1, NORMAL_CHAR]));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
let undo = undo_steps(&s);
|
||||
for (src, says) in [
|
||||
("cs.getByName('Nope');", "Not found"),
|
||||
("cs.index(4);", "Not found"),
|
||||
("cs.add('Body'); cs.add('Body');", "already exists"),
|
||||
("cs[0].remove();", "cannot be removed"),
|
||||
("ps[0].name = 'Mine';", "cannot be renamed"),
|
||||
("cs.getByName(5);", "string"),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::<String>::new()));
|
||||
}
|
||||
|
||||
/// Names are trimmed; an empty name, one past 256 characters and one with a control character
|
||||
/// are refused with nothing changed.
|
||||
#[test]
|
||||
fn style_names_are_trimmed_and_checked() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256)));
|
||||
assert_eq!(out, [json!("Lead"), json!(256)]);
|
||||
let undo = undo_steps(&s);
|
||||
let long = "x".repeat(257);
|
||||
for (src, says) in [
|
||||
("cs.add(' ');".to_string(), "empty"),
|
||||
(format!("cs.add('{long}');"), "256 characters"),
|
||||
("cs.add('a\\u0007b');".to_string(), "control characters"),
|
||||
("ps.add('tab\\there');".to_string(), "control characters"),
|
||||
("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"),
|
||||
("cs.add(5);".to_string(), "string"),
|
||||
(format!("cs.getByName('{}');", "y".repeat(5000)), "too long"),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
assert_eq!(char_names(&s).len(), 2);
|
||||
// Path characters are kept as part of the name; a style name never names a file.
|
||||
let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);"));
|
||||
assert_eq!(out, [json!("../a/b\\c:*?")]);
|
||||
assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?"));
|
||||
}
|
||||
|
||||
/// A style attribute that is not a finite number in range is refused with nothing changed.
|
||||
#[test]
|
||||
fn style_attributes_refuse_values_that_are_not_finite_or_in_range() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');"));
|
||||
let undo = undo_steps(&s);
|
||||
for (src, says) in [
|
||||
("cs[1].characterAttributes.size = NaN;", "finite number"),
|
||||
("cs[1].characterAttributes.size = Infinity;", "finite number"),
|
||||
("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"),
|
||||
("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"),
|
||||
("cs[1].characterAttributes.tracking = -1e9;", "tracking"),
|
||||
("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"),
|
||||
("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
let attrs = |s: &Session| {
|
||||
s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::<usize>()
|
||||
};
|
||||
assert_eq!(attrs(&s), 0);
|
||||
}
|
||||
|
||||
/// A style object follows its style through a rename made with it; after the style is removed,
|
||||
/// with the object or with a command, every member throws, and a new style of that name does not
|
||||
/// bring it back.
|
||||
#[test]
|
||||
fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() {
|
||||
let (mut s, id) = doc_with("Hello");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\
|
||||
a.name = 'B'; vc.log(cs.length);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!(["B", "B", true]), json!(2)]);
|
||||
assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B"));
|
||||
for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] {
|
||||
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;"));
|
||||
assert!(e.contains("Stale style"), "{remove}: {e}");
|
||||
}
|
||||
// A style removed and made again by commands is another style.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// So is a style removed and made again by the steps of one batch.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \
|
||||
{{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// And a style a batch renames and then names back.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \
|
||||
{{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// The attributes object of a removed style throws for its typename too.
|
||||
let e =
|
||||
failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// A style renamed by a command is stale too, and its text keeps its look after a removal.
|
||||
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
let e =
|
||||
failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
let size = runs(&s, id)[0].2;
|
||||
log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();"));
|
||||
assert_eq!(runs(&s, id)[0].1, None);
|
||||
assert_ne!(runs(&s, id)[0].2, size);
|
||||
assert_eq!(runs(&s, id)[0].2, 40.0);
|
||||
}
|
||||
|
||||
/// The steps of one batch a script runs keep one copy of a document's style lists, however many of
|
||||
/// them change the lists.
|
||||
#[test]
|
||||
fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let commands: Vec<Value> = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect();
|
||||
s.script_in_run = true;
|
||||
let r = s.execute("command.batch", &json!({"commands": commands}));
|
||||
s.script_in_run = false;
|
||||
r.unwrap();
|
||||
assert_eq!(char_names(&s).len(), 20);
|
||||
assert_eq!(crate::script::retained_style_lists(&s), 1);
|
||||
}
|
||||
|
||||
/// A removal or rename whose result cannot cross to the script is put back, and the style's object
|
||||
/// still names the style after it.
|
||||
#[test]
|
||||
fn a_style_change_that_is_put_back_keeps_the_style_object() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap();
|
||||
TEST_RESULT_BYTES.with(|b| b.set(Some(1)));
|
||||
let r = run(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B');\
|
||||
try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\
|
||||
try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\
|
||||
try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\
|
||||
vc.log([a.name, a === cs.getByName('B'), cs.length]);"
|
||||
),
|
||||
);
|
||||
TEST_RESULT_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}");
|
||||
assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s));
|
||||
}
|
||||
|
||||
/// A character style styles exactly the range; without clearing overrides the range keeps its
|
||||
/// own underline, and with them it goes back to the Normal style first.
|
||||
#[test]
|
||||
fn apply_to_styles_a_range_and_clearing_overrides_resets_it() {
|
||||
let (mut s, id) = doc_with("Hello world");
|
||||
let before = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
&format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"),
|
||||
);
|
||||
assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);"));
|
||||
assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false));
|
||||
// A whole frame, and an empty range, which changes nothing.
|
||||
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);"));
|
||||
assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]);
|
||||
}
|
||||
|
||||
/// A character style applied to an empty frame styles the text set in it later.
|
||||
#[test]
|
||||
fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() {
|
||||
for target in ["tf", "tf.textRange"] {
|
||||
let (mut s, id) = doc_with("");
|
||||
log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';"));
|
||||
assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph style styles every paragraph the text touches, and only those.
|
||||
#[test]
|
||||
fn a_paragraph_style_styles_the_paragraphs_the_text_touches() {
|
||||
let (mut s, id) = doc_with("one\ntwo\nthree");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\
|
||||
vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\
|
||||
a.justification = Justification.CENTER; a.spaceBefore = 6;\
|
||||
vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\
|
||||
vc.log(tf.paragraphs[1].paragraphAttributes.justification);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]);
|
||||
let t = text_of(&s, id);
|
||||
let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect();
|
||||
assert_eq!(names, [None, Some("Centered".to_string()), None]);
|
||||
assert_eq!(t.para_at(1).space_before, 6.0);
|
||||
assert_eq!(t.para_at(2).space_before, 0.0);
|
||||
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';"));
|
||||
assert!(e.contains("Justification"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;"));
|
||||
assert!(e.contains("1296"), "{e}");
|
||||
}
|
||||
|
||||
/// A style's character attributes read `undefined` until set; setting one restyles the text in
|
||||
/// the style but not a value the text changed itself.
|
||||
#[test]
|
||||
fn style_attributes_redefine_the_text_in_the_style() {
|
||||
let (mut s, id) = doc_with("ab cd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var x = cs.add('X'), a = x.characterAttributes;\
|
||||
vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\
|
||||
a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\
|
||||
vc.log([a.size, a.autoLeading, a.underline]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]);
|
||||
assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]);
|
||||
// Turning auto leading off keeps the leading auto leading gave the style's size.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"),
|
||||
);
|
||||
assert_eq!(out, [json!([false, 288])]);
|
||||
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;"));
|
||||
assert!(e.contains("0.1 to 1296"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';"));
|
||||
assert!(e.contains("TextFont"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;"));
|
||||
assert!(e.contains("not available yet"), "{e}");
|
||||
}
|
||||
|
||||
/// A range lists each style its text uses once, in order, with the Normal style for unstyled
|
||||
/// text, and its lists cannot add or remove styles.
|
||||
#[test]
|
||||
fn a_range_lists_the_styles_its_text_uses() {
|
||||
let (mut s, _) = doc_with("aa bb cc\ndd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\
|
||||
ps.add('P').applyTo(tf.paragraphs[1]);\
|
||||
function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\
|
||||
vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\
|
||||
vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\
|
||||
vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\
|
||||
tf.textRange.characterStyles.parent.typename]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"]));
|
||||
assert_eq!(out[1], json!(["X"]));
|
||||
assert_eq!(out[2], json!([NORMAL_PARA, "P"]));
|
||||
assert_eq!(out[3], json!([NORMAL_PARA]));
|
||||
assert_eq!(out[4], json!([true, "X", "TextRange"]));
|
||||
for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another
|
||||
/// document, and a range whose text changed, with nothing changed.
|
||||
#[test]
|
||||
fn apply_to_refuses_bad_arguments_with_nothing_changed() {
|
||||
let (mut s, id) = doc_with("Hello");
|
||||
log(&mut s, &format!("{DOC} cs.add('X');"));
|
||||
let runs_before = runs(&s, id);
|
||||
for (src, says) in [
|
||||
("cs[1].applyTo(5);".to_string(), "TextRange"),
|
||||
("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"),
|
||||
("cs[1].applyTo(cs);".to_string(), "TextRange"),
|
||||
(format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"),
|
||||
(
|
||||
"var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(),
|
||||
"another document",
|
||||
),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(runs(&s, id), runs_before);
|
||||
}
|
||||
|
||||
/// A run names at most 4,096 styles; reading past that throws instead of growing without bound.
|
||||
#[test]
|
||||
fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B');\
|
||||
vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\
|
||||
var cs2 = app.activeDocument.characterStyles;\
|
||||
try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\
|
||||
vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);"
|
||||
),
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}");
|
||||
assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style");
|
||||
assert_eq!(out[2], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_names_at_most_4096_styles() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let mut d = (*s.active().unwrap().doc).clone();
|
||||
let defs: Vec<TextStyleDef> = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect();
|
||||
d.char_styles = defs.into();
|
||||
s.doc_mut().unwrap().doc = std::sync::Arc::new(d);
|
||||
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);"));
|
||||
assert_eq!(out, [json!(false), json!(4101)]);
|
||||
let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;"));
|
||||
assert!(e.contains("4096 styles"), "{e}");
|
||||
// `add` with every slot taken adds no style; with one slot left it adds the style.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"),
|
||||
);
|
||||
assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]);
|
||||
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);"));
|
||||
assert_eq!(out, [json!("New"), json!(4102)]);
|
||||
}
|
||||
|
||||
/// A script loads styles from a file only where it may read files; a file outside that is refused.
|
||||
#[test]
|
||||
fn a_script_loads_styles_only_from_a_file_it_may_read() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Other.vectorcraft");
|
||||
let mut other = Session::new();
|
||||
other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap();
|
||||
std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap();
|
||||
let p = path.to_string_lossy().replace('\\', "/");
|
||||
let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(e.contains("access denied"), "{e}");
|
||||
assert!(char_names(&s).is_empty());
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
//! Type in the script object model: `textFrames`, text ranges, their attributes and `textFonts`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Justify;
|
||||
|
||||
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 undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with point type holding `text`.
|
||||
fn doc_with(text: &str) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
(s, NodeId(id))
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_frames_add_point_area_and_path_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 100})).unwrap();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems;\
|
||||
var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\
|
||||
var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\
|
||||
var pt = d.textFrames.add(); pt.contents = 'Point';\
|
||||
var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\
|
||||
vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\
|
||||
vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\
|
||||
vc.log([d.textFrames[0].contents, d.textFrames[3].contents]); vc.log(d.textFrames[9] === undefined);\
|
||||
vc.log(at.orientation); vc.log(d.textFrames.parent.typename);",
|
||||
);
|
||||
assert_eq!(out[0], json!(4));
|
||||
assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"]));
|
||||
// Topmost first, as `pageItems` lists them: the newest type, then the area type on the rectangle.
|
||||
assert_eq!(
|
||||
out[2..],
|
||||
[json!("TextFrame"), json!(true), json!(["At", "Area"]), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]
|
||||
);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
// A path of another kind, or no path, is refused.
|
||||
assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem"));
|
||||
assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1]);").contains("anchor"));
|
||||
assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1, 2], 'up');").contains("TextOrientation"));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
// pathText takes its orientation fourth, after the start and end positions it does not take yet.
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 250}, {"x": 300, "y": 260}], "closed": false})).unwrap();
|
||||
let find = "var d = app.activeDocument, p = d.pageItems, q; for (var i = 0; i < p.length; i++) if (p[i].typename == 'PathItem') q = p[i];";
|
||||
assert!(failure(&mut s, &format!("{find} d.textFrames.pathText(q, 0.5);")).contains("not available yet"));
|
||||
let out = log(&mut s, &format!("{find} vc.log(d.textFrames.pathText(q, undefined, undefined, TextOrientation.VERTICAL).orientation);"));
|
||||
assert_eq!(out, vec![json!("TextOrientation.VERTICAL")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() {
|
||||
let (mut s, id) = doc_with("x");
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);");
|
||||
assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]);
|
||||
assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e");
|
||||
assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contents_takes_a_number_as_its_text() {
|
||||
let (mut s, id) = doc_with("x");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\
|
||||
t.textRange.characters[0].contents = 2.5; vc.log(t.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("7"), json!("2.5")]);
|
||||
assert_eq!(plain(&s, id), "2.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets_count_utf16_units_and_keep_surrogate_pairs_whole() {
|
||||
let (mut s, _) = doc_with("a\u{1F600}b cd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].textRange, c = r.characters;\
|
||||
vc.log([r.length, r.start, r.end, c.length]);\
|
||||
vc.log([c[1].start, c[1].length, c[2].start, c[2].contents]);\
|
||||
vc.log([r.words.length, r.words[1].contents, r.words[0].characters.length]);\
|
||||
vc.log(app.activeDocument.textFrames[0].contents.length === r.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([7, 0, 7, 6]), json!([1, 2, 3, "b"]), json!([2, "cd", 3]), json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_character_of_each_word_grows_in_one_undo_step() {
|
||||
let (mut s, id) = doc_with("one two");
|
||||
let before = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
"var text = app.activeDocument.textFrames[0].textRange;\
|
||||
for (var j = 0; j < text.words.length; j++) { var f = text.words[j].characters[0]; f.size = f.size * 1.5; }",
|
||||
);
|
||||
assert_eq!(sizes(&s, id), vec![("o".into(), 18.0), ("ne ".into(), 12.0), ("t".into(), 18.0), ("wo".into(), 12.0)]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_follow_model_edits_and_go_stale_after_other_edits() {
|
||||
let (mut s, id) = doc_with("one two three");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], w = t.words, second = w[1], third = w[2];\
|
||||
w[0].contents = 'first'; vc.log([second.contents, second.start, third.contents]);\
|
||||
second.contents = ''; vc.log([second.length, third.contents, t.contents]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["two", 6, "three"]), json!([0, "three", "first three"])]);
|
||||
let source = format!("var r = app.activeDocument.textFrames[0].words[0]; vc.run('text.setText', {{id: {}, text: 'other'}}); r.contents;", id.0);
|
||||
let e = failure(&mut s, &source);
|
||||
assert!(e.contains("Stale text range"), "{e}");
|
||||
let e = failure(&mut s, "var t = app.activeDocument.textFrames[0], r = t.textRange; t.remove(); r.contents;");
|
||||
assert!(e.contains("Stale text range"), "{e}");
|
||||
// A change reversed before the range is read leaves the text the range knew.
|
||||
let (mut s, id) = doc_with("one two");
|
||||
let source = format!(
|
||||
"var r = app.activeDocument.textFrames[0].words[1]; vc.run('text.setText', {{id: {0}, text: 'other'}});\
|
||||
vc.run('text.setText', {{id: {0}, text: 'one two'}}); vc.log([r.contents, r.start]);",
|
||||
id.0
|
||||
);
|
||||
assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() {
|
||||
let (mut s, _) = doc_with("one two");
|
||||
let path = std::env::temp_dir().join(format!("vc-text-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.words[1];\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
var now = app.activeDocument.textFrames[0];\
|
||||
vc.log(now.contents); try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\
|
||||
vc.log(now.words[1].contents);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(out[0], json!("one two"), "the reverted file holds the same text");
|
||||
assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert_eq!(out[2], json!("two"), "a range made after the revert reads the reverted text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_and_its_ranges_held_across_file_revert_go_stale() {
|
||||
let (mut s, _) = doc_with("one two");
|
||||
let path = std::env::temp_dir().join(format!("vc-text-revert-held-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words;\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
try { vc.log(t.contents); } catch (e) { vc.log(e.message); }\
|
||||
try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\
|
||||
try { vc.log(w.length); } catch (e) { vc.log(e.message); }\
|
||||
var now = app.activeDocument.textFrames[0], r2 = now.textRange;\
|
||||
vc.log(r2.contents); r2.contents = 'three'; vc.log(now.contents);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale page item")), "{out:?}");
|
||||
assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert_eq!(out[3], json!("one two"), "a range made after the revert reads the reverted text");
|
||||
assert_eq!(out[4], json!("three"), "a frame found after the revert can be edited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_an_edit_covers_holds_the_edits_new_text() {
|
||||
let (mut s, _) = doc_with("abc");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], first = t.characters[0], r = t.characters[1];\
|
||||
t.characters[2].contents = 'ZZ'; vc.log([first.contents, r.contents]);\
|
||||
t.contents = 'XY'; vc.log([r.contents, r.start, r.length, first.contents]);",
|
||||
);
|
||||
// A range that ends where an edit starts keeps its end; one inside the edit takes the new text.
|
||||
assert_eq!(out, vec![json!(["a", "b"]), json!(["XY", 0, 2, "XY"])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_attribute_values_are_refused_without_a_change() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let before = undo_steps(&s);
|
||||
for (src, want) in [
|
||||
("r.size = 0;", "size must be from 0.1"),
|
||||
("r.size = 'big';", "size must be a finite number"),
|
||||
("r.size = NaN;", "not a finite number"),
|
||||
("r.leading = 0;", "leading must be from 0.1"),
|
||||
("r.characterAttributes.tracking = 1e9;", "tracking"),
|
||||
("r.underline = 1;", "underline must be true or false"),
|
||||
("r.textFont = 'Arial';", "textFont must be a TextFont"),
|
||||
("r.paragraphAttributes.justification = 'LEFT';", "Justification value"),
|
||||
("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"),
|
||||
("r.length = -1;", "length must be a whole number from 0 to 3"),
|
||||
("r.length = 1.5;", "length must be a whole number from 0 to 3"),
|
||||
("r.length = 4;", "length must be a whole number from 0 to 3"),
|
||||
("r.length = 'two';", "length must be a finite number"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}"));
|
||||
assert!(e.contains(want), "{src}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(sizes(&s, id), vec![("abc".into(), 12.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_the_value_a_range_has_records_no_undo_step() {
|
||||
let (mut s, _) = doc_with("abc");
|
||||
let before = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.textRange; r.size = r.size; r.underline = false;\
|
||||
t.contents = t.contents; r.paragraphAttributes.leftIndent = 0; r.characters[0].characterAttributes.size = 12;",
|
||||
);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = r.leading; vc.log([r.autoLeading, r.leading]);");
|
||||
assert_eq!(out, vec![json!([false, 14.4])]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
// A fixed leading set to its own value is still no change.
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = 14.4; vc.log(r.autoLeading);");
|
||||
assert_eq!(out, vec![json!(false)]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_attributes_set_the_paragraphs_a_range_touches() {
|
||||
let (mut s, _) = doc_with("first\nsecond");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], p = t.paragraphs;\
|
||||
vc.log([p.length, p[0].contents, p[1].contents]);\
|
||||
p[1].paragraphAttributes.justification = Justification.CENTER; p[1].paragraphAttributes.leftIndent = 9;\
|
||||
vc.log([p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\
|
||||
vc.log([p[0].paragraphAttributes.leftIndent, p[1].paragraphAttributes.leftIndent, p[1].getParagraphLength()]);",
|
||||
);
|
||||
assert_eq!(out[0], json!([2, "first\r", "second"]));
|
||||
assert_eq!(out[1], json!(["Justification.LEFT", "Justification.CENTER"]));
|
||||
assert_eq!(out[2], json!([0, 9, 6]));
|
||||
// A paragraph whose range ends after its break sets only itself.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\
|
||||
p[0].paragraphAttributes.spaceAfter = 4;\
|
||||
vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\
|
||||
vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]);
|
||||
// The empty paragraph after a final break belongs only to an empty range at the end.
|
||||
let (mut s, id) = doc_with("a\n");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], p = t.paragraphs; p[0].paragraphAttributes.spaceAfter = 4;\
|
||||
vc.log([p.length, p[0].paragraphs.length, p[0].paragraphAttributes.spaceAfter]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([1, 1, 4])]);
|
||||
let after: Vec<f64> = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (0..2).map(|i| t.para_at(i).space_after).collect(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(after, vec![4.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() {
|
||||
let (mut s, id) = doc_with("first\nsecond");
|
||||
s.execute("text.setFormat", &json!({"id": id.0, "start": 6, "end": 6, "autoLeading": 200})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.textFrames[0].paragraphs; vc.log([p[0].leading, p[1].leading, p[1].characters[0].leading]);\
|
||||
p[1].autoLeading = false; vc.log([p[0].autoLeading, p[1].autoLeading, p[1].leading]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([14.4, 24, 24]), json!([true, false, 24])]);
|
||||
let leadings: Vec<(String, Option<f64>)> = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading)).collect(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(leadings, vec![("first\n".into(), None), ("second".into(), Some(24.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() {
|
||||
let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}');
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c));
|
||||
if !covers(from) || covers(to) {
|
||||
return; // Installed fonts of these names cover other characters.
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap();
|
||||
let pick = format!("var r = app.activeDocument.textFrames[0].textRange, f = app.textFonts.getByName('{to} Regular');");
|
||||
let e = failure(&mut s, &format!("{pick} r.textFont = f;"));
|
||||
assert!(e.contains("textFont: the font has no glyph for 1 character, which keeps its font"), "{e}");
|
||||
// Characters the font can draw take it without an error.
|
||||
let out = log(&mut s, &format!("{pick} r.characters[0].textFont = f; vc.log(r.characters[0].textFont.family);"));
|
||||
assert_eq!(out, vec![json!(to)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_auto_leading_off_keeps_each_characters_leading() {
|
||||
let (mut s, id) = doc_with("ab\ncd");
|
||||
s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 200})).unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "size": 24})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.autoLeading = false; vc.log(r.autoLeading);");
|
||||
assert_eq!(out, vec![json!(false)]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
let leadings: Vec<(String, Option<i64>)> = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading.map(|l| (l * 1000.0).round() as i64))).collect(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
let want = [("a", 14_400), ("b", 28_800), ("\n", 14_400), ("cd", 24_000)];
|
||||
assert_eq!(leadings, want.iter().map(|(t, l)| (t.to_string(), Some(*l))).collect::<Vec<_>>());
|
||||
// Paragraphs and runs with the same leading take one command.
|
||||
let (mut s, _) = doc_with("one\ntwo\nthree");
|
||||
let r = run(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;").unwrap();
|
||||
let calls: Vec<(Value, Value)> = r["slowestCommands"].as_array().unwrap().iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect();
|
||||
assert_eq!(calls, vec![(json!("text.setRangeStyle"), json!(1))]);
|
||||
// Auto leading that a fixed leading cannot hold is refused before anything changes.
|
||||
let (mut s, id) = doc_with("ab\ncd");
|
||||
s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 0})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;");
|
||||
assert!(e.contains("autoLeading cannot be turned off"), "{e}");
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_alignment_replaces_auto_alignment() {
|
||||
let justify = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.para_at(0).justify,
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
for (text, reads) in [("abc", "Justification.LEFT"), ("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "Justification.RIGHT")] {
|
||||
let (mut s, id) = doc_with(text);
|
||||
assert_eq!(justify(&s, id), Justify::Auto);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var a = app.activeDocument.textFrames[0].textRange.paragraphAttributes; vc.log(a.justification);\
|
||||
a.justification = Justification.LEFT; vc.log(a.justification);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(reads), json!("Justification.LEFT")], "{text}");
|
||||
assert_eq!(justify(&s, id), Justify::Left, "{text}");
|
||||
assert_eq!(undo_steps(&s), before + 1, "{text}");
|
||||
}
|
||||
// Each paragraph on Auto reads by its own text.
|
||||
let (mut s, _) = doc_with("abc\n\u{5e9}\u{5dc}\u{5d5}\u{5dd}\nd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.textFrames[0].paragraphs; var j = function (i) { return p[i].paragraphAttributes.justification; }; vc.log([j(0), j(1), j(2)]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Justification.LEFT", "Justification.RIGHT", "Justification.LEFT"])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_range_has_no_parent() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let source = format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'x'}}); r.parent;", id.0);
|
||||
let e = failure(&mut s, &source);
|
||||
assert!(e.contains("Stale text range"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_range_and_its_collections_have_no_typename() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let source = format!(
|
||||
"var r = app.activeDocument.textFrames[0].textRange, all = [r, r.characters, r.words, r.paragraphs, r.characterAttributes, r.paragraphAttributes];\
|
||||
var names = []; for (var i = 0; i < all.length; i++) names.push(all[i].typename); vc.log(names);\
|
||||
vc.run('text.setText', {{id: {}, text: 'other'}}); var m = [];\
|
||||
for (var i = 0; i < all.length; i++) {{ try {{ m.push(all[i].typename); }} catch (e) {{ m.push(e.message); }} }} vc.log(m);",
|
||||
id.0
|
||||
);
|
||||
let out = log(&mut s, &source);
|
||||
assert_eq!(out[0], json!(["TextRange", "Characters", "Words", "Paragraphs", "CharacterAttributes", "ParagraphAttributes"]));
|
||||
assert_eq!(out[1], json!(vec!["Stale text range"; 6]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_not_built_yet_throw_after_the_stale_check() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames[0].lines;");
|
||||
assert!(e.contains("TextFrame.lines is not available yet"), "{e}");
|
||||
let e = failure(&mut s, "var t = app.activeDocument.textFrames[0]; t.remove(); t.lines;");
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.lines;");
|
||||
assert!(e.contains("TextRange.lines is not available yet"), "{e}");
|
||||
for member in ["r.lines", "r.start = 1"] {
|
||||
let source =
|
||||
format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'other'}}); {member};", id.0);
|
||||
let e = failure(&mut s, &source);
|
||||
assert!(e.contains("Stale text range"), "{member}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_fonts_list_and_assign_fonts_by_name() {
|
||||
// The last font in the menu that draws "abc", so Missing Glyph Protection keeps no character.
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let listed: Vec<(String, String)> = db.menu_family_list().iter().flat_map(|f| db.styles(f).into_iter().map(move |st| (f.clone(), st))).collect();
|
||||
let covers = |(f, st): &&(String, String)| db.face(f, st).is_some_and(|face| "abc".chars().all(|c| face.covers(c)));
|
||||
let Some((pos, (family, style))) = listed.iter().enumerate().rev().find(|(_, fs)| covers(fs)) else {
|
||||
return; // No installed font draws "abc".
|
||||
};
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var f = app.textFonts, m = '';\
|
||||
try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\
|
||||
vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\
|
||||
vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!([family, style]), json!(true), json!(true), json!(true)]);
|
||||
let set = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone()),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(&set, &(family.clone(), style.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() {
|
||||
let (mut s, id) = doc_with("hello world");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\
|
||||
vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\
|
||||
w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\
|
||||
t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]);
|
||||
assert_eq!(plain(&s, id), "Jello world");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
/// A length that ends inside a surrogate pair moves the range's end out to the end of the character.
|
||||
#[test]
|
||||
fn a_length_ending_inside_a_surrogate_pair_keeps_the_character_whole() {
|
||||
let (mut s, _) = doc_with("a\u{1F600}b");
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.length = 2; vc.log([r.length, r.end, r.contents]);");
|
||||
assert_eq!(out, vec![json!([3, 3, "a\u{1F600}"])]);
|
||||
}
|
||||
|
||||
/// `textFrames.removeAll()` deletes nothing when type is on a locked artboard.
|
||||
#[test]
|
||||
fn remove_all_type_refuses_type_on_a_locked_artboard() {
|
||||
let (mut s, id) = doc_with("kept");
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}");
|
||||
assert!(s.active().unwrap().doc.node(id).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_of_text_add_words_characters_and_paragraphs() {
|
||||
let cases = [
|
||||
("t.words.add('x')", "hello world", "hello world x", "x"),
|
||||
("t.words.addBefore('x')", "hello world", "x hello world", "x"),
|
||||
("t.words[0].words.add('x')", "hello world", "hello x world", "x"),
|
||||
("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"),
|
||||
("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"),
|
||||
("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"),
|
||||
("t.words.add('x')", "hello world ", "hello world x ", "x"),
|
||||
("t.words.add('x')", "", "x", "x"),
|
||||
("t.words.add(7)", "a", "a 7", "7"),
|
||||
("t.characters.add('!')", "hi", "hi!", "!"),
|
||||
("t.characters[0].characters.add('x')", "hi", "hxi", "x"),
|
||||
("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"),
|
||||
("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"),
|
||||
("t.paragraphs.addBefore('top')", "one", "top\none", "top"),
|
||||
];
|
||||
for (call, text, after, added) in cases {
|
||||
let (mut s, id) = doc_with(text);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);"));
|
||||
assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}");
|
||||
assert_eq!(plain(&s, id), after, "{call} on {text:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}");
|
||||
}
|
||||
// Empty contents add nothing; bad arguments throw before anything changes.
|
||||
let (mut s, id) = doc_with("ab");
|
||||
s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
// `textFrames` lists the topmost first, so the newer "other" is [0].
|
||||
let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);");
|
||||
assert_eq!(out, vec![json!([0, 5])]);
|
||||
for (call, want) in [
|
||||
("t.words.add(null)", "contents must be a string or a number"),
|
||||
("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"),
|
||||
("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"),
|
||||
("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"),
|
||||
("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};"));
|
||||
assert!(e.contains(want), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(plain(&s, id), "ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_fonts_find_a_bundled_face_by_its_postscript_name() {
|
||||
let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else {
|
||||
return; // Built without the bundled fonts.
|
||||
};
|
||||
let ps = face.postscript_name();
|
||||
let (mut s, _) = doc_with("abc");
|
||||
let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);"));
|
||||
assert_eq!(out, vec![json!([face.family, face.style, ps])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() {
|
||||
let (mut s, id) = doc_with("first\nsecond\nthird");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\
|
||||
vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\
|
||||
t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]);
|
||||
let justify: Vec<Justify> = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(justify, vec![Justify::Center; 3]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';");
|
||||
assert!(e.contains("Justification value"), "{e}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_outline_and_conversions_return_the_new_objects() {
|
||||
let (mut s, id) = doc_with("Hi");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], m = '';\
|
||||
try { t.convertAreaObjectToPointObject(); } catch (e) { m = e.message; } vc.log(m);\
|
||||
var a = t.convertPointObjectToAreaObject(); vc.log(a.kind);\
|
||||
var p = a.convertAreaObjectToPointObject(); vc.log(p.kind); vc.log(p.contents);\
|
||||
var g = p.createOutline(); vc.log(g.typename); vc.log(app.activeDocument.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out[0], json!("the text frame is not area type"));
|
||||
assert_eq!(out[1..], [json!("TextType.AREATEXT"), json!("TextType.POINTTEXT"), json!("Hi"), json!("GroupItem"), json!(0)]);
|
||||
assert!(s.active().unwrap().doc.node(id).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlining_type_with_nothing_to_outline_gives_null() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let out =
|
||||
log(&mut s, "var d = app.activeDocument, t = d.textFrames.add(); var g = t.createOutline(); vc.log([g === null, d.textFrames.length]);");
|
||||
assert_eq!(out, vec![json!([true, 0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_made_with_a_large_id_is_the_new_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// The second frame's id, 2^53 + 1, is not exact as a number.
|
||||
let big = 1u64 << 53;
|
||||
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, a = d.textFrames.add(), b = d.textFrames.pointText([5, 5]); b.contents = 'second';\
|
||||
vc.log([a === b, a.contents, b.createOutline().typename]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([false, "", "GroupItem"])]);
|
||||
assert_eq!(plain(&s, NodeId(big)), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_members_refuse_objects_of_other_classes() {
|
||||
let (mut s, _) = doc_with("abc");
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);");
|
||||
assert!(e.contains("this is not a TextFrame"), "{e}");
|
||||
let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);");
|
||||
assert!(e.contains("this is not a TextRange"), "{e}");
|
||||
let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['TextFont', 0, 0]; app.activeDocument.textFrames[0].textRange.textFont = f;");
|
||||
assert!(e.contains("not plain data"), "{e}");
|
||||
// A font from an earlier run of a named engine is stale.
|
||||
run(&mut s, "#targetengine keepfont\nvar held = app.textFonts[0];").unwrap();
|
||||
for member in ["held.family", "held.parent"] {
|
||||
let e = failure(&mut s, &format!("#targetengine keepfont\n{member};"));
|
||||
assert!(e.contains("Stale text font"), "{member}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`,
|
||||
//! `document.stories`, and the text of a story of several frames.
|
||||
|
||||
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 undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn new_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Area type `width` × `height` at `x` holding `text`.
|
||||
fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId {
|
||||
let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn threads(s: &Session) -> Vec<Vec<NodeId>> {
|
||||
s.active().unwrap().doc.text_threads.clone()
|
||||
}
|
||||
|
||||
/// The text of every frame of the document's threads, in thread order.
|
||||
fn story(s: &Session, frames: &[NodeId]) -> String {
|
||||
frames.iter().map(|f| plain(s, *f)).collect()
|
||||
}
|
||||
|
||||
/// Two area frames threaded into one story whose text starts in the first, one line high, and
|
||||
/// flows on into the second.
|
||||
fn threaded(text: &str) -> (Session, NodeId, NodeId) {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 90.0, 18.0, text);
|
||||
let b = area(&mut s, 150.0, 200.0, 200.0, "");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
const STORY: &str = "alpha beta gamma\ndelta \u{1F600}";
|
||||
|
||||
#[test]
|
||||
fn stories_list_one_story_for_each_thread_and_each_frame_in_none() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
area(&mut s, 400.0, 120.0, 40.0, "Alone");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, st = d.stories[1];\
|
||||
vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\
|
||||
vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\
|
||||
vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\
|
||||
vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\
|
||||
d.textFrames.add(); vc.log(d.stories.length);\
|
||||
vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\
|
||||
vc.log(d.textFrames[1].story.textFrames[0].contents);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(2),
|
||||
json!("Story"),
|
||||
json!(2),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!("Alone"),
|
||||
json!(1),
|
||||
json!(3),
|
||||
json!("Document"),
|
||||
json!("Document"),
|
||||
json!("Stories"),
|
||||
json!("Alone")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_counts_utf16_units_across_its_frames() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}");
|
||||
assert_eq!(first.clone() + &second, STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, r = st.textRange;\
|
||||
vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\
|
||||
vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\
|
||||
vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\
|
||||
vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\
|
||||
vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(25),
|
||||
json!(25),
|
||||
json!("alpha beta gamma\rdelta \u{1F600}"),
|
||||
json!("TextRange"),
|
||||
json!(24),
|
||||
json!(5),
|
||||
json!(2),
|
||||
json!("alpha beta gamma\r"),
|
||||
json!("\u{1F600}"),
|
||||
json!(23),
|
||||
json!(8),
|
||||
json!(25),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The members a long story's range does not have yet throw that they are not available, and
|
||||
/// first that a range that went stale is stale.
|
||||
#[test]
|
||||
fn a_story_range_names_the_members_it_does_not_have_yet() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange;\
|
||||
try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!("TextRange.characterAttributes is not available yet"),
|
||||
json!("TextRange.size is not available yet"),
|
||||
json!("Story.lines is not available yet")
|
||||
]
|
||||
);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
/// Ranges of one story read from different frames keep their places through each other's edits.
|
||||
#[test]
|
||||
fn story_ranges_read_from_different_frames_follow_each_others_edits() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\
|
||||
x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\
|
||||
vc.log(t[1].story.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]);
|
||||
}
|
||||
|
||||
/// A story range that an edit covers holds the edit's new text, as a frame's range does.
|
||||
#[test]
|
||||
fn a_story_range_an_edit_covers_holds_the_new_text() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\
|
||||
st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_edit_across_frames_reflows_in_one_undo_step() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\
|
||||
var p = st.paragraphs[0], tail = st.paragraphs[1];\
|
||||
p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\
|
||||
try { frame.contents; } catch (e) { vc.log(String(e.message)); }\
|
||||
st.words[2].remove(); vc.log(st.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]);
|
||||
assert_eq!(story(&s, &[a, b]), "X\ndelta ");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(story(&s, &[a, b]), STORY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_is_stale_after_another_change_to_the_story() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.words[1];\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
var st = app.activeDocument.textFrames[0].story;\
|
||||
vc.log(st.textFrames.length); vc.log(st.textRange.contents);\
|
||||
try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(st.words[1].contents);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(out[0], json!(2), "the reverted file keeps the thread");
|
||||
assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "First story.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Second.");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\
|
||||
t[2].nextFrame = t[1];",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]);
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
assert_eq!(story(&s, &[a, b]), "First story.Second.");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]);
|
||||
// previousFrame links the other way.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into()));
|
||||
log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];");
|
||||
assert_eq!(threads(&s), vec![vec![b, a]]);
|
||||
assert_eq!(story(&s, &[b, a]), "Second.First story.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_breaks_the_link_and_each_frame_keeps_its_text() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\
|
||||
t[1].nextFrame = null;",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(1), json!(null)]);
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), (first, second));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_and_path_text_thread_the_new_frame_to_a_base_frame() {
|
||||
let mut s = new_doc();
|
||||
let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it.");
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\
|
||||
var after = d.textFrames.areaText(p[2], undefined, base);\
|
||||
var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\
|
||||
var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\
|
||||
vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]);
|
||||
let t = threads(&s);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_base_frame_is_refused_before_a_frame_is_made() {
|
||||
let mut s = new_doc();
|
||||
s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
let count = |s: &Session| s.active().unwrap().doc.node_count();
|
||||
let (n, before) = (count(&s), undo_steps(&s));
|
||||
let d = "var d = app.activeDocument, p = d.pageItems;";
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix"));
|
||||
assert_eq!((count(&s), undo_steps(&s)), (n, before));
|
||||
}
|
||||
|
||||
/// A base frame given with a path inside a compound path is refused before the path is turned
|
||||
/// into type, so a script that catches the error finds the path as it was.
|
||||
#[test]
|
||||
fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() {
|
||||
let mut s = new_doc();
|
||||
area(&mut s, 10.0, 120.0, 60.0, "Base.");
|
||||
let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = null;\
|
||||
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\
|
||||
try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds
|
||||
/// now, to check that a refused change left it alone.
|
||||
fn three() -> (Session, [NodeId; 4]) {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let c = area(&mut s, 400.0, 120.0, 40.0, "Third");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
(s, [a, b, c, p])
|
||||
}
|
||||
|
||||
fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec<Vec<NodeId>>, Vec<String>, usize)) {
|
||||
assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::<Vec<_>>(), undo_steps(s)), *before);
|
||||
}
|
||||
|
||||
fn state(s: &Session, ids: &[NodeId]) -> (Vec<Vec<NodeId>>, Vec<String>, usize) {
|
||||
(threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_to_the_frame_itself_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];");
|
||||
assert!(m.contains("nextFrame") && m.contains("itself"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_that_makes_a_loop_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_into_the_middle_of_a_story_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];");
|
||||
assert!(m.contains("already has a previous frame"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];");
|
||||
assert!(m.contains("already has a next frame"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_and_other_values_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;");
|
||||
assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;");
|
||||
assert!(m.contains("TextFrame or null"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_or_locked_frame_in_either_story_stops_a_link() {
|
||||
let (mut s, ids) = three();
|
||||
log(&mut s, "app.activeDocument.textFrames[2].locked = true;");
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
// A script that catches the error goes on, and the links stay as they were.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; try { t[2].nextFrame = t[1]; } catch (e) { vc.log([e.name, /hidden or locked/.test(e.message)]); }\
|
||||
vc.log(t[2].nextFrame === null);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Error", true]), json!(true)]);
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// Reading a story whose text is larger than what one run may pass to and from the host stops
|
||||
/// the run when the story's text is joined.
|
||||
#[test]
|
||||
fn joining_a_storys_text_counts_toward_the_runs_data_limit() {
|
||||
let text = "word ".repeat(40_000);
|
||||
let (mut s, _, _) = threaded(&text);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(100_000)));
|
||||
let r = run(&mut s, "vc.log(app.activeDocument.stories[0].length);");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("the run read a 200 KB story within a 100 KB limit: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("more data to and from commands"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_of_another_document_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
area(&mut s, 10.0, 100.0, 40.0, "Elsewhere");
|
||||
s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap();
|
||||
let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];");
|
||||
assert!(m.contains("different documents"), "{m}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.documents[0], p = d.pageItems[0];\
|
||||
try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_frame_makes_its_story_and_links_stale() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;");
|
||||
assert!(m.contains("Stale page item"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;");
|
||||
assert!(m.contains("Stale text range"), "{m}");
|
||||
// A story read from a frame that stays follows it when its link is broken.
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);");
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stories_refuse_bad_keys_and_huge_numbers() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!(true)]);
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError"));
|
||||
log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_story_walks_to_its_end_and_refuses_a_loop() {
|
||||
let mut s = new_doc();
|
||||
let ids: Vec<NodeId> = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect();
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![ids.clone()]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(120), json!(120), json!(1)]);
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame
|
||||
/// once, so a walk along `nextFrame` ends.
|
||||
#[test]
|
||||
fn a_thread_listing_a_frame_twice_is_walked_once() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]];
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2), json!(1)]);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
assert!(threads(&s).is_empty());
|
||||
}
|
||||
|
||||
/// When a frame is listed in two threads, a story read from a frame of the second thread reads
|
||||
/// that thread's text, not the text of the story read before it from a shared frame.
|
||||
#[test]
|
||||
fn stories_of_threads_that_share_a_frame_keep_their_own_text() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
let c = area(&mut s, 300.0, 120.0, 60.0, "Three!");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]];
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);");
|
||||
let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count());
|
||||
assert_ne!(ab, bc);
|
||||
assert_eq!(out, vec![json!(ab), json!(bc)]);
|
||||
}
|
||||
|
||||
/// A story and its range keep the exact id of the frame they were read from, also past 2^53.
|
||||
#[test]
|
||||
fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() {
|
||||
let mut s = new_doc();
|
||||
// The second frame's id, 2^53 + 1, is not exact as a number.
|
||||
let big = 1u64 << 53;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
assert_eq!((a.0, b.0), (big, big + 1));
|
||||
s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\
|
||||
st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);",
|
||||
);
|
||||
// The whole story flows into the first frame, so the second is empty once the link is broken.
|
||||
assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
for bad in [
|
||||
json!({"id": a.0, "side": "up", "neighbor": b.0}),
|
||||
json!({"id": a.0, "side": "next"}),
|
||||
json!({"id": a.0, "side": "next", "neighbor": 999_999}),
|
||||
] {
|
||||
assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
}
|
||||
|
||||
/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered
|
||||
/// paragraphs count from 1, also when that story keeps two frames.
|
||||
#[test]
|
||||
fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() {
|
||||
let mut s = new_doc();
|
||||
let items = (1..=12).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")];
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "list": "number"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let numbers = |s: &Session, id: NodeId| {
|
||||
let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(!t.first_para_continues, "every frame starts a paragraph");
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let first = numbers(&s, ids[0]);
|
||||
assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items");
|
||||
assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1."));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]}));
|
||||
let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat();
|
||||
let expected: Vec<String> = (1..=later.len()).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!(later, expected, "the later story counts from 1");
|
||||
assert_eq!(numbers(&s, ids[0]), first);
|
||||
}
|
||||
@@ -217,4 +217,178 @@ fn set_option_sets_the_direction_and_refuses_bad_values() {
|
||||
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
|
||||
}
|
||||
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
|
||||
// `join` starts off and `tangentSnap` on; both take only true or false.
|
||||
assert_eq!(
|
||||
(s.tool_options_of("threePointArc")["join"].clone(), s.tool_options_of("threePointArc")["tangentSnap"].clone()),
|
||||
(json!(false), json!(true))
|
||||
);
|
||||
let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"join": true, "tangentSnap": false}})).unwrap();
|
||||
assert_eq!((set["join"].clone(), set["tangentSnap"].clone()), (json!(true), json!(false)));
|
||||
for key in ["join", "tangentSnap"] {
|
||||
let e = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "key": key, "value": 1})).unwrap_err();
|
||||
assert_eq!(e, format!("tool `threePointArc`: `{key}` must be true or false"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An open path drawn from SVG path data, selected.
|
||||
fn open_path(s: &mut Session, d: &str) -> NodeId {
|
||||
id_of(&s.execute("path.create", &json!({ "d": d })).unwrap())
|
||||
}
|
||||
|
||||
/// The anchors of the first subpath of `id`, and whether it is closed.
|
||||
fn anchors(s: &Session, id: NodeId) -> (Vec<Point>, bool) {
|
||||
let n = node(s, id);
|
||||
let sp = &n.path_data().unwrap().subpaths[0];
|
||||
(sp.anchors.iter().map(|a| a.p).collect(), sp.closed)
|
||||
}
|
||||
|
||||
/// With `join`, an arc starting on the last anchor of an open path is added to that path: the path
|
||||
/// keeps its id and direction and now ends where the arc ends, the anchor where they meet is not
|
||||
/// doubled, and it is one undo step. An arc ending on a path's first anchor is added before it.
|
||||
#[test]
|
||||
fn join_adds_the_arc_to_the_open_path_it_starts_on() {
|
||||
let mut s = session();
|
||||
let id = open_path(&mut s, "M0 100 L100 100");
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
|
||||
assert_eq!((id_of(&out), out["joined"].clone(), out["radius"].as_f64()), (id, json!(true), Some(40.0)), "{out}");
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count));
|
||||
let (pts, closed) = anchors(&s, id);
|
||||
assert!(!closed);
|
||||
assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(0.0, 100.0)), Some(Point::new(180.0, 100.0))), "{pts:?}");
|
||||
assert_eq!(pts.iter().filter(|p| **p == Point::new(100.0, 100.0)).count(), 1, "{pts:?}");
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 60.0), Point::new(50.0, 100.0)]) < 1e-9);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(anchors(&s, id).0, [Point::new(0.0, 100.0), Point::new(100.0, 100.0)]);
|
||||
// The arc ends on the first anchor of a path running right: the path still runs right, from
|
||||
// the arc's start.
|
||||
let id = open_path(&mut s, "M300 100 L400 100");
|
||||
let out = s.execute(C, &json!({"start": [220, 100], "end": [300, 100], "toward": [220, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), id);
|
||||
let (pts, _) = anchors(&s, id);
|
||||
assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(220.0, 100.0)), Some(Point::new(400.0, 100.0))), "{pts:?}");
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(260.0, 60.0)]) < 1e-9);
|
||||
}
|
||||
|
||||
/// With both ends on ends of two open paths, the arc joins them into one path in one undo step;
|
||||
/// with both ends on the two ends of one open path, the path closes.
|
||||
#[test]
|
||||
fn join_with_both_ends_on_open_paths_makes_one_path() {
|
||||
let mut s = session();
|
||||
let a = open_path(&mut s, "M0 100 L100 100");
|
||||
let b = open_path(&mut s, "M180 100 L280 100");
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), a);
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count - 1));
|
||||
assert!(s.doc().unwrap().doc.node(b).is_none());
|
||||
let (pts, closed) = anchors(&s, a);
|
||||
assert!(!closed);
|
||||
let ends = (pts.first().copied(), pts.last().copied());
|
||||
assert!(
|
||||
ends == (Some(Point::new(0.0, 100.0)), Some(Point::new(280.0, 100.0)))
|
||||
|| ends == (Some(Point::new(280.0, 100.0)), Some(Point::new(0.0, 100.0))),
|
||||
"{pts:?}"
|
||||
);
|
||||
for p in [Point::new(100.0, 100.0), Point::new(180.0, 100.0)] {
|
||||
assert_eq!(pts.iter().filter(|q| **q == p).count(), 1, "{pts:?}");
|
||||
}
|
||||
assert!(farthest_from_path(&s, a, &[Point::new(140.0, 60.0), Point::new(230.0, 100.0)]) < 1e-9);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((object_count(&s), anchors(&s, b).0.len()), (count, 2));
|
||||
// One path's two ends: it closes.
|
||||
let id = open_path(&mut s, "M100 300 L180 300");
|
||||
let out = s.execute(C, &json!({"start": [180, 300], "end": [100, 300], "through": [140, 340], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), id);
|
||||
let (pts, closed) = anchors(&s, id);
|
||||
assert!(closed, "{pts:?}");
|
||||
assert_eq!(pts.iter().filter(|q| **q == Point::new(100.0, 300.0)).count(), 1, "{pts:?}");
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 340.0), Point::new(140.0, 300.0)]) < 1e-9);
|
||||
}
|
||||
|
||||
/// Of two open path ends at the arc's start, `join` takes the one in the selection, and with
|
||||
/// neither selected the one in front.
|
||||
#[test]
|
||||
fn join_prefers_the_selected_path_then_the_front_one() {
|
||||
let mut s = session();
|
||||
let back = open_path(&mut s, "M0 100 L100 100");
|
||||
let front = open_path(&mut s, "M100 200 L100 100");
|
||||
for (selected, want) in [(Some(back), back), (None, front)] {
|
||||
let ids: Vec<u64> = selected.iter().map(|id| id.0).collect();
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), want, "{selected:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// In isolation mode, a path outside the isolated group is left alone.
|
||||
s.execute("select.set", &json!({ "ids": [back.0] })).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({ "id": group })).unwrap();
|
||||
s.execute("select.set", &json!({ "ids": [] })).unwrap();
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [100, 20], "through": [60, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), back, "{out}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let out = s.execute(C, &json!({"start": [100, 200], "end": [180, 200], "through": [140, 160], "join": true})).unwrap();
|
||||
assert!(out.get("joined").is_none(), "{out}");
|
||||
assert_eq!(anchors(&s, front).0.len(), 2);
|
||||
}
|
||||
|
||||
/// Without `join`, away from open path ends, on a locked path, or on a closed path's anchor, the
|
||||
/// arc is a new path; a `join` that is not true or false is an error and draws nothing.
|
||||
#[test]
|
||||
fn join_leaves_paths_it_cannot_join_alone() {
|
||||
let mut s = session();
|
||||
let line = open_path(&mut s, "M0 100 L100 100");
|
||||
let rect = open_path(&mut s, "M200 200 L300 200 L300 300 Z");
|
||||
let arc = |s: &mut Session, start: [f64; 2], end: [f64; 2], via: [f64; 2], join: Value| {
|
||||
s.execute(C, &json!({"start": start, "end": end, "through": via, "join": join}))
|
||||
};
|
||||
for (start, end, via, join) in [
|
||||
([100.0, 100.0], [180.0, 100.0], [140.0, 60.0], json!(false)),
|
||||
([100.0, 120.0], [180.0, 120.0], [140.0, 80.0], json!(true)),
|
||||
([200.0, 200.0], [120.0, 200.0], [160.0, 160.0], json!(true)),
|
||||
] {
|
||||
let count = object_count(&s);
|
||||
let out = arc(&mut s, start, end, via, join.clone()).unwrap();
|
||||
assert!(out.get("joined").is_none() && id_of(&out) != line && id_of(&out) != rect, "{join}: {out}");
|
||||
assert_eq!(object_count(&s), count + 1);
|
||||
}
|
||||
assert_eq!(anchors(&s, line).0.len(), 2);
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
// On the line's other end, where none of the arcs above ends.
|
||||
let out = arc(&mut s, [0.0, 100.0], [0.0, 180.0], [40.0, 140.0], json!(true)).unwrap();
|
||||
assert!(out.get("joined").is_none(), "{out}");
|
||||
assert_eq!(anchors(&s, line).0.len(), 2);
|
||||
let count = object_count(&s);
|
||||
let e = arc(&mut s, [100.0, 300.0], [180.0, 300.0], [140.0, 260.0], json!("yes")).unwrap_err().to_string();
|
||||
assert!(e.contains("`join` must be true or false"), "{e}");
|
||||
assert_eq!(object_count(&s), count);
|
||||
}
|
||||
|
||||
/// With the tool's `join` option on, clicks near an open path's end place the arc's end on it and
|
||||
/// the arc joins the path; with it off the arc is a path of its own, and J while the ends are
|
||||
/// placed switches it on.
|
||||
#[test]
|
||||
fn the_tool_joins_the_arc_to_the_path_end_it_starts_near() {
|
||||
let mut s = session();
|
||||
let id = open_path(&mut s, "M0 100 L100 100");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.select_tool("threePointArc", view()).unwrap();
|
||||
let count = object_count(&s);
|
||||
for p in [(100.0, 100.0), (180.0, 100.0), (140.0, 60.0)] {
|
||||
click(&mut s, p.0, p.1);
|
||||
}
|
||||
assert_eq!((object_count(&s), anchors(&s, id).0.len()), (count + 1, 2), "off: a path of its own");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// J after the first click, near the path's end, switches `join` on.
|
||||
click(&mut s, 99.0, 100.5);
|
||||
s.tool_key(ToolKey::Letter('j'), Mods::default(), view()).unwrap();
|
||||
click(&mut s, 180.0, 100.0);
|
||||
click(&mut s, 140.0, 60.0);
|
||||
assert_eq!(object_count(&s), count);
|
||||
let (pts, _) = anchors(&s, id);
|
||||
assert_eq!((pts.len() > 2, pts.last().copied()), (true, Some(Point::new(180.0, 100.0))), "{pts:?}");
|
||||
assert_eq!(s.tool_options_of("threePointArc")["join"], json!(true), "J keeps the option switched");
|
||||
}
|
||||
@@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
|
||||
("object.cropImage", json!({})),
|
||||
("imageTrace.make", json!({})),
|
||||
("object.mesh.create", json!({})),
|
||||
// Vector art has no pixels to put between the corners.
|
||||
(
|
||||
"file.place",
|
||||
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
|
||||
json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg' width='9' height='9'><rect width='9' height='9'/></svg>")}),
|
||||
),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
|
||||
@@ -630,6 +630,7 @@ impl Session {
|
||||
freeform_point: self.selected_freeform_point(),
|
||||
raster_sample: self.prefs.eyedropper.sample_size,
|
||||
preview_bounds: self.prefs.use_preview_bounds,
|
||||
scale_strokes: self.prefs.scale_strokes,
|
||||
glyph_bounds: self.prefs.type_glyph_bounds,
|
||||
preview_memo: Some(&self.preview_memo),
|
||||
unit,
|
||||
|
||||
@@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
|
||||
/// behind the selection, given back, answers the same ratio.
|
||||
#[test]
|
||||
fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() {
|
||||
let _g = settings();
|
||||
let before = cms::active_settings();
|
||||
let _g = restored_settings();
|
||||
let mut s = session();
|
||||
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
|
||||
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"}));
|
||||
@@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space
|
||||
exec(&mut s, "paint.setFill", json!({"color": "#808080"}));
|
||||
let below = s.execute("color.contrast", &json!({}));
|
||||
let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok());
|
||||
cms::set_active(&before).unwrap();
|
||||
let given = given.unwrap();
|
||||
assert_eq!(given["against"], "#806040", "{given}");
|
||||
let (below, again) = (below.unwrap(), again.unwrap());
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
|
||||
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
|
||||
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
|
||||
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor
|
||||
//! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed),
|
||||
//! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed),
|
||||
@@ -1171,6 +1172,58 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any
|
||||
/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite
|
||||
/// font's `W` of any shape, and the `ToUnicode` map of object 5.
|
||||
fn arb_width_font() -> impl Strategy<Value = String> {
|
||||
(
|
||||
prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]),
|
||||
prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]),
|
||||
prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]),
|
||||
prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12),
|
||||
prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10),
|
||||
prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]),
|
||||
any::<bool>(),
|
||||
)
|
||||
.prop_map(|(subtype, encoding, first, widths, w, name, mapped)| {
|
||||
let map = if mapped { "/ToUnicode 5 0 R" } else { "" };
|
||||
format!(
|
||||
"<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \
|
||||
/DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>",
|
||||
widths.join(" "),
|
||||
w.join(" ")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read
|
||||
/// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that
|
||||
/// draw themselves.
|
||||
#[test]
|
||||
fn pdf_font_widths_never_panic(
|
||||
fonts in prop::collection::vec(arb_width_font(), 1..4),
|
||||
cmap in prop::collection::vec(prop::sample::select(vec![
|
||||
"begincmap", "1 begincodespacerange", "<0000> <FFFF>", "<00> <FF>", "endcodespacerange", "2 beginbfchar", "<0001> <0041>",
|
||||
"<0002> <D800>", "<41> <FFFD>", "1 beginbfrange", "<0000> <FFFF> <0000>", "<FFFF> <0000> <0041>", "<0001> <0003> [<0041> <0042>]",
|
||||
"endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar",
|
||||
]), 0..12),
|
||||
) {
|
||||
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
|
||||
let map = cmap.join("\n");
|
||||
let form = format!(
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream",
|
||||
fonts[0]
|
||||
);
|
||||
let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()];
|
||||
let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more);
|
||||
let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths()));
|
||||
prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a
|
||||
/// broken `#` escape, a number with a stray `-`).
|
||||
fn arb_dict_value() -> impl Strategy<Value = &'static str> {
|
||||
|
||||
@@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
|
||||
getIsFileOpen redraw selection selection= toString typename",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \
|
||||
undo unloadAction unloadAction=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
@@ -105,10 +106,10 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
|
||||
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
|
||||
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \
|
||||
typename views width",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -152,6 +153,116 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
(
|
||||
"",
|
||||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||||
ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \
|
||||
TextFrames TextOrientation TextRange TextType Words",
|
||||
),
|
||||
("TextFrames.", "prototype"),
|
||||
("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"),
|
||||
("TextFrame.", "prototype"),
|
||||
(
|
||||
"TextFrame.prototype.",
|
||||
"anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \
|
||||
contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \
|
||||
insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \
|
||||
opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \
|
||||
rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \
|
||||
textSelection= words",
|
||||
),
|
||||
("TextRange.", "prototype"),
|
||||
(
|
||||
"TextRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \
|
||||
characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \
|
||||
duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \
|
||||
getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \
|
||||
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
|
||||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \
|
||||
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
|
||||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
|
||||
verticalScale= words",
|
||||
),
|
||||
("Characters.", "prototype"),
|
||||
("Characters.prototype.", "add addBefore constructor length parent typename"),
|
||||
("Words.", "prototype"),
|
||||
("Words.prototype.", "add addBefore constructor length parent typename"),
|
||||
("Paragraphs.", "prototype"),
|
||||
("Paragraphs.prototype.", "add addBefore constructor length parent typename"),
|
||||
("CharacterAttributes.", "prototype"),
|
||||
(
|
||||
"CharacterAttributes.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||||
underline= verticalScale verticalScale=",
|
||||
),
|
||||
("ParagraphAttributes.", "prototype"),
|
||||
(
|
||||
"ParagraphAttributes.prototype.",
|
||||
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
|
||||
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
|
||||
),
|
||||
("CharacterStyles.", "prototype"),
|
||||
("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("CharacterStyle.", "prototype"),
|
||||
("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"),
|
||||
("CharacterStyleAttributes.", "prototype"),
|
||||
(
|
||||
"CharacterStyleAttributes.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||||
underline= verticalScale verticalScale=",
|
||||
),
|
||||
("ParagraphStyles.", "prototype"),
|
||||
("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("ParagraphStyle.", "prototype"),
|
||||
(
|
||||
"ParagraphStyle.prototype.",
|
||||
"applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename",
|
||||
),
|
||||
("ParagraphStyleAttributes.", "prototype"),
|
||||
(
|
||||
"ParagraphStyleAttributes.prototype.",
|
||||
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
|
||||
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
|
||||
),
|
||||
("TextFonts.", "prototype"),
|
||||
("TextFonts.prototype.", "constructor getByName index length parent typename"),
|
||||
("TextFont.", "prototype"),
|
||||
("TextFont.prototype.", "constructor family name parent style typename"),
|
||||
("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"),
|
||||
("TextOrientation.", "HORIZONTAL VERTICAL"),
|
||||
("TextType.", "AREATEXT PATHTEXT POINTTEXT"),
|
||||
("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"),
|
||||
("Stories.", "prototype"),
|
||||
("Stories.prototype.", "constructor index length parent typename"),
|
||||
("Story.", "prototype"),
|
||||
(
|
||||
"Story.prototype.",
|
||||
"characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \
|
||||
textRanges textRanges= textSelection textSelection= typename words",
|
||||
),
|
||||
("StoryRange.", "prototype"),
|
||||
(
|
||||
"StoryRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
|
||||
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
|
||||
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
|
||||
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
|
||||
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
|
||||
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
|
||||
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
|
||||
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
|
||||
underline underline= verticalScale verticalScale= words",
|
||||
),
|
||||
("StoryCharacters.", "prototype"),
|
||||
("StoryCharacters.prototype.", "constructor length parent typename"),
|
||||
("StoryWords.", "prototype"),
|
||||
("StoryWords.prototype.", "constructor length parent typename"),
|
||||
("StoryParagraphs.", "prototype"),
|
||||
("StoryParagraphs.prototype.", "constructor length parent typename"),
|
||||
// Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s
|
||||
// `visibilityVariable` is in its row above.
|
||||
("", "Dataset Datasets Variable VariableKind Variables"),
|
||||
@@ -173,7 +284,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types.
|
||||
const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
|
||||
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame";
|
||||
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem";
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Direct Selection picks several direction handles and drags them together (`path.moveHandles`).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_engine::{Session, ViewInfo};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, Point};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
@@ -191,3 +191,22 @@ fn move_handles_checks_its_params() {
|
||||
near(anchor(&s, id, 2).h_in, Point::new(305.0, 140.0));
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// A move by nothing that makes one path's smooth anchor a corner leaves a listed handle of a live
|
||||
/// rectangle, which needs no change, alone: the rectangle stays live.
|
||||
#[test]
|
||||
fn a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live() {
|
||||
let (mut s, id) = session();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 100, "height": 60})).unwrap();
|
||||
let rect = NodeId(rect["id"].as_u64().unwrap());
|
||||
let live = |s: &Session| matches!(&s.doc().unwrap().doc.node(rect).unwrap().kind, NodeKind::Path { live: Some(_), .. });
|
||||
assert!(live(&s), "shape.rectangle makes a live rectangle");
|
||||
let handles = json!([
|
||||
{"id": id.0, "anchor": 1, "which": "in"},
|
||||
{"id": id.0, "anchor": 1, "which": "out"},
|
||||
{"id": rect.0, "anchor": 0, "which": "out"}
|
||||
]);
|
||||
s.execute("path.moveHandles", &json!({"handles": handles, "dx": 0, "dy": 0})).unwrap();
|
||||
assert_eq!(anchor(&s, id, 1).kind, AnchorKind::Corner, "both handles listed make the smooth anchor a corner");
|
||||
assert!(live(&s), "the rectangle's listed handle needed no change, so the rectangle stays live");
|
||||
}
|
||||
@@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() {
|
||||
let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []}));
|
||||
assert_eq!(r["started"], false);
|
||||
assert_eq!(r["ok"], false);
|
||||
assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}");
|
||||
assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -634,7 +634,7 @@ fn font_name(st: &CharStyle) -> FontRecord {
|
||||
.collect();
|
||||
let name = face.postscript_name();
|
||||
// The reader takes the face of a name alone as `postscript_face` finds it.
|
||||
let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id());
|
||||
let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id());
|
||||
let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() };
|
||||
FontRecord { name, truetype: face.is_truetype(), design, version }
|
||||
}
|
||||
@@ -681,7 +681,7 @@ fn fixed(v: f32) -> i64 {
|
||||
fn font_kept(st: &CharStyle) -> bool {
|
||||
let record = font_name(st);
|
||||
let version = crate::import::record_version(&record.version);
|
||||
let (family, style, read) = crate::import::document_font(&record.name, version);
|
||||
let (family, style, read) = crate::import::document_font(&record.name, version, None);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id());
|
||||
family == st.font_family
|
||||
|
||||
@@ -564,7 +564,7 @@ impl Reader<'_> {
|
||||
st.cmap = cmap;
|
||||
// The installed face of that PostScript name, as type from a text document
|
||||
// takes it; else the name split into a family and style.
|
||||
let text = super::super::super::text::named_font(name, None);
|
||||
let text = super::super::super::text::named_font(name, None, None);
|
||||
let (family, style, version) = text.unwrap_or_else(|| {
|
||||
let (family, style) = super::super::super::text::family_style(name);
|
||||
(family, style, None)
|
||||
|
||||
@@ -236,6 +236,10 @@ pub struct Structure {
|
||||
/// placed in the document, or a color linked to its swatch at its tint (see
|
||||
/// `ate::Texts::with_paints`).
|
||||
pub text_paints: HashMap<String, Paint>,
|
||||
/// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies
|
||||
/// of a font apart for type whose font record keeps no version (see
|
||||
/// `ate::Texts::with_page_widths`): none until the importer sets them.
|
||||
pub page_widths: vectorcraft_pdf::PageWidths,
|
||||
/// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not.
|
||||
pub canvas_scale: f64,
|
||||
/// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its
|
||||
|
||||
@@ -1481,6 +1481,7 @@ impl<'a> Reader<'a> {
|
||||
},
|
||||
styles_read,
|
||||
text_paints,
|
||||
page_widths: Default::default(),
|
||||
canvas_scale: self.canvas_scale,
|
||||
symbols_own_size: self.symbols_own_size,
|
||||
xml_ids: self.xml_ids,
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
//! a layout has its point type's anchor at its frame's point. See [`Story::place`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -581,15 +582,20 @@ struct DocFont {
|
||||
/// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed
|
||||
/// copies of one font apart.
|
||||
version: Option<String>,
|
||||
/// [`Self::font`]'s answer, found once for every run that names the record.
|
||||
font: std::sync::OnceLock<Font>,
|
||||
/// The widths the file's page gives the font's characters, when it has them
|
||||
/// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record
|
||||
/// of the font shares them.
|
||||
widths: Option<Arc<vectorcraft_pdf::FontWidths>>,
|
||||
/// [`Self::font`]'s answer, found once for every run that names the record, and shared by the
|
||||
/// records of the same name and version, which give the same answer.
|
||||
font: Arc<std::sync::OnceLock<Font>>,
|
||||
}
|
||||
|
||||
impl DocFont {
|
||||
/// The font type set in this record's font takes: the installed copy it names
|
||||
/// ([`super::text::document_font`]).
|
||||
fn font(&self) -> &Font {
|
||||
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref()))
|
||||
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,6 +645,17 @@ impl Texts {
|
||||
Texts { paints, ..self }
|
||||
}
|
||||
|
||||
/// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`])
|
||||
/// gives the characters of its fonts, by each record's PostScript name: a record that keeps no
|
||||
/// version is set in the installed copy of its font that sets them at those widths
|
||||
/// ([`super::text::postscript_face`]).
|
||||
pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts {
|
||||
for f in &mut self.fonts {
|
||||
f.widths = page.widths(super::text::bare_name(&f.name)).cloned();
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The text document in the editing copy `data`, if it has one that can be read.
|
||||
pub(super) fn read(data: &[u8]) -> Option<Texts> {
|
||||
fn find(h: &[u8], n: &[u8], from: usize) -> Option<usize> {
|
||||
@@ -666,6 +683,8 @@ impl Texts {
|
||||
return None;
|
||||
}
|
||||
let doc = names::numbered(read(&bytes)?);
|
||||
// Records of one name and version share their answer.
|
||||
let mut answers: HashMap<(String, Option<String>), Arc<std::sync::OnceLock<Font>>> = HashMap::new();
|
||||
let fonts = doc
|
||||
.get("0")?
|
||||
.get("1")?
|
||||
@@ -675,11 +694,10 @@ impl Texts {
|
||||
.map(|f| {
|
||||
let record = f.get("0").and_then(|f| f.get("0"));
|
||||
let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str);
|
||||
DocFont {
|
||||
name: text("0").unwrap_or_default().to_string(),
|
||||
version: text("5").and_then(record_version).map(str::to_string),
|
||||
font: std::sync::OnceLock::new(),
|
||||
}
|
||||
let name = text("0").unwrap_or_default().to_string();
|
||||
let version = text("5").and_then(record_version).map(str::to_string);
|
||||
let font = answers.entry((name.clone(), version.clone())).or_default().clone();
|
||||
DocFont { name, version, widths: None, font }
|
||||
})
|
||||
.collect();
|
||||
let main = doc.get("1")?;
|
||||
@@ -1653,6 +1671,40 @@ fn art_scale(to_doc: Affine) -> f64 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The records of a text document's font list that name one font share the widths the file's
|
||||
/// page gives it and the face they resolve to, however many there are: 20,000 records of a font
|
||||
/// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record
|
||||
/// of another version is resolved apart.
|
||||
#[test]
|
||||
fn records_of_one_font_share_its_page_widths_and_answer() {
|
||||
let n = 20_000;
|
||||
let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>";
|
||||
let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n");
|
||||
let data =
|
||||
format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes()));
|
||||
let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n16 beginbfrange\n");
|
||||
for hi in 1..=16u32 {
|
||||
cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n"));
|
||||
}
|
||||
cmap.push_str("endbfrange\nendcmap\n");
|
||||
let extra = vectorcraft_testkit::pdf::first_extra(1);
|
||||
let font = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \
|
||||
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>"
|
||||
);
|
||||
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
|
||||
let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
|
||||
let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths();
|
||||
let shared = widths.widths("Sharetest-Regular").unwrap();
|
||||
assert_eq!(shared.len(), 4096);
|
||||
let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths);
|
||||
assert_eq!(texts.fonts.len(), n + 1);
|
||||
assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared))));
|
||||
let first = &texts.fonts[0].font;
|
||||
assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first)));
|
||||
assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_paragraphs_swap_left_and_right_alignment() {
|
||||
let texts = Texts {
|
||||
|
||||
@@ -178,17 +178,25 @@ impl ReadText {
|
||||
self.frames.get_or_insert_with(|| ai::text_frames(data))
|
||||
}
|
||||
|
||||
/// The text document of `data` ([`Texts::read`]), if it has one that can be read.
|
||||
fn texts(&mut self, data: &[u8]) -> Option<&Texts> {
|
||||
/// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths
|
||||
/// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given
|
||||
/// when it is first read, before any of its fonts is found: each is found once, with the widths
|
||||
/// it has then. Every check and build of one open passes the same widths.
|
||||
fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
|
||||
self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref()
|
||||
}
|
||||
|
||||
/// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]).
|
||||
fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
|
||||
fn texts_with(
|
||||
&mut self,
|
||||
data: &[u8],
|
||||
paints: std::collections::HashMap<String, vectorcraft_color::Paint>,
|
||||
page_widths: &vectorcraft_pdf::PageWidths,
|
||||
) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints));
|
||||
self.texts.insert(texts).as_ref()
|
||||
let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths)));
|
||||
self.texts.insert(read.map(|t| t.with_paints(paints))).as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo
|
||||
for info in &mut infos {
|
||||
info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone())));
|
||||
}
|
||||
let Some(texts) = text.texts(data) else { return false };
|
||||
let Some(texts) = text.texts(data, &structure.page_widths) else { return false };
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
.iter()
|
||||
@@ -338,6 +346,7 @@ pub(super) fn build_weighing(
|
||||
envelopes_drawn,
|
||||
styles_read,
|
||||
text_paints,
|
||||
page_widths,
|
||||
canvas_scale,
|
||||
symbols_own_size,
|
||||
xml_ids,
|
||||
@@ -498,7 +507,7 @@ pub(super) fn build_weighing(
|
||||
// The page's type that needs no text object of the layers: the layers' own legacy text, or
|
||||
// placed files that show it.
|
||||
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
|
||||
let texts = text.texts_with(data, text_paints);
|
||||
let texts = text.texts_with(data, text_paints, &page_widths);
|
||||
// Each story is read once, however many text objects name it.
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
|
||||
@@ -149,7 +149,7 @@ pub fn layered_ai_from(
|
||||
all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part"));
|
||||
all
|
||||
};
|
||||
let AiLayers { data, structure, alone, mut text } = layers;
|
||||
let AiLayers { data, structure, alone, mut text, page_widths } = layers;
|
||||
let data = match data {
|
||||
Ok(data) => data,
|
||||
Err(why) => return (visible, unread(warnings, &why), false),
|
||||
@@ -189,10 +189,17 @@ pub fn layered_ai_from(
|
||||
add_notes(&mut all, read.notes());
|
||||
(visible, all, false)
|
||||
};
|
||||
// The layers read, with the widths the PDF part gives the characters of its fonts.
|
||||
let read = || {
|
||||
ai::read_over_page(&data, false, names).map(|mut structure| {
|
||||
structure.page_widths = page_widths.clone();
|
||||
structure
|
||||
})
|
||||
};
|
||||
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
|
||||
// envelopes of type the layers had.
|
||||
let (mut free, mut count) = (None, 0);
|
||||
let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| {
|
||||
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
|
||||
count = structure.warped_type.envelope_count();
|
||||
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
|
||||
});
|
||||
@@ -205,7 +212,7 @@ pub fn layered_ai_from(
|
||||
let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers));
|
||||
if !live
|
||||
&& let Some((mut done, notes)) = alone.and_then(|(pages, unit)| {
|
||||
let mut structure = ai::read_over_page(&data, false, names).ok()?;
|
||||
let mut structure = read().ok()?;
|
||||
// With none free, nothing needs settling again: every envelope keeps its drawn art.
|
||||
if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) {
|
||||
structure.warped_type.open_alone(free, count);
|
||||
@@ -244,9 +251,17 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
|
||||
/// reading it, when the file's text document makes all of its type and nothing in its layers needs
|
||||
/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the
|
||||
/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part
|
||||
/// is imported. `names`: the encoding of names that aren't UTF-8.
|
||||
pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names)
|
||||
/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the
|
||||
/// PDF part gives the characters of its fonts, which tell installed copies of a font apart
|
||||
/// ([`AiLayers::with_page_widths`]).
|
||||
pub fn ai_layers_alone(
|
||||
private: &[u8],
|
||||
pages: &[(f64, f64)],
|
||||
unit: f64,
|
||||
names: ai::NameEncoding,
|
||||
page_widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names, page_widths)
|
||||
}
|
||||
|
||||
/// [`ai_layers_alone`] of an editing copy already decoded (`decoded`, as [`decode_ai_private`]
|
||||
@@ -256,31 +271,33 @@ pub fn ai_layers_alone_decoded(
|
||||
pages: &[(f64, f64)],
|
||||
unit: f64,
|
||||
names: ai::NameEncoding,
|
||||
page_widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
let data = match decoded {
|
||||
Ok(data) => data,
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }),
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }),
|
||||
};
|
||||
if !has_layers(&data) {
|
||||
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() });
|
||||
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths });
|
||||
}
|
||||
// An image past the hard limits is read as an unread box, which the PDF part's art replaces.
|
||||
let structure = match ai::read_over_page(&data, false, names) {
|
||||
let mut structure = match ai::read_over_page(&data, false, names) {
|
||||
Ok(structure) => structure,
|
||||
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }),
|
||||
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }),
|
||||
};
|
||||
structure.page_widths = page_widths.clone();
|
||||
let mut text = Box::<ReadText>::default();
|
||||
// An envelope of type opens live only where the layers with it draw as the page, as the other
|
||||
// live envelopes do: the PDF part is imported to compare them with. Should none open live, the
|
||||
// layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]).
|
||||
if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() {
|
||||
let alone = Some((pages.to_vec(), unit));
|
||||
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text });
|
||||
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths });
|
||||
}
|
||||
match build_without_page(structure, &data, pages, unit, &mut text) {
|
||||
Ok(Ok((doc, notes))) => Ok((doc, notes)),
|
||||
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }),
|
||||
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }),
|
||||
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }),
|
||||
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,6 +314,8 @@ pub struct AiLayers {
|
||||
alone: Option<(Vec<(f64, f64)>, f64)>,
|
||||
/// The text objects' frames and the text document of the editing copy, as far as they were read.
|
||||
text: Box<ReadText>,
|
||||
/// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]).
|
||||
page_widths: vectorcraft_pdf::PageWidths,
|
||||
}
|
||||
|
||||
impl AiLayers {
|
||||
@@ -308,7 +327,20 @@ impl AiLayers {
|
||||
/// An editing copy already decoded (`decoded`, as [`decode_ai_private`] gives it, or why it
|
||||
/// can't be).
|
||||
pub fn decoded(decoded: Result<Vec<u8>, String>) -> Self {
|
||||
Self { data: decoded, structure: None, alone: None, text: Box::default() }
|
||||
Self { data: decoded, structure: None, alone: None, text: Box::default(), page_widths: Default::default() }
|
||||
}
|
||||
|
||||
/// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of
|
||||
/// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no
|
||||
/// version is set in the installed copy of its font that sets them at those widths, where
|
||||
/// several copies answer to its name. The layers read before take them too, and a text document
|
||||
/// read before is read again with them, since its fonts are found once, with the widths they had
|
||||
/// then.
|
||||
pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self {
|
||||
if let Some(Ok(structure)) = &mut self.structure {
|
||||
structure.page_widths = page_widths.clone();
|
||||
}
|
||||
Self { page_widths, text: Box::default(), ..self }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,17 +642,21 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) {
|
||||
/// Editing data written on a large canvas comes in at its declared scale: no page holds the size.
|
||||
/// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]).
|
||||
pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec<String>), String> {
|
||||
ai_alone_with(private, ai::NameEncoding::default())
|
||||
ai_alone_with(private, ai::NameEncoding::default(), Default::default())
|
||||
}
|
||||
|
||||
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`.
|
||||
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
ai_alone_decoded(&ai::decode_private(private)?, names)
|
||||
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the
|
||||
/// file's PDF part gives the characters of its fonts when it has one that holds the art
|
||||
/// ([`AiLayers::with_page_widths`]).
|
||||
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
|
||||
ai_alone_decoded(&ai::decode_private(private)?, names, page_widths)
|
||||
}
|
||||
|
||||
/// [`ai_alone_with`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives it).
|
||||
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
build_from(ai::read_in(data, true, names)?, data, None, Page::Artboard, false, false, 1.0)
|
||||
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
|
||||
let mut structure = ai::read_in(data, true, names)?;
|
||||
structure.page_widths = page_widths;
|
||||
build_from(structure, data, None, Page::Artboard, false, false, 1.0)
|
||||
}
|
||||
|
||||
/// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height)
|
||||
|
||||
@@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() {
|
||||
assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1");
|
||||
}
|
||||
|
||||
/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of
|
||||
/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em.
|
||||
fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
|
||||
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect();
|
||||
let font = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
|
||||
widths.join(" ")
|
||||
);
|
||||
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
|
||||
vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths()
|
||||
}
|
||||
|
||||
/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives
|
||||
/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths.
|
||||
fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let pairs: Vec<String> = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect();
|
||||
let cmap = format!(
|
||||
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n",
|
||||
pairs.len(),
|
||||
pairs.join("\n")
|
||||
);
|
||||
let w: Vec<String> = chars.iter().map(|c| width(*c).to_string()).collect();
|
||||
let extra = vectorcraft_testkit::pdf::first_extra(1);
|
||||
let font = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
|
||||
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>",
|
||||
w.join(" ")
|
||||
);
|
||||
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
|
||||
let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
|
||||
vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths()
|
||||
}
|
||||
|
||||
/// The advance of `c` in installed `face`, in thousandths of an em.
|
||||
fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 {
|
||||
face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em()
|
||||
}
|
||||
|
||||
/// The version of the face that type from the text document of a `.ai` whose font record is
|
||||
/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the
|
||||
/// widths its PDF part gives the characters of its fonts.
|
||||
fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String {
|
||||
let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1);
|
||||
let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") };
|
||||
let texts = text_of(&d.layers[0]);
|
||||
assert_eq!(texts.len(), 1, "{record}: {notes:?}");
|
||||
vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone()
|
||||
}
|
||||
|
||||
/// Two installed copies of one font can share its PostScript name, family and style, and differ
|
||||
/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no
|
||||
/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF
|
||||
/// part gives them, also when the record spells the name with other punctuation. Without those
|
||||
/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first
|
||||
/// loaded); a version the record keeps decides first. The widths of a simple font in
|
||||
/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart.
|
||||
#[test]
|
||||
fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() {
|
||||
install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]);
|
||||
let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular");
|
||||
let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone();
|
||||
let (old, new) = (copy("1.0"), copy("1.1"));
|
||||
assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths");
|
||||
let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c));
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0");
|
||||
// Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's.
|
||||
let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by);
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0");
|
||||
// A record whose name differs from the copies' in punctuation alone, as its PDF part's font.
|
||||
assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1");
|
||||
// Widths of another font, or no copy setting the characters at the PDF part's widths.
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0");
|
||||
// A version the record keeps picks the copy, and one that isn't installed gives the copy it gave.
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0");
|
||||
// The widths of a composite font.
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0");
|
||||
// A font installed once is set in that copy whatever the widths.
|
||||
install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]);
|
||||
assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0");
|
||||
// Of several copies that set the characters at the widths, the first in the order the faces
|
||||
// are found (the first loaded).
|
||||
install(&[
|
||||
(true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")),
|
||||
(false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")),
|
||||
(false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")),
|
||||
]);
|
||||
assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1");
|
||||
}
|
||||
|
||||
/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character
|
||||
/// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large
|
||||
/// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point
|
||||
@@ -6490,7 +6589,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
|
||||
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
// A PDF part the layers don't draw as.
|
||||
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names);
|
||||
assert!(read, "{notes:?}");
|
||||
@@ -6499,7 +6598,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
|
||||
assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}");
|
||||
assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}");
|
||||
// A PDF part that draws as those layers, with the drawn art: the envelope opens live.
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names);
|
||||
assert!(read, "{notes:?}");
|
||||
let (envelopes, loose) = envelopes_and_type(&d);
|
||||
@@ -6527,7 +6626,7 @@ fn layers_that_open_alone_read_their_text_once() {
|
||||
let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]);
|
||||
let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1)));
|
||||
let file = private(&native_with_text(&art, &doc));
|
||||
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok();
|
||||
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok();
|
||||
let (opened, texts, frames) = text_reads(false, open);
|
||||
let Some((d, notes)) = opened else { panic!("didn't open without the page") };
|
||||
assert_eq!((texts, frames), (1, 1), "{notes:?}");
|
||||
@@ -6546,7 +6645,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() {
|
||||
let file = private(&native_with_text(&art, "not a text document"));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = || {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names)
|
||||
};
|
||||
let (opened, texts, frames) = text_reads(false, open);
|
||||
@@ -6573,7 +6672,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() {
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// A PDF part the layers don't draw as: they open alone, after a build with the page and one without.
|
||||
@@ -6657,7 +6756,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr
|
||||
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names);
|
||||
assert!(read, "{notes:?}");
|
||||
let (envelopes, loose) = envelopes_and_type(&d);
|
||||
@@ -6751,7 +6850,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// The layers alone, with the envelope's drawn art: what the page draws.
|
||||
@@ -6794,7 +6893,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document, trust: bool| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names)
|
||||
};
|
||||
let (mut page, _, _) = open(pdf_part(80.0, 80.0), false);
|
||||
@@ -6833,7 +6932,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// The layers alone, with the drawn art of both envelopes, but the first's: the page draws
|
||||
|
||||
@@ -44,7 +44,7 @@ fn style_word(w: &str) -> String {
|
||||
|
||||
/// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy
|
||||
/// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`).
|
||||
fn bare_name(name: &str) -> &str {
|
||||
pub(super) fn bare_name(name: &str) -> &str {
|
||||
let name = match name.split_once('+') {
|
||||
Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest,
|
||||
_ => name,
|
||||
@@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str {
|
||||
}
|
||||
|
||||
/// The font of type that a text document's font record names: by `name`, its PostScript name, and
|
||||
/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that
|
||||
/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the
|
||||
/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
|
||||
/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the
|
||||
/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face
|
||||
/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`])
|
||||
/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
|
||||
/// Microsoft YaHei). → (family, style, version).
|
||||
///
|
||||
/// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family
|
||||
pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option<String>) {
|
||||
named_font(name, version).unwrap_or_else(|| {
|
||||
pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option<String>) {
|
||||
named_font(name, version, widths).unwrap_or_else(|| {
|
||||
let (family, style) = family_style(name);
|
||||
let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family);
|
||||
(family, style, None)
|
||||
@@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin
|
||||
}
|
||||
|
||||
/// The font of type set in the installed face of PostScript name `name` (a subset prefix and a
|
||||
/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and
|
||||
/// style, and its version when the family and style alone resolve to another installed copy of
|
||||
/// the font. A library can keep two copies under one family and style that differ in their
|
||||
/// PostScript names or their versions, and draw the same text at different widths. → (family,
|
||||
/// style, version); `None` when no installed face has the name.
|
||||
pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option<String>)> {
|
||||
let face = postscript_face(bare_name(name), version)?;
|
||||
/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths`
|
||||
/// ([`postscript_face`]): that face's own family and style, and its version when the family and
|
||||
/// style alone resolve to another installed copy of the font. A library can keep two copies under
|
||||
/// one family and style that differ in their PostScript names or their versions, and draw the same
|
||||
/// text at different widths. → (family, style, version); `None` when no installed face has the name.
|
||||
pub(crate) fn named_font(
|
||||
name: &str,
|
||||
version: Option<&str>,
|
||||
widths: Option<&vectorcraft_pdf::FontWidths>,
|
||||
) -> Option<(String, String, Option<String>)> {
|
||||
let face = postscript_face(bare_name(name), version, widths)?;
|
||||
// As the PDF import names a version: only one that the family and style don't resolve to.
|
||||
let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style);
|
||||
let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone());
|
||||
Some((face.family.clone(), face.style.clone(), version))
|
||||
}
|
||||
|
||||
/// How far an installed face's advance may be from the width a page gives a character, in
|
||||
/// thousandths of an em, for the face to set it at that width: files write widths rounded.
|
||||
const PAGE_WIDTH_SLACK: f64 = 1.0;
|
||||
|
||||
/// The most characters of a page's font [`sets_page_widths`] compares.
|
||||
const MAX_WIDTHS_COMPARED: usize = 512;
|
||||
|
||||
/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`])
|
||||
/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters
|
||||
/// in code-point order are compared; a character the face has no glyph for isn't set at its width.
|
||||
fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool {
|
||||
let k = 1000.0 / face.units_per_em();
|
||||
widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| {
|
||||
let gid = face.glyph_for(*c);
|
||||
gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK
|
||||
})
|
||||
}
|
||||
|
||||
/// The installed face of PostScript name `name` (without a subset prefix), among the installed
|
||||
/// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there
|
||||
/// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named
|
||||
/// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in
|
||||
/// `version` when it is installed, else the first. `None` when no installed face has the name.
|
||||
/// `version` when it is installed. Without a version, copies whose names, family and style are all
|
||||
/// one can still set the type at other widths: of those, the first that sets the characters of
|
||||
/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which
|
||||
/// compares the first 512 characters). Else the first. `None` when no installed face has the name.
|
||||
///
|
||||
/// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces
|
||||
pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option<Arc<vectorcraft_text::FontFace>> {
|
||||
pub(crate) fn postscript_face(
|
||||
name: &str,
|
||||
version: Option<&str>,
|
||||
widths: Option<&vectorcraft_pdf::FontWidths>,
|
||||
) -> Option<Arc<vectorcraft_text::FontFace>> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let found = db.find_postscript(name)?;
|
||||
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) {
|
||||
let widths = widths.filter(|_| version.is_none());
|
||||
let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w));
|
||||
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) {
|
||||
return Some(found);
|
||||
}
|
||||
let faces = db.postscript_faces(name);
|
||||
let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect();
|
||||
let pool = if named.is_empty() { faces } else { named };
|
||||
let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned());
|
||||
Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found))
|
||||
let by_widths = || pool.iter().find(|f| on_page(f)).cloned();
|
||||
Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found))
|
||||
}
|
||||
|
||||
/// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the
|
||||
@@ -620,7 +653,7 @@ impl Interp<'_> {
|
||||
}
|
||||
// The installed face of that PostScript name, as type from a text document takes it; else
|
||||
// the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei".
|
||||
let (font_family, font_style, font_version) = document_font(&name, None);
|
||||
let (font_family, font_style, font_version) = document_font(&name, None, None);
|
||||
let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() };
|
||||
let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() };
|
||||
let mut t = TextObject::point(Point::ZERO, text, style);
|
||||
|
||||
@@ -403,11 +403,32 @@ impl SubPath {
|
||||
/// Bend segment `seg` so its point at `t` moves by `dv`: both inner control points move by
|
||||
/// dv / 3t(1-t), since B(t) moves by 3t(1-t) times that. A smooth anchor stays smooth: its other
|
||||
/// handle turns with the moved one. False when there is no such segment.
|
||||
///
|
||||
/// A straight segment's handles lie on its anchors, so moving them as they are curls its ends
|
||||
/// round (#9225). It is bent as the same line with its handles at its thirds instead, so it
|
||||
/// bows evenly, the point at `t` still landing `dv` away.
|
||||
pub fn bend_segment(&mut self, seg: usize, t: f64, dv: kurbo::Vec2) -> bool {
|
||||
let n = self.anchors.len();
|
||||
if seg >= self.segment_count() || n == 0 {
|
||||
return false;
|
||||
}
|
||||
if dv == kurbo::Vec2::ZERO {
|
||||
return true;
|
||||
}
|
||||
let mut t = t;
|
||||
if self.segment_is_line(seg) {
|
||||
let c = self.segment(seg);
|
||||
let third = (c.p3 - c.p0) / 3.0;
|
||||
if let Some(a) = self.anchors.get_mut(seg % n) {
|
||||
a.set_handle(true, c.p0 + third, false);
|
||||
}
|
||||
if let Some(b) = self.anchors.get_mut((seg + 1) % n) {
|
||||
b.set_handle(false, c.p3 - third, false);
|
||||
}
|
||||
// With its handles on its anchors, the line is at t²(3 - 2t) of the way along at t; with
|
||||
// them at its thirds, that far along is where it is at that same parameter.
|
||||
t = t * t * (3.0 - 2.0 * t);
|
||||
}
|
||||
let v = dv / (3.0 * t * (1.0 - t));
|
||||
if let Some(a) = self.anchors.get_mut(seg % n) {
|
||||
a.set_handle(true, a.h_out + v, false);
|
||||
@@ -940,6 +961,28 @@ fn push_curve(cur: &mut Option<SubPath>, last: Point, c1: Point, c2: Point, p: P
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// #9225: a straight segment bent from its middle bows evenly: its handles leave from along the
|
||||
/// line, toward the middle, not straight out of its anchors, and the grabbed point follows.
|
||||
#[test]
|
||||
fn bending_a_straight_segment_pulls_its_handles_from_along_the_line() {
|
||||
for t in [0.5, 0.3, 0.1] {
|
||||
let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false);
|
||||
let grabbed = sp.segment(0).eval(t);
|
||||
let dv = kurbo::Vec2::new(0.0, 60.0);
|
||||
assert!(sp.bend_segment(0, t, dv));
|
||||
let (a, b) = (sp.anchors[0], sp.anchors[1]);
|
||||
assert!(a.h_out.x > a.p.x + 1.0 && b.h_in.x < b.p.x - 1.0, "t {t}: {a:?} {b:?}");
|
||||
let landed = sp.segment(0).nearest(grabbed + dv, 1e-9).distance_sq.sqrt();
|
||||
assert!(landed < 1e-6, "t {t}: the grabbed point is {landed} off the pointer");
|
||||
}
|
||||
// No move leaves it as it was, a smooth end's other handle included.
|
||||
let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false);
|
||||
sp.anchors[1].h_out = Point::new(300.0, 50.0);
|
||||
sp.anchors[1].kind = AnchorKind::Smooth;
|
||||
let before = sp.clone();
|
||||
assert!(sp.bend_segment(0, 0.5, kurbo::Vec2::ZERO));
|
||||
assert_eq!(sp.anchors, before.anchors);
|
||||
}
|
||||
use super::*;
|
||||
|
||||
/// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives,
|
||||
|
||||
@@ -614,8 +614,67 @@ pub struct Program {
|
||||
pub(crate) lines: crate::LineTable,
|
||||
/// It was read with [`crate::Options::es2015`].
|
||||
pub(crate) es2015: bool,
|
||||
/// What `super` and `new.target` may do at its top: nothing in a script, and in eval code
|
||||
/// what they may do in the code that calls a direct `eval` (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
/// The name an import takes from the module it names, or an export from a module it re-exports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportName {
|
||||
/// The export of this name (`default` for a default import).
|
||||
Name(String),
|
||||
/// The module's namespace object (`* as ns`).
|
||||
Namespace,
|
||||
}
|
||||
|
||||
/// A module a module imports or re-exports from: the specifier as written and where it stands.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleRequest {
|
||||
/// The specifier as text, with each unpaired surrogate written as U+FFFD.
|
||||
pub specifier: String,
|
||||
/// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16,
|
||||
/// ModuleRequests). It may hold an unpaired surrogate, which no host path can name.
|
||||
pub units: Vec<u16>,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImportEntry {
|
||||
/// The index of the module in [`ModuleInfo::requests`].
|
||||
pub request: usize,
|
||||
pub import: ImportName,
|
||||
/// The name bound in the importing module.
|
||||
pub local: Name,
|
||||
}
|
||||
|
||||
/// One name a module exports (ExportEntry).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ExportEntry {
|
||||
/// `export_name` is the module's own binding `local` (`*default*` for a default export of an
|
||||
/// expression or an anonymous function).
|
||||
Local { export_name: String, local: String, span: Span },
|
||||
/// `export_name` is the export `import` of the module `request` (`export { a as b } from`,
|
||||
/// `export * as ns from`, or an exported import).
|
||||
Indirect { export_name: String, request: usize, import: ImportName, span: Span },
|
||||
/// Every export of the module `request` but `default` (`export * from`).
|
||||
Star { request: usize, span: Span },
|
||||
}
|
||||
|
||||
/// What a module imports and exports, read by [`crate::parse_module`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ModuleInfo {
|
||||
/// The modules it names, each specifier once, in the order they first appear.
|
||||
pub requests: Vec<ModuleRequest>,
|
||||
pub imports: Vec<ImportEntry>,
|
||||
pub exports: Vec<ExportEntry>,
|
||||
}
|
||||
|
||||
/// The binding name of a default export that has no name of its own (ECMA-262 2015 section
|
||||
/// 15.2.3.5); no identifier can name it.
|
||||
pub const DEFAULT_BINDING: &str = "*default*";
|
||||
|
||||
impl Program {
|
||||
/// The line and column (both from 1, the column in UTF-16 code units) of a source offset.
|
||||
pub fn line_column(&self, offset: u32) -> (u32, u32) {
|
||||
|
||||
@@ -591,15 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
|
||||
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?))
|
||||
}
|
||||
|
||||
/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member.
|
||||
fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name),
|
||||
crate::symbol::PropKey::Sym(_) => Ok(false),
|
||||
}
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -618,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
|
||||
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?))
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
// ---- Function ----
|
||||
|
||||
@@ -15,12 +15,13 @@
|
||||
//! every buffer's bytes are checked against the heap before they are allocated. Every element
|
||||
//! a method visits takes a unit of fuel, and a sort's comparisons take one each.
|
||||
//!
|
||||
//! The language has no iterators yet, so constructing from an object reads an array or an object
|
||||
//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A
|
||||
//! constructor given a primitive string reads it as a length.
|
||||
//! Constructing from an object that is not a buffer or a typed array, and `%TypedArray%.from`,
|
||||
//! read a source with an `@@iterator` method through its iterator (a string by code point), and
|
||||
//! any other source as an array-like object, by index. `%TypedArray%.prototype[@@iterator]` is
|
||||
//! `values`. A constructor given a primitive string reads it as a length.
|
||||
|
||||
use super::collections::{for_each_item, getter, length_of, new_iter, new_proto};
|
||||
use super::{arg, array, data, method, native, require_callable, to_integer};
|
||||
use super::collections::{getter, length_of, new_iter, new_proto};
|
||||
use super::{arg, array, data, method, native, new_array, require_callable, to_integer};
|
||||
use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key};
|
||||
use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult};
|
||||
use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32};
|
||||
@@ -28,9 +29,6 @@ use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint3
|
||||
/// The longest buffer, in bytes.
|
||||
const MAX_BUFFER: u64 = u32::MAX as u64;
|
||||
|
||||
/// The bytes each item a method gathers before it writes them is charged.
|
||||
const ITEM_BYTES: usize = 16;
|
||||
|
||||
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
install_array_buffer(interp)?;
|
||||
install_data_view(interp)?;
|
||||
@@ -124,6 +122,11 @@ fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> {
|
||||
for (name, f, length) in methods {
|
||||
method(interp, proto, name, f, length)?;
|
||||
}
|
||||
// `%TypedArray%.prototype[@@iterator]` is `values` (section 22.2.3.30).
|
||||
if let Some(iterator) = interp.well_known(|w| &w.iterator) {
|
||||
let values = interp.get_from(proto, &key("values"), &Value::Object(proto))?;
|
||||
interp.define_sym(proto, iterator, crate::heap::Prop::Data { value: values, flags: HIDDEN })?;
|
||||
}
|
||||
// `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28).
|
||||
let array_proto = interp.intrinsics.array_proto;
|
||||
let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?;
|
||||
@@ -645,21 +648,59 @@ fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Ele
|
||||
}
|
||||
return Ok(Value::Object(ta));
|
||||
}
|
||||
let len = length_of(interp, o)?;
|
||||
let ta = new_typed(interp, elem, len)?;
|
||||
interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?;
|
||||
Ok(Value::Object(ta))
|
||||
// Any other object is read as TypedArrayFrom reads it (section 22.2.1.4).
|
||||
typed_array_from(interp, &first, None, |interp, len| new_typed(interp, elem, len))
|
||||
}
|
||||
|
||||
/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`,
|
||||
/// each converted with ToNumber.
|
||||
fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> {
|
||||
let Value::Object(o) = src else { return Ok(()) };
|
||||
/// TypedArrayFrom (section 22.2.2.1.1): a typed array with the values of `items`, made by `make`
|
||||
/// once their number is known, each value mapped with `map` (the function and its `this`) when
|
||||
/// one is given and converted with ToNumber. An `items` with an `@@iterator` method is read
|
||||
/// through its iterator to the end before the typed array is made. Any other value is read as
|
||||
/// an array-like object, each element read, mapped and written before the next is read.
|
||||
fn typed_array_from(
|
||||
interp: &mut Interp,
|
||||
items: &Value,
|
||||
map: Option<(&Value, &Value)>,
|
||||
make: impl FnOnce(&mut Interp, u64) -> JsResult<ObjId>,
|
||||
) -> JsResult<Value> {
|
||||
let using_iterator = match interp.well_known(|w| &w.iterator) {
|
||||
Some(iterator) => interp.get_value_sym(items, &iterator)?,
|
||||
None => Value::Undefined,
|
||||
};
|
||||
let src = if using_iterator.is_nullish() {
|
||||
interp.to_object(items)?
|
||||
} else {
|
||||
let rec = interp.get_iterator_with(items, &using_iterator)?;
|
||||
interp.rooted(&[Value::Object(rec)], |interp| {
|
||||
let list = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(list)], |interp| interp.append_values(rec, list))?;
|
||||
Ok(list)
|
||||
})?
|
||||
};
|
||||
let src_value = Value::Object(src);
|
||||
interp.rooted(std::slice::from_ref(&src_value), |interp| {
|
||||
let len = length_of(interp, src)?;
|
||||
let ta = make(interp, len)?;
|
||||
interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, src, len, map))?;
|
||||
Ok(Value::Object(ta))
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the elements `0` to `len - 1` of the object `src` to the typed array `ta`, each mapped
|
||||
/// with `map` when one is given and converted with ToNumber. Each element is read just before it
|
||||
/// is mapped and written.
|
||||
fn fill_from(interp: &mut Interp, ta: ObjId, src: ObjId, len: u64, map: Option<(&Value, &Value)>) -> JsResult<()> {
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
let src_value = Value::Object(src);
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = interp.get_from(*o, &super::key_of(i as f64), src)?;
|
||||
let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = match map {
|
||||
Some((f, this_arg)) => interp.call(f, this_arg, &[item, Value::Number(i as f64)])?,
|
||||
None => item,
|
||||
};
|
||||
let n = interp.to_number(&v)?;
|
||||
write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n);
|
||||
}
|
||||
@@ -741,54 +782,11 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe
|
||||
require_callable(interp, &map_fn, "the map function")?;
|
||||
}
|
||||
let this_arg = arg(args, 2);
|
||||
let source = arg(args, 0);
|
||||
if !matches!(source, Value::String(_)) {
|
||||
// An array-like source: each element is read, mapped and written before the next is read.
|
||||
let src = interp.to_object(&source)?;
|
||||
let src_value = Value::Object(src);
|
||||
let len = length_of(interp, src)?;
|
||||
let map = mapping.then_some((&map_fn, &this_arg));
|
||||
typed_array_from(interp, &arg(args, 0), map, |interp, len| {
|
||||
let elem = ctor_elem(interp, &this, "from")?;
|
||||
let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?;
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| {
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item };
|
||||
let n = interp.to_number(&v)?;
|
||||
write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n);
|
||||
}
|
||||
Ok(Value::Object(ta))
|
||||
});
|
||||
}
|
||||
// A string is read by code point first, as an iterable source is, and then mapped.
|
||||
let mark = interp.temp_roots.len();
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
let gathered = for_each_item(interp, &source, false, |interp, item| {
|
||||
held.add(interp, ITEM_BYTES)?;
|
||||
interp.temp_roots.push(item);
|
||||
Ok(())
|
||||
});
|
||||
let result = gathered.and_then(|()| {
|
||||
let items: Vec<Value> = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default();
|
||||
let elem = ctor_elem(interp, &this, "from")?;
|
||||
let ta = new_typed(interp, elem, items.len() as u64)?;
|
||||
interp.temp_roots.push(Value::Object(ta));
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item };
|
||||
let n = interp.to_number(&v)?;
|
||||
write(interp, &view, i, n);
|
||||
}
|
||||
Ok(Value::Object(ta))
|
||||
});
|
||||
interp.temp_roots.truncate(mark);
|
||||
drop(held);
|
||||
result
|
||||
new_typed(interp, elem, len)
|
||||
})
|
||||
}
|
||||
|
||||
/// `%TypedArray%.of(...items)` (section 22.2.2.2).
|
||||
|
||||
@@ -8,18 +8,20 @@
|
||||
//! entries hold their key weakly: the collector removes an entry once its key is reachable only
|
||||
//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed.
|
||||
//!
|
||||
//! The language has no iterators yet, so the constructors read their argument by index: an
|
||||
//! array or an object with a `length`, or a string by code point. Every entry added is checked
|
||||
//! against the heap limit before it is added, and every entry visited takes a unit of fuel.
|
||||
//! The constructors read their argument through its `@@iterator` method (GetIterator, section
|
||||
//! 7.4.1), and close the iterator when adding an entry throws (IteratorClose, section 7.4.6).
|
||||
//! `Map.prototype[@@iterator]` is `entries`, `Set.prototype[@@iterator]` is `values`, and the
|
||||
//! iterators inherit from `%IteratorPrototype%`. Every entry added is checked against the heap
|
||||
//! limit before it is added, and every entry visited takes a unit of fuel.
|
||||
|
||||
use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable};
|
||||
use super::{arg, constructor, create_at, method, native, new_array, require_callable};
|
||||
use crate::heap::{
|
||||
COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object,
|
||||
PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes,
|
||||
};
|
||||
use crate::interp::{Abrupt, Interp, JsResult};
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::value::{Str, Value};
|
||||
use crate::value::Value;
|
||||
|
||||
/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does
|
||||
/// to the globals.
|
||||
@@ -137,7 +139,14 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
getter(interp, set_proto, "get size", set_size)?;
|
||||
// `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8).
|
||||
let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?;
|
||||
interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
|
||||
interp.define(set_proto, key("keys"), Prop::Data { value: values.clone(), flags: crate::heap::HIDDEN })?;
|
||||
// `Map.prototype[@@iterator]` is `entries` and `Set.prototype[@@iterator]` is `values`
|
||||
// (sections 23.1.3.12 and 23.2.3.11).
|
||||
if let Some(iterator) = interp.well_known(|w| &w.iterator) {
|
||||
let entries = interp.get_from(map_proto, &key("entries"), &Value::Object(map_proto))?;
|
||||
interp.define_sym(map_proto, iterator.clone(), Prop::Data { value: entries, flags: crate::heap::HIDDEN })?;
|
||||
interp.define_sym(set_proto, iterator, Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
|
||||
}
|
||||
|
||||
let weak_map_proto = new_proto(interp, object_proto);
|
||||
interp.intrinsics.es2015.weak_map_proto = weak_map_proto;
|
||||
@@ -158,8 +167,12 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
method(interp, weak_set_proto, name, f, length)?;
|
||||
}
|
||||
|
||||
// The iterators' prototypes inherit from `%IteratorPrototype%` (sections 23.1.5.2, 23.2.5.2
|
||||
// and 22.1.5.2), whose `@@iterator` gives the iterator itself.
|
||||
let iterator_proto =
|
||||
interp.symbols.objects.and_then(|o| interp.heap.object(o.array_iterator_proto).and_then(|p| p.proto)).unwrap_or(object_proto);
|
||||
for source in [IterSource::Map, IterSource::Set, IterSource::Array] {
|
||||
let proto = new_proto(interp, object_proto);
|
||||
let proto = new_proto(interp, iterator_proto);
|
||||
let next: NativeFn = match source {
|
||||
IterSource::Map => map_iterator_next,
|
||||
IterSource::Set => set_iterator_next,
|
||||
@@ -209,56 +222,10 @@ pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult<u64> {
|
||||
Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 })
|
||||
}
|
||||
|
||||
/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`,
|
||||
/// or a string's code points. Any other value is a `TypeError`, and so is an object without a
|
||||
/// `length` when `need_length` is true. Each item takes a unit of fuel.
|
||||
pub(crate) fn for_each_item(
|
||||
interp: &mut Interp,
|
||||
list: &Value,
|
||||
need_length: bool,
|
||||
mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>,
|
||||
) -> JsResult<()> {
|
||||
match list {
|
||||
Value::Object(o) => {
|
||||
if need_length && !interp.has_property(*o, &key("length"))? {
|
||||
return Err(interp.type_error("the value is not an array, a string or an object with a length"));
|
||||
}
|
||||
let len = length_of(interp, *o)?;
|
||||
let mut i = 0u64;
|
||||
while i < len {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let item = interp.get_from(*o, &key_of(i as f64), list)?;
|
||||
f(interp, item)?;
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::String(s) => {
|
||||
let units = flat_charged(interp, s)?;
|
||||
let mut i = 0;
|
||||
while i < units.len() {
|
||||
interp.use_fuel()?;
|
||||
let width = match (units.get(i), units.get(i + 1)) {
|
||||
(Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let piece = units.get(i..i + width).unwrap_or_default().to_vec();
|
||||
let bytes = string_bytes(piece.len());
|
||||
interp.reserve_heap(bytes)?;
|
||||
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
|
||||
f(interp, Value::String(Str::from_units(piece)))?;
|
||||
i += width;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(interp.type_error("the value is not an array, a string or an object with a length")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the items of `list` to the new collection `target` with its `adder` method, as the
|
||||
/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item
|
||||
/// as a `[key, value]` entry.
|
||||
/// Adds the values the iterator of `list` gives to the new collection `target` with its `adder`
|
||||
/// method, as the constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs`
|
||||
/// reads each value as a `[key, value]` entry, which must be an object. When reading an entry
|
||||
/// or adding it throws, the iterator is closed.
|
||||
fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> {
|
||||
if list.is_nullish() {
|
||||
return Ok(());
|
||||
@@ -268,7 +235,8 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo
|
||||
let add = interp.get_from(target, &key(adder), &this)?;
|
||||
require_callable(interp, &add, adder)?;
|
||||
interp.rooted(std::slice::from_ref(&add), |interp| {
|
||||
for_each_item(interp, list, true, |interp, item| {
|
||||
let rec = interp.get_iterator(list)?;
|
||||
interp.for_each_value(rec, |interp, item| {
|
||||
if !pairs {
|
||||
return interp.call(&add, &this, &[item]).map(drop);
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _:
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
let k = interp.to_prop_key(&arg(args, 1))?;
|
||||
match interp.get_own_pk(o, &k)? {
|
||||
match interp.own_pk(o, &k)? {
|
||||
Some(p) => from_prop(interp, &p),
|
||||
None => Ok(Value::Undefined),
|
||||
}
|
||||
@@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
|
||||
let o = *o;
|
||||
for k in own_prop_keys(interp, o)? {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
@@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
let mut names = Vec::new();
|
||||
for k in interp.own_keys(o)? {
|
||||
interp.use_fuel()?;
|
||||
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
names.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,6 +453,10 @@ pub(crate) struct Code {
|
||||
/// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]),
|
||||
/// and it is not a constructor.
|
||||
pub(crate) generator: bool,
|
||||
/// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the
|
||||
/// rules of the function's body, of the code around an arrow function, or those eval code was
|
||||
/// read with (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors.
|
||||
|
||||
@@ -131,10 +131,11 @@ fn iterators_step_through_live_entries() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constructors_read_arrays_strings_and_array_likes() {
|
||||
fn constructors_read_arrays_and_strings() {
|
||||
truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'");
|
||||
truth("new Set('ab\u{1F600}b').size === 3");
|
||||
truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2");
|
||||
// An object without `@@iterator` is not iterable, whatever its `length` (section 23.2.1.1).
|
||||
throws("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'})", "TypeError");
|
||||
truth("new Map(null).size === 0 && new Set(undefined).size === 0");
|
||||
truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'");
|
||||
throws("Map()", "TypeError");
|
||||
@@ -146,7 +147,8 @@ fn constructors_read_arrays_strings_and_array_likes() {
|
||||
truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3");
|
||||
// `from` reads each element of an array-like source just before mapping it (section 22.2.2.1).
|
||||
truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'");
|
||||
truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'");
|
||||
// An iterable source is read to the end before the first value is mapped (section 22.2.2.1.1).
|
||||
truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,2'");
|
||||
truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'");
|
||||
throws("Map.prototype.get.call({}, 1)", "TypeError");
|
||||
throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError");
|
||||
@@ -158,6 +160,86 @@ fn constructors_read_arrays_strings_and_array_likes() {
|
||||
truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'");
|
||||
}
|
||||
|
||||
/// An iterable that gives `values` and counts the calls of its `return` method in `closed`.
|
||||
const CLOSING: &str = "var closed = 0; function closing(values) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \
|
||||
next: function () { return i < values.length ? { value: values[i++], done: false } : { done: true }; }, \
|
||||
return: function () { closed++; return {}; } }; }";
|
||||
|
||||
#[test]
|
||||
fn constructors_read_their_argument_through_its_iterator() {
|
||||
// GetIterator and IteratorStep (sections 23.1.1.1, 23.2.1.1, 23.3.1.1, 23.4.1.1 and 22.2.1.4).
|
||||
truth("function* g() { yield 1; yield 2; yield 1; } var s = new Set(g()); s.size === 2 && s.has(2)");
|
||||
truth("function* g() { yield ['a', 1]; yield ['b', 2]; } new Map(g()).get('b') === 2");
|
||||
truth("function* g() { yield 3; yield 4; } new Uint8Array(g()).join() === '3,4' && Int16Array.from(g()).join() === '3,4'");
|
||||
truth(&format!("{CLOSING} var s = new Set(closing(['x', 'y'])); s.size === 2 && s.has('y') && closed === 0"));
|
||||
truth(&format!(
|
||||
"{CLOSING} var k = {{}}; var w = new WeakMap(closing([[k, 5]])); var ws = new WeakSet(closing([k])); w.get(k) === 5 && ws.has(k)"
|
||||
));
|
||||
truth(&format!("{CLOSING} new Float64Array(closing([1.5, 2])).join() === '1.5,2' && closed === 0"));
|
||||
// A string is read by code point, as its iterator reads it.
|
||||
truth("new Set('\\uD83D\\uDE00\\uD83D\\uDE00').size === 1 && new Set('\\uD83D\\uDE00x').has('\\uD83D\\uDE00')");
|
||||
truth("var m = new Map([[1, 'a']]); Array.prototype.join.call(Uint8Array.from(m.keys())) === '1'");
|
||||
// An array is read through its `@@iterator`, not by index.
|
||||
truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; var s = new Set(a); s.has(9) && !s.has(1)");
|
||||
truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; new Uint8Array(a).join() === '9'");
|
||||
// An object without `@@iterator` is still read by index by the typed array constructors.
|
||||
truth("new Uint8Array({length: 2, 0: 1, 1: 2}).join() === '1,2'");
|
||||
throws("new Set({ [Symbol.iterator]: 1 })", "TypeError");
|
||||
throws("new Uint8Array({ [Symbol.iterator]: 1 })", "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_and_typed_arrays_are_iterable() {
|
||||
// Sections 23.1.3.12, 23.2.3.11 and 22.2.3.30.
|
||||
truth("Map.prototype[Symbol.iterator] === Map.prototype.entries && Set.prototype[Symbol.iterator] === Set.prototype.values");
|
||||
truth("var p = Object.getPrototypeOf(Int8Array.prototype); p[Symbol.iterator] === p.values");
|
||||
truth("var m = new Map([[1, 'a'], [2, 'b']]); var out = []; for (var e of m) out.push(e.join(':')); out.join() === '1:a,2:b'");
|
||||
truth("var out = []; for (var v of new Set([3, 4])) out.push(v); for (var v of new Int8Array([5])) out.push(v); out.join() === '3,4,5'");
|
||||
truth("var m = new Map([[1, 2]]); new Map(m).get(1) === 2 && new Set(new Set([7])).has(7) && new Set(new Uint8Array([8])).has(8)");
|
||||
// The iterators inherit `%IteratorPrototype%[@@iterator]` (sections 23.1.5.2, 23.2.5.2 and 22.1.5.2).
|
||||
truth("var it = new Map().keys(); it[Symbol.iterator]() === it && new Set([1]).values()[Symbol.iterator]().next().value === 1");
|
||||
truth("var it = new Int8Array([6]).values(); it[Symbol.iterator]() === it && [...new Set([1, 2]).keys()].join() === '1,2'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_entry_that_is_not_an_object_closes_the_iterator() {
|
||||
// Section 23.1.1.1, step 10.d.
|
||||
truth(&format!("{CLOSING} var caught; try {{ new Map(closing([1])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1"));
|
||||
truth(&format!(
|
||||
"{CLOSING} var caught; try {{ new WeakMap(closing(['k'])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_iterator_whose_next_throws_is_not_closed() {
|
||||
let src = "var closed = 0; var it = { [Symbol.iterator]: function () { return this; }, \
|
||||
next: function () { throw new RangeError('next'); }, return: function () { closed++; return {}; } };";
|
||||
for make in ["new Set(it)", "new Map(it)", "new WeakSet(it)", "new Uint8Array(it)", "Uint8Array.from(it)"] {
|
||||
truth(&format!(
|
||||
"{src} var caught; try {{ {make}; }} catch (e) {{ caught = e instanceof RangeError && e.message === 'next'; }} caught && closed === 0"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_throwing_adder_closes_the_iterator() {
|
||||
// IteratorClose (section 7.4.6) keeps the adder's exception, even when `return` throws too.
|
||||
for (ctor, adder) in [("Set", "add"), ("Map", "set"), ("WeakSet", "add"), ("WeakMap", "set")] {
|
||||
let src = format!(
|
||||
"{CLOSING} var o = {{}}; {ctor}.prototype.{adder} = function () {{ throw new RangeError('adder'); }}; var caught; \
|
||||
try {{ new {ctor}(closing([[o, 1], [o, 2]])); }} catch (e) {{ caught = e instanceof RangeError && e.message === 'adder'; }}"
|
||||
);
|
||||
truth(&format!("{src} caught && closed === 1"));
|
||||
let throwing = src.replace("closed++; return {};", "closed++; throw new TypeError('return');");
|
||||
truth(&format!("{throwing} caught && closed === 1"));
|
||||
}
|
||||
// A Map entry whose `0` getter throws closes the iterator as well.
|
||||
truth(&format!(
|
||||
"{CLOSING} var bad = {{ get 0() {{ throw new RangeError('key'); }} }}; var caught; \
|
||||
try {{ new Map(closing([bad])); }} catch (e) {{ caught = e.message === 'key'; }} caught && closed === 1"
|
||||
));
|
||||
}
|
||||
|
||||
// ---- WeakMap and WeakSet ----
|
||||
|
||||
#[test]
|
||||
@@ -220,7 +302,9 @@ fn collections_of_millions_end_at_the_limits() {
|
||||
assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap);
|
||||
assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap);
|
||||
let fuel = Limits { fuel: 100_000, ..Limits::default() };
|
||||
assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel);
|
||||
let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }";
|
||||
assert_eq!(limit(&fuel, &format!("new Set({endless})")), LimitKind::Fuel);
|
||||
assert_eq!(limit(&fuel, &format!("new Uint8Array({endless})")), LimitKind::Fuel);
|
||||
let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });";
|
||||
assert_eq!(limit(&fuel, m), LimitKind::Fuel);
|
||||
}
|
||||
|
||||
+87
-27
@@ -25,6 +25,7 @@ use crate::ast::{
|
||||
use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
use crate::heap::Key;
|
||||
use crate::parser::SuperRules;
|
||||
use crate::value::Str;
|
||||
use pattern::Mode;
|
||||
|
||||
@@ -97,6 +98,8 @@ struct FnCompiler<'a> {
|
||||
recursion: u32,
|
||||
/// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
|
||||
es2015: bool,
|
||||
/// The code is a module's ([`compile_module`]), which has no completion value.
|
||||
module: bool,
|
||||
scopes: Vec<BlockScope>,
|
||||
templates: Vec<Template>,
|
||||
uses_this: bool,
|
||||
@@ -112,6 +115,8 @@ struct FnCompiler<'a> {
|
||||
optional: Vec<(Label, u32)>,
|
||||
/// The code is a generator function's.
|
||||
generator: bool,
|
||||
/// [`Code::supers`].
|
||||
supers: SuperRules,
|
||||
}
|
||||
|
||||
/// The `var` names and function declarations a body hoists.
|
||||
@@ -153,6 +158,7 @@ impl<'a> FnCompiler<'a> {
|
||||
uses_arguments: false,
|
||||
recursion,
|
||||
es2015: false,
|
||||
module: false,
|
||||
scopes: Vec::new(),
|
||||
templates: Vec::new(),
|
||||
uses_this: false,
|
||||
@@ -162,9 +168,16 @@ impl<'a> FnCompiler<'a> {
|
||||
annex: HashSet::new(),
|
||||
optional: Vec::new(),
|
||||
generator: false,
|
||||
supers: SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Script and eval code keep the value of the last expression statement as their
|
||||
/// completion value; function and module code do not.
|
||||
fn keeps_completion(&self) -> bool {
|
||||
self.kind != CodeKind::Function && !self.module
|
||||
}
|
||||
|
||||
// ---- emitting ----
|
||||
|
||||
fn emit(&mut self, op: Op) {
|
||||
@@ -266,8 +279,10 @@ impl<'a> FnCompiler<'a> {
|
||||
let mut seen = HashSet::new();
|
||||
// The `let` and `const` names and the block functions of each statement list and loop the
|
||||
// walk enters, with the index of the one around it; the body's are first, and its
|
||||
// functions are var-scoped.
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
|
||||
// functions are var-scoped. Only Annex B's block functions read them, so without
|
||||
// [`crate::Options::es2015`] none is collected.
|
||||
let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() };
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, top, HashSet::new())];
|
||||
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
|
||||
let mut add_var = |out: &mut Hoisted, k: Key| {
|
||||
if seen.insert(k.clone()) {
|
||||
@@ -302,7 +317,7 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
Stmt::Block(list) => {
|
||||
let s = enter(self.lexical_names(list), self.block_function_names(list));
|
||||
let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope };
|
||||
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::If { consequent, alternate, .. } => {
|
||||
@@ -310,7 +325,7 @@ impl<'a> FnCompiler<'a> {
|
||||
// (Annex B.3.4).
|
||||
for &branch in alternate.iter().chain(std::iter::once(consequent)) {
|
||||
let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_)));
|
||||
let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
work.push((branch, nested || inner, s));
|
||||
}
|
||||
}
|
||||
@@ -343,30 +358,38 @@ impl<'a> FnCompiler<'a> {
|
||||
work.push((*body, nested || inner, s));
|
||||
}
|
||||
Stmt::Switch { cases, .. } => {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
let s = enter(names, funcs);
|
||||
let s = if inner {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
enter(names, funcs)
|
||||
} else {
|
||||
scope
|
||||
};
|
||||
for case in cases.iter().rev() {
|
||||
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
}
|
||||
Stmt::Try { block, handler, finalizer } => {
|
||||
if let Some(f) = finalizer {
|
||||
let s = enter(self.lexical_names(f), self.block_function_names(f));
|
||||
let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope };
|
||||
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
if let Some(h) = handler {
|
||||
// A `var` cannot redeclare a destructured catch parameter's names
|
||||
// (ECMA-262 11th edition section B.3.5), so a block function of that name
|
||||
// in the body is not also made a `var` (section B.3.3).
|
||||
let mut names = self.lexical_names(&h.body);
|
||||
if matches!(h.param, Binding::Pattern(_)) {
|
||||
names.extend(self.bound_keys(&h.param));
|
||||
}
|
||||
let s = enter(names, self.block_function_names(&h.body));
|
||||
let s = if inner {
|
||||
// A `var` cannot redeclare a destructured catch parameter's names
|
||||
// (ECMA-262 11th edition section B.3.5), so a block function of that
|
||||
// name in the body is not also made a `var` (section B.3.3).
|
||||
let mut names = self.lexical_names(&h.body);
|
||||
if matches!(h.param, Binding::Pattern(_)) {
|
||||
names.extend(self.bound_keys(&h.param));
|
||||
}
|
||||
enter(names, self.block_function_names(&h.body))
|
||||
} else {
|
||||
scope
|
||||
};
|
||||
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
let s = enter(self.lexical_names(block), self.block_function_names(block));
|
||||
let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope };
|
||||
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::Expr(_)
|
||||
@@ -489,7 +512,10 @@ impl<'a> FnCompiler<'a> {
|
||||
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
|
||||
for d in decls {
|
||||
match (d.init, &d.target) {
|
||||
(Some(init), Binding::Name(name)) => self.named_expr(init, &name.name)?,
|
||||
(Some(init), Binding::Name(name)) => {
|
||||
let public_name = if name.name == crate::ast::DEFAULT_BINDING { "default" } else { &name.name };
|
||||
self.named_expr(init, public_name)?;
|
||||
}
|
||||
(Some(init), Binding::Pattern(_)) => self.expr(init)?,
|
||||
(None, Binding::Name(_)) => self.emit(Op::Undefined),
|
||||
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
|
||||
@@ -501,7 +527,7 @@ impl<'a> FnCompiler<'a> {
|
||||
|
||||
/// Compiles a nested function and returns its index in the function table.
|
||||
fn function(&mut self, fid: FunctionId) -> CResult<u32> {
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?;
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015, self.supers)?;
|
||||
// An arrow function reads the `this`, `arguments` and `new.target` of the code around it.
|
||||
if code.arrow {
|
||||
self.uses_this |= code.uses_this;
|
||||
@@ -548,7 +574,7 @@ impl<'a> FnCompiler<'a> {
|
||||
Stmt::Empty | Stmt::Debugger => Ok(()),
|
||||
Stmt::Expr(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
|
||||
self.emit(if self.keeps_completion() { Op::SetCompletion } else { Op::Pop });
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Block(list) => self.block(list),
|
||||
@@ -1012,8 +1038,12 @@ impl<'a> FnCompiler<'a> {
|
||||
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
|
||||
self.statement_completion_start();
|
||||
self.expr(*discriminant)?;
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
let scope = self.list_scope(&all, true)?;
|
||||
let scope = if self.es2015 {
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
self.list_scope(&all, true)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(scope) = scope {
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
@@ -1243,7 +1273,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.bind(fin_entry);
|
||||
// In script and eval code the finally block keeps the completion value of the try or
|
||||
// catch block when it ends normally (ECMA-262 5.1 section 12.14).
|
||||
let keeps_completion = self.kind != CodeKind::Function;
|
||||
let keeps_completion = self.keeps_completion();
|
||||
if keeps_completion {
|
||||
self.emit(Op::GetCompletion);
|
||||
}
|
||||
@@ -2389,6 +2419,7 @@ impl<'a> FnCompiler<'a> {
|
||||
own_name: meta.own_name,
|
||||
method: meta.method,
|
||||
generator: self.generator,
|
||||
supers: self.supers,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
Ok(Rc::new(code))
|
||||
@@ -2419,12 +2450,22 @@ fn len_u32(n: usize) -> u32 {
|
||||
}
|
||||
|
||||
/// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in.
|
||||
pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>, recursion: u32, bind_name: bool, es2015: bool) -> CResult<Rc<Code>> {
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in, and `outer` the
|
||||
/// [`Code::supers`] of the code around it, which an arrow function keeps.
|
||||
pub(crate) fn compile_function(
|
||||
ast: &Ast,
|
||||
fid: FunctionId,
|
||||
source: &Rc<Source>,
|
||||
recursion: u32,
|
||||
bind_name: bool,
|
||||
es2015: bool,
|
||||
outer: SuperRules,
|
||||
) -> CResult<Rc<Code>> {
|
||||
let Some(f) = ast.function(fid) else { return internal("function out of range") };
|
||||
let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion);
|
||||
c.es2015 = es2015;
|
||||
c.generator = f.generator;
|
||||
c.supers = if f.kind == FunctionKind::Arrow { outer } else { SuperRules::function(f.home, f.kind == FunctionKind::DerivedConstructor) };
|
||||
c.at(f.span.start);
|
||||
c.enter()?;
|
||||
// A destructured parameter has a binding of its own under a name no script can write, which
|
||||
@@ -2504,7 +2545,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
class_ctor: f.is_class_constructor(),
|
||||
derived: f.kind == FunctionKind::DerivedConstructor,
|
||||
pattern_names,
|
||||
own_name: es2015.then(|| key_of(f.name.as_ref().map_or("", |n| n.name.as_str()))),
|
||||
own_name: es2015.then(|| {
|
||||
let name = f.name.as_ref().map_or("", |n| n.name.as_str());
|
||||
key_of(if f.kind == FunctionKind::Declaration && name == crate::ast::DEFAULT_BINDING { "default" } else { name })
|
||||
}),
|
||||
method: (f.home && !f.is_class_constructor())
|
||||
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
|
||||
};
|
||||
@@ -2515,6 +2559,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kind: CodeKind) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0);
|
||||
c.es2015 = program.es2015;
|
||||
c.supers = program.supers;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
@@ -2523,6 +2568,21 @@ pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kin
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an
|
||||
/// environment of its own, as strict eval code does, and returns `undefined`.
|
||||
pub(crate) fn compile_module(program: &crate::Program, source: &Rc<Source>) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0);
|
||||
c.es2015 = true;
|
||||
c.module = true;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
c.emit(Op::Undefined);
|
||||
c.emit(Op::Return);
|
||||
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
|
||||
/// must be that one parenthesized function expression and nothing else. The name `anonymous` is
|
||||
/// not bound inside the function (section 15.3.2.1).
|
||||
@@ -2531,5 +2591,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc
|
||||
let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) };
|
||||
let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) };
|
||||
let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) };
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some)
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015, program.supers).map(Some)
|
||||
}
|
||||
@@ -119,8 +119,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
|
||||
syntax("'use strict'; { function f() {} function f() {} }");
|
||||
syntax("for (let x = 1 in {}) {}");
|
||||
syntax("if (1) let x = 1;");
|
||||
// No statement starts with `let [`, in a statement list or in the body of an `if` or a loop.
|
||||
for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] {
|
||||
syntax(&format!("var let = [1]; {body}"));
|
||||
}
|
||||
// Outside strict mode code `let` is still a name where no declaration can start.
|
||||
truth("var let = 3; let === 3");
|
||||
truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1");
|
||||
truth("var let = [2]; if (true) let\n; let.length === 1");
|
||||
// ECMAScript 5.1 reads it as a property read.
|
||||
assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0)));
|
||||
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
|
||||
// A labeled function in a block declares its name in the block.
|
||||
syntax("{ let f; label: function f() {} }");
|
||||
@@ -202,7 +210,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
|
||||
assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
|
||||
assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
|
||||
let restricted = realm.run("let undefined = 1;");
|
||||
assert!(restricted.is_err(), "{restricted:?}");
|
||||
assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,8 +396,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() {
|
||||
assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0)));
|
||||
// Deleting the property itself, not through the global environment, keeps the record
|
||||
// (ECMA-262 2015 sections 12.5.3.2 and 8.1.1.4.7).
|
||||
// Deleting the global object's property, not the variable, leaves the name declared
|
||||
// (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`).
|
||||
assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true)));
|
||||
assert!(is_thrown(&realm.run("let w = 4;"), "SyntaxError"));
|
||||
let after_property = realm.run("let w = 4; w");
|
||||
assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}");
|
||||
assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true)));
|
||||
let after_with = realm.run("let v = 4; v");
|
||||
assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}");
|
||||
assert_eq!(realm.run("(0, eval)('var u = 1'); with (this) { delete u; }"), Ok(JsValue::Bool(true)));
|
||||
assert!(is_thrown(&realm.run("let u = 5;"), "SyntaxError"));
|
||||
// Deleting a name the global object only inherits deletes no variable.
|
||||
@@ -525,6 +539,17 @@ fn arrow_functions_cannot_be_constructed() {
|
||||
truth("((a, b) => 0).length === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arrow_functions_length_is_configurable_and_read_only() {
|
||||
truth(
|
||||
"var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \
|
||||
d.configurable && !d.writable && !d.enumerable && d.value === 1",
|
||||
);
|
||||
truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')");
|
||||
// In ECMAScript 2015 code the other functions' `length` is configurable too (section 19.2.4.1).
|
||||
truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); d.configurable && !d.writable && !d.enumerable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arrow_functions_are_syntax_errors() {
|
||||
syntax("var f = x\n=> x;");
|
||||
@@ -1639,6 +1664,56 @@ fn eval_inside_a_function_reads_its_new_target() {
|
||||
throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a method reads `super` properties of the method's home object, from an
|
||||
/// arrow function and a nested `eval` too; in a function that is not a method, at the top of a
|
||||
/// script, through an indirect `eval` and in a `Function` body it is a `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_method_reads_super_properties() {
|
||||
truth("class A { get x() { return 'a' + this.n; } } class B extends A { m() { this.n = 1; return eval('super.x'); } } new B().m() === 'a1'");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return (() => eval('super.f()'))(); } } new B().m() === 3");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return eval('eval(\"super[\\'f\\']()\")'); } } new B().m() === 3");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return eval('() => super.f()')(); } } new B().m() === 3");
|
||||
truth("class A {} class B extends A { m() { eval('super.y = 5'); return this.y; } } new B().m() === 5");
|
||||
truth("class A { static s() { return 4; } } class B extends A { static s() { return eval('super.s()'); } } B.s() === 4");
|
||||
truth("class A { constructor() { this.t = eval('super.constructor'); } } new A().t === Object");
|
||||
truth("var o = { __proto__: { x: 2 }, m() { 'use strict'; return eval('super.x'); } }; o.m() === 2");
|
||||
throws("function F() { return eval('super.x'); } F()", "SyntaxError");
|
||||
throws("eval('super.x')", "SyntaxError");
|
||||
throws("class A { m() { return (function () { return eval('super.x'); })(); } } new A().m()", "SyntaxError");
|
||||
throws("class A { m() { return (0, eval)('super.x'); } } new A().m()", "SyntaxError");
|
||||
throws("class A { m() { return Function('return super.x'); } } new A().m()", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a derived class's constructor calls the superclass's constructor with
|
||||
/// `super(…)` and binds `this` once; elsewhere `super(…)` in eval code is a `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_derived_constructor_calls_super() {
|
||||
let a = "class A { constructor(v) { this.a = v; this.t = new.target; } } ";
|
||||
truth(&format!(
|
||||
"{a}class B extends A {{ constructor() {{ eval('super(1)'); this.b = 2; }} }} var b = new B(); b.a === 1 && b.b === 2 && b.t === B && b instanceof B"
|
||||
));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ var r = eval('super(1)'); this.r = r === this; }} }} new B().r"));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ (() => eval('super(1)'))(); }} }} new B().a === 1"));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ 'use strict'; eval('super(1)'); }} }} new B().a === 1"));
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ super(1); eval('super(2)'); }} }} new B()"), "ReferenceError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ eval('super(1); super(2)'); }} }} new B()"), "ReferenceError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ eval('this'); super(1); }} }} new B()"), "ReferenceError");
|
||||
throws("class A { constructor() { eval('super()'); } } new A()", "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ m() {{ eval('super()'); }} }} new B(1).m()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('super(1)'); }})(); }} }} new B()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ (0, eval)('super(1)'); }} }} new B()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ Function('super(1)'); }} }} new B()"), "SyntaxError");
|
||||
throws("function F() { eval('super()'); } F()", "SyntaxError");
|
||||
throws("eval('super()')", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A `Function` body reads its own `new.target`, wherever the `Function` constructor is called.
|
||||
#[test]
|
||||
fn a_function_body_reads_its_own_new_target() {
|
||||
truth("var G = Function('return new.target'); new G() === G && G() === undefined");
|
||||
truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
@@ -305,6 +305,8 @@ impl Interp {
|
||||
completion,
|
||||
boundary,
|
||||
generator: Some(generator),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+54
-3
@@ -199,7 +199,7 @@ pub(crate) enum Func {
|
||||
Pausable { f: crate::interp::PausableFn, name: &'static str },
|
||||
Host { f: Rc<HostFn>, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str> },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str>, site: bool },
|
||||
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
|
||||
}
|
||||
|
||||
@@ -272,6 +272,9 @@ pub(crate) enum Class {
|
||||
Xmp(Box<crate::xmp::Meta>),
|
||||
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
|
||||
XmpFile(Box<PropMap<Value>>),
|
||||
/// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the
|
||||
/// module's exports, read live from the bindings they name.
|
||||
ModuleNamespace(Box<ModuleExports>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
@@ -598,6 +601,8 @@ impl Class {
|
||||
Class::String(_) => "String",
|
||||
Class::RegExp(_) => "RegExp",
|
||||
Class::Date(_) => "Date",
|
||||
// The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1).
|
||||
Class::ModuleNamespace(_) => "Module",
|
||||
Class::UnitValue(_) => "UnitValue",
|
||||
Class::Map(_) => "Map",
|
||||
Class::Set(_) => "Set",
|
||||
@@ -644,17 +649,49 @@ pub(crate) struct Binding {
|
||||
/// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
|
||||
/// declares cannot take its name.
|
||||
pub(crate) lexical: bool,
|
||||
/// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5,
|
||||
/// CreateImportBinding): reading it reads the binding of that name in that environment, and
|
||||
/// writing it is a `TypeError`. `value` is unused.
|
||||
pub(crate) import: Option<(EnvId, Key)>,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
/// An initialized binding.
|
||||
pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None }
|
||||
}
|
||||
|
||||
/// A `let` (or with `constant`, a `const`) binding not yet initialized.
|
||||
pub(crate) fn lexical(constant: bool) -> Self {
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None }
|
||||
}
|
||||
|
||||
/// An import of the binding `name` of the environment `env`.
|
||||
pub(crate) fn import(env: EnvId, name: Key) -> Self {
|
||||
Self {
|
||||
value: Value::Undefined,
|
||||
mutable: false,
|
||||
deletable: false,
|
||||
uninitialized: false,
|
||||
constant: true,
|
||||
lexical: true,
|
||||
import: Some((env, name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in
|
||||
/// code unit order, with the environment and name of the binding it reads, or `None` for an export
|
||||
/// whose value is fixed (another module's namespace object), kept in the object's own property.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct ModuleExports {
|
||||
pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>,
|
||||
}
|
||||
|
||||
impl ModuleExports {
|
||||
/// The binding the export `name` reads, when it reads one.
|
||||
pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> {
|
||||
self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1103,6 +1140,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.push(map.env.0);
|
||||
extra = ARG_NAME_BYTES * map.names.len();
|
||||
}
|
||||
Class::ModuleNamespace(exports) => {
|
||||
for (k, b) in &exports.bindings {
|
||||
strings.add_key(k);
|
||||
if let Some((env, name)) = b {
|
||||
work.push(env.0);
|
||||
strings.add_key(name);
|
||||
}
|
||||
}
|
||||
extra = PROP_BYTES * exports.bindings.len();
|
||||
}
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
@@ -1233,6 +1280,10 @@ fn trace_env(e: &Env, work: &mut Vec<u32>, strings: &mut StringSizes) -> usize {
|
||||
for (k, b) in bindings.iter() {
|
||||
strings.add_key(k);
|
||||
mark_value(&b.value, work, strings);
|
||||
if let Some((env, name)) = &b.import {
|
||||
work.push(env.0);
|
||||
strings.add_key(name);
|
||||
}
|
||||
}
|
||||
ENV_BYTES + PROP_BYTES * bindings.len()
|
||||
}
|
||||
|
||||
+19
-6
@@ -160,11 +160,14 @@ pub enum HostItem {
|
||||
/// that is not a string is the call's result. `end` is called when the source has run,
|
||||
/// normally or not. Each source given has the next tag of [`crate::Realm::error_source`],
|
||||
/// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`]
|
||||
/// for that source alone; with `None` it takes the calling code's.
|
||||
/// for that source alone; with `None` it takes the calling code's. With `site`, `source` is
|
||||
/// given the [`CallSite`] of the code that calls it first, as the three numbers its source
|
||||
/// tag, line and column, and the arguments after them.
|
||||
Evaluator {
|
||||
source: HostFunction,
|
||||
end: Rc<dyn Fn()>,
|
||||
strict_writes: Rc<dyn Fn() -> Option<bool>>,
|
||||
site: bool,
|
||||
},
|
||||
/// A read-only property that reads the interpreter's own state.
|
||||
Script(ScriptItem),
|
||||
@@ -311,6 +314,8 @@ impl Interp {
|
||||
out
|
||||
}
|
||||
|
||||
/// The [`crate::host_ref`] of the object of a host class `id`, its key, class name and handle
|
||||
/// charged to `r` as the plain data they are before they are copied.
|
||||
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
|
||||
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
|
||||
self.charge_entries(r, len.saturating_add(2))?;
|
||||
@@ -466,7 +471,8 @@ impl Interp {
|
||||
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
|
||||
/// value. A result that is not a string is given to the script as it is. `end` is called once
|
||||
/// the source has run, normally or not. `strict_writes` gives the source's
|
||||
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's.
|
||||
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`,
|
||||
/// `f` is given the calling code's [`CallSite`] before the arguments.
|
||||
pub(crate) fn call_evaluator(
|
||||
&mut self,
|
||||
f: &crate::heap::DataFn,
|
||||
@@ -474,8 +480,13 @@ impl Interp {
|
||||
strict_writes: &Rc<dyn Fn() -> Option<bool>>,
|
||||
name: &Rc<str>,
|
||||
args: &[Value],
|
||||
site: bool,
|
||||
) -> JsResult<Value> {
|
||||
let data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
let caller = site.then(|| self.call_site());
|
||||
let mut data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
if let Some(caller) = caller {
|
||||
data.splice(0..0, site_data(caller));
|
||||
}
|
||||
let source = match f(data) {
|
||||
Ok(Data::String(source)) => source,
|
||||
Ok(d) => return self.write_data(d, 0, false),
|
||||
@@ -517,7 +528,9 @@ impl Interp {
|
||||
r
|
||||
}
|
||||
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says. With `this`, the
|
||||
/// first is the object `this` stands for, or `undefined` when it is not an object of a host
|
||||
/// class, charged to the same limits as the arguments.
|
||||
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading {
|
||||
limits: match how {
|
||||
@@ -689,9 +702,9 @@ impl Interp {
|
||||
HostItem::Converted(list, f) => {
|
||||
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
|
||||
}
|
||||
HostItem::Evaluator { source, end, strict_writes } => {
|
||||
HostItem::Evaluator { source, end, strict_writes, site } => {
|
||||
let proto = self.intrinsics.function_proto;
|
||||
let func = Func::Eval { f: source, end, strict_writes, name: full.into() };
|
||||
let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site };
|
||||
let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto)));
|
||||
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ use std::rc::Rc;
|
||||
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key};
|
||||
use crate::host::ArgRead;
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::Value;
|
||||
use crate::{Data, HostError, HostFunction};
|
||||
|
||||
@@ -245,6 +246,22 @@ impl Interp {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// [`Self::is_host_member`] for a property key. A Symbol names no host member.
|
||||
pub(crate) fn is_host_member_pk(&self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.is_host_member(id, name),
|
||||
PropKey::Sym(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::has_property_indexed`] for a property key. A Symbol does not go to the indexer.
|
||||
pub(crate) fn has_pk_indexed(&mut self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.has_property_indexed(id, name),
|
||||
PropKey::Sym(_) => self.has_pk(id, k),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`Data`] for the object of a host class `id`, or `None` when it is not one.
|
||||
pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult<Option<Data>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
@@ -253,6 +270,8 @@ impl Interp {
|
||||
Ok(Some(host_ref(&name, &h.handle)))
|
||||
}
|
||||
|
||||
/// The length of the class name and of the handle of the object of a host class `id`, or `None`
|
||||
/// when it is not one.
|
||||
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
|
||||
|
||||
@@ -433,7 +433,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
Ok(Data::Number(f64::from(s.line)))
|
||||
});
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap();
|
||||
r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap();
|
||||
let first = r.script_tag();
|
||||
@@ -455,6 +455,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag()));
|
||||
}
|
||||
|
||||
/// An evaluator made with `site` is given the place of the code that calls it before its
|
||||
/// arguments; one made without it is given only the arguments.
|
||||
#[test]
|
||||
fn an_evaluator_with_site_is_told_where_it_is_called() {
|
||||
let mut r = realm(10_000_000);
|
||||
let given: Rc<RefCell<Vec<Vec<Data>>>> = Rc::default();
|
||||
let evaluator = |site: bool| {
|
||||
let log = given.clone();
|
||||
let source: HostFunction = Rc::new(move |a| {
|
||||
log.borrow_mut().push(a);
|
||||
Ok(Data::String("1".into()))
|
||||
});
|
||||
HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site }
|
||||
};
|
||||
r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap();
|
||||
r.run("\n\n host.at('x');\nhost.plain('y');").unwrap();
|
||||
let tag = f64::from(r.script_tag());
|
||||
let given = given.borrow();
|
||||
assert_eq!(given.len(), 2, "{given:?}");
|
||||
assert_eq!(given[0].len(), 4, "{given:?}");
|
||||
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
|
||||
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
|
||||
assert_eq!(given[1], vec![Data::String("y".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_function_takes_each_argument_as_string_gives_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -849,6 +874,40 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
|
||||
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
|
||||
}
|
||||
|
||||
/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by
|
||||
/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing`
|
||||
/// with the handle `[0]`.
|
||||
fn with_long_things(r: &mut Realm, len: usize) {
|
||||
let make: HostFunction = Rc::new(move |a| {
|
||||
let mut handle = vec![if let Some(Data::Number(n)) = a.get(1) { *n } else { 0.0 }];
|
||||
handle.resize(len, 0.0);
|
||||
Ok(host_ref("Thing", &handle))
|
||||
});
|
||||
let take: HostFunction = Rc::new(|_| Ok(Data::Undefined));
|
||||
let members = vec![("make".to_string(), HostMember::Method(make)), ("take".to_string(), HostMember::Method(take))];
|
||||
let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
|
||||
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits() {
|
||||
let mut r = realm(100_000_000);
|
||||
with_long_things(&mut r, 1024);
|
||||
// 100 references to an object with a handle of 1,024 numbers are more than 100,000 entries.
|
||||
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 100_000 });
|
||||
let probe = "var t = thing.make(1), list = []; for (var i = 0; i < 100; i++) list.push(t); var m = 'none'; \
|
||||
try { thing.take(list); } catch (e) { m = e.name + '|' + e.message; } m";
|
||||
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
|
||||
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
|
||||
// The object a member is called on counts too.
|
||||
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 });
|
||||
let probe = "var m = 'none'; try { thing.make(2).take(); } catch (e) { m = e.name + '|' + e.message; } m";
|
||||
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
|
||||
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
|
||||
// Short handles stay within the limits.
|
||||
assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_constructor_called_with_new_cannot_wait() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -978,7 +1037,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() {
|
||||
fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() {
|
||||
let mut r = realm(10_000_000);
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
r.run("function late() { throw new Error('late'); }").unwrap();
|
||||
assert!(r.run("host.load()").is_err());
|
||||
@@ -1000,7 +1059,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
let s = seen.clone();
|
||||
r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units)));
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap();
|
||||
assert_eq!(out, JsValue::Number(49.0));
|
||||
@@ -1015,7 +1074,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() {
|
||||
let mut r = realm(10_000_000);
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet");
|
||||
r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap();
|
||||
@@ -1048,7 +1107,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() {
|
||||
let ends = Rc::new(Cell::new(0));
|
||||
let ended = ends.clone();
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17)))));
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) };
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false };
|
||||
let mut r = realm(10_000);
|
||||
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
|
||||
let e = r.run("host.evaluate()").unwrap_err();
|
||||
@@ -1069,7 +1128,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() {
|
||||
// The source does not parse, so a parse would throw a syntax error instead.
|
||||
let n = (1 << 17) + 1;
|
||||
let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1)))));
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
|
||||
r.interp().collect_for_room();
|
||||
|
||||
+308
-32
@@ -26,9 +26,10 @@ use crate::ast::BinaryOp;
|
||||
use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source};
|
||||
use crate::compiler::{CompileFail, compile_program};
|
||||
use crate::heap::{
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
|
||||
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES,
|
||||
OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
};
|
||||
use crate::parser::SuperRules;
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32};
|
||||
@@ -230,6 +231,11 @@ pub(crate) struct Frame {
|
||||
pub(crate) boundary: bool,
|
||||
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
|
||||
pub(crate) generator: Option<ObjId>,
|
||||
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
|
||||
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
|
||||
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
|
||||
pub(crate) chained: bool,
|
||||
pub(crate) pending_module: bool,
|
||||
}
|
||||
|
||||
/// Where the exception being thrown was raised: the code and the instruction.
|
||||
@@ -274,6 +280,7 @@ pub(crate) struct Interp {
|
||||
pub(crate) heap: Heap,
|
||||
pub(crate) stack: Vec<Value>,
|
||||
pub(crate) frames: Vec<Frame>,
|
||||
pending_module_frames: usize,
|
||||
/// Values native code holds while it may run JavaScript.
|
||||
pub(crate) temp_roots: Vec<Value>,
|
||||
/// Environments native code is still building.
|
||||
@@ -636,6 +643,7 @@ impl Interp {
|
||||
heap,
|
||||
stack: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
pending_module_frames: 0,
|
||||
temp_roots: Vec::new(),
|
||||
temp_envs: Vec::new(),
|
||||
temp_codes: Vec::new(),
|
||||
@@ -1031,7 +1039,11 @@ impl Interp {
|
||||
self.push(v)?;
|
||||
return Ok(None);
|
||||
}
|
||||
if self.frames.last().is_some_and(|frame| frame.pending_module) {
|
||||
self.pending_module_frames -= 1;
|
||||
}
|
||||
let frame = self.frame_mut()?;
|
||||
frame.pending_module = false;
|
||||
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
|
||||
frame.pc += 1;
|
||||
match op {
|
||||
@@ -1100,10 +1112,14 @@ impl Interp {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
|
||||
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if frame.boundary {
|
||||
if frame.chained {
|
||||
// The modules under it have not started, so no handler of theirs takes it.
|
||||
self.abort_to_boundary();
|
||||
}
|
||||
if frame.boundary || frame.chained {
|
||||
self.passing = v.clone();
|
||||
return Err(Abrupt::Throw(v));
|
||||
}
|
||||
@@ -1113,11 +1129,24 @@ impl Interp {
|
||||
/// Each running frame of script code, outermost first: its code, the index of its next
|
||||
/// instruction, and whether it runs a function (not global or eval code).
|
||||
pub(crate) fn script_frames(&self) -> impl Iterator<Item = (&Rc<Code>, usize, bool)> {
|
||||
self.frames.iter().map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
self.frames.iter().filter(|f| !f.pending_module).map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
}
|
||||
|
||||
pub(crate) fn clear_frames(&mut self) {
|
||||
self.frames.clear();
|
||||
self.pending_module_frames = 0;
|
||||
}
|
||||
|
||||
fn pop_frame(&mut self) -> Option<Frame> {
|
||||
let frame = self.frames.pop()?;
|
||||
if frame.pending_module {
|
||||
self.pending_module_frames -= 1;
|
||||
}
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
fn abort_to_boundary(&mut self) {
|
||||
while let Some(frame) = self.frames.pop() {
|
||||
while let Some(frame) = self.pop_frame() {
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if frame.boundary {
|
||||
@@ -1147,7 +1176,7 @@ impl Interp {
|
||||
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
|
||||
None => v,
|
||||
};
|
||||
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
|
||||
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
|
||||
@@ -1159,6 +1188,9 @@ impl Interp {
|
||||
if frame.boundary {
|
||||
return Ok(Some(v));
|
||||
}
|
||||
if frame.chained {
|
||||
return Ok(None);
|
||||
}
|
||||
self.push(v)?;
|
||||
Ok(None)
|
||||
}
|
||||
@@ -1489,6 +1521,15 @@ impl Interp {
|
||||
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
|
||||
}
|
||||
|
||||
/// The binding the binding `name` of the declarative environment `env` imports, when it is a
|
||||
/// module's import.
|
||||
fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> {
|
||||
match self.heap.env(env) {
|
||||
Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
|
||||
@@ -1501,6 +1542,14 @@ impl Interp {
|
||||
|
||||
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
|
||||
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
|
||||
if let Resolved::Decl(e) = r
|
||||
&& let Some((target, target_name)) = self.import_of(e, name)
|
||||
{
|
||||
if self.uninitialized(target, &target_name) {
|
||||
return Err(self.not_initialized(name));
|
||||
}
|
||||
return Ok((self.binding_value(target, &target_name)?, Value::Undefined));
|
||||
}
|
||||
match r {
|
||||
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
|
||||
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
|
||||
@@ -1520,6 +1569,12 @@ impl Interp {
|
||||
/// PutValue of a reference whose base was resolved earlier (section 8.7.2).
|
||||
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
|
||||
let strict = self.strict();
|
||||
if let Resolved::Decl(e) = r
|
||||
&& self.import_of(e, name).is_some()
|
||||
{
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
return Err(self.type_error(&format!("assignment to the import '{ident}'")));
|
||||
}
|
||||
match r {
|
||||
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
|
||||
Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
|
||||
@@ -1725,18 +1780,59 @@ impl Interp {
|
||||
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
|
||||
}
|
||||
}
|
||||
Class::ModuleNamespace(exports) => {
|
||||
if let Some((env, name)) = exports.binding(k)
|
||||
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
|
||||
{
|
||||
return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags }));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(o.props.get(k).cloned())
|
||||
}
|
||||
|
||||
/// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like):
|
||||
/// [`Self::get_own_property`], except that an export of a module namespace object read before
|
||||
/// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5).
|
||||
pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
|
||||
self.check_namespace_export(id, k)?;
|
||||
self.get_own_property(id, k)
|
||||
}
|
||||
|
||||
/// [`Self::own_property`] for a name or a Symbol: [`Self::get_own_pk`], with the same
|
||||
/// `ReferenceError` for a namespace export read before its module initialized it.
|
||||
pub(crate) fn own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
if let PropKey::Str(name) = k {
|
||||
self.check_namespace_export(id, name)?;
|
||||
}
|
||||
self.get_own_pk(id, k)
|
||||
}
|
||||
|
||||
/// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module
|
||||
/// has not initialized yet.
|
||||
fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> {
|
||||
if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class)
|
||||
&& let Some((env, name)) = exports.binding(k)
|
||||
&& self.uninitialized(*env, name)
|
||||
{
|
||||
return Err(self.not_initialized(k));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [[GetProperty]]: the property found on the object or its prototype chain.
|
||||
pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
|
||||
Ok(self.find_property_on(id, k)?.map(|(_, p)| p))
|
||||
}
|
||||
|
||||
/// [`Self::find_property`], with the object on the prototype chain that has the property.
|
||||
fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult<Option<(ObjId, Prop)>> {
|
||||
let mut cur = Some(id);
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
if let Some(p) = self.get_own_property(o, k)? {
|
||||
return Ok(Some(p));
|
||||
return Ok(Some((o, p)));
|
||||
}
|
||||
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
|
||||
if crate::builtins::binary::typed_key(self, o, k).is_some() {
|
||||
@@ -1763,7 +1859,14 @@ impl Interp {
|
||||
{
|
||||
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
|
||||
}
|
||||
match self.find_property(start, k)? {
|
||||
let found = self.find_property_on(start, k)?;
|
||||
// A module's export read before the module ran is in its temporal dead zone (ECMA-262
|
||||
// 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it
|
||||
// through a prototype chain.
|
||||
if let Some((holder, _)) = &found {
|
||||
self.check_namespace_export(*holder, k)?;
|
||||
}
|
||||
match found.map(|(_, p)| p) {
|
||||
// A name the object and its prototypes lack is the indexer's answer too.
|
||||
None => match self.host_indexer(start)? {
|
||||
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
|
||||
@@ -1779,7 +1882,11 @@ impl Interp {
|
||||
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
|
||||
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
|
||||
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
|
||||
match self.find_property(start, k)? {
|
||||
let found = self.find_property_on(start, k)?;
|
||||
if let Some((holder, _)) = &found {
|
||||
self.check_namespace_export(*holder, k)?;
|
||||
}
|
||||
match found.map(|(_, p)| p) {
|
||||
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Some(Prop::Data { value, .. }) => Ok(value),
|
||||
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
@@ -1891,10 +1998,26 @@ impl Interp {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw),
|
||||
_ => self.define_ordinary(id, k, desc, throw),
|
||||
}
|
||||
}
|
||||
|
||||
/// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a
|
||||
/// descriptor that leaves an export as it is (enumerable, writable, not configurable, its
|
||||
/// current value) succeeds.
|
||||
fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else {
|
||||
return self.reject_bool(throw, k, "a module namespace object is not extensible");
|
||||
};
|
||||
let unchanged = desc.configurable != Some(true)
|
||||
&& desc.enumerable != Some(false)
|
||||
&& !desc.is_accessor()
|
||||
&& desc.writable != Some(false)
|
||||
&& desc.value.as_ref().is_none_or(|v| same_value(v, &value));
|
||||
if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") }
|
||||
}
|
||||
|
||||
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
|
||||
if throw {
|
||||
let key = String::from_utf16_lossy(k);
|
||||
@@ -2067,6 +2190,10 @@ impl Interp {
|
||||
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
|
||||
return crate::builtins::binary::set_element(self, id, n, &v);
|
||||
}
|
||||
// A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9).
|
||||
if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) {
|
||||
return self.reject(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
match self.get_own_property(id, &k)? {
|
||||
Some(Prop::Data { flags, .. }) => {
|
||||
if flags & WRITABLE == 0 {
|
||||
@@ -2078,8 +2205,25 @@ impl Interp {
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
|
||||
None => {}
|
||||
}
|
||||
let proto = self.object(id)?.proto;
|
||||
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
|
||||
let mut inherited = None;
|
||||
let mut cur = self.object(id)?.proto;
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
// A write that reaches a module namespace object on the prototype chain is refused
|
||||
// there too: its [[Set]] returns false for every key.
|
||||
if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) {
|
||||
return self.reject(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
if let Some(p) = self.get_own_property(o, &k)? {
|
||||
inherited = Some(p);
|
||||
break;
|
||||
}
|
||||
cur = self.object(o)?.proto;
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return internal("prototype chain too long");
|
||||
}
|
||||
}
|
||||
match inherited {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
|
||||
@@ -2952,6 +3096,8 @@ impl Interp {
|
||||
// listed or their bytes reserved must not free it.
|
||||
let saved = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(o));
|
||||
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
|
||||
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
|
||||
let keys = self.enumerable_keys(o).and_then(|keys| {
|
||||
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
|
||||
self.reserve_heap(bytes)?;
|
||||
@@ -3066,8 +3212,8 @@ impl Interp {
|
||||
// keeps itself reachable.
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
|
||||
}
|
||||
Func::Eval { f, end, strict_writes, name } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?));
|
||||
Func::Eval { f, end, strict_writes, name, site } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?));
|
||||
}
|
||||
Func::Host { f: host, .. } => {
|
||||
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
|
||||
@@ -3156,9 +3302,7 @@ impl Interp {
|
||||
/// the stack.
|
||||
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let Entry { callee, code, env, this, args, new_target } = entry;
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
self.check_frame_room()?;
|
||||
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
|
||||
// An arrow function reads the `arguments` object of the function around it.
|
||||
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
|
||||
@@ -3219,6 +3363,8 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
};
|
||||
@@ -3545,17 +3691,16 @@ impl Interp {
|
||||
|
||||
/// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`.
|
||||
pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
|
||||
self.compile_units(units, strict, writes, kind, false)
|
||||
self.compile_units(units, strict, writes, kind, SuperRules::default())
|
||||
}
|
||||
|
||||
/// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function,
|
||||
/// where `new.target` is allowed.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result<Rc<Code>, CompileError> {
|
||||
/// [`Interp::compile_source_writes`]; `supers` says what `super` and `new.target` may do at
|
||||
/// the top of the code: what they may do where a direct `eval` is called.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, supers: SuperRules) -> Result<Rc<Code>, CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
|
||||
let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 };
|
||||
let program = parse(units, &options).map_err(CompileError::Syntax)?;
|
||||
let program = crate::parse_utf16_with_supers(units, &options, supers).map_err(CompileError::Syntax)?;
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
compile_program(&program, &source, kind).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
@@ -3563,6 +3708,22 @@ impl Interp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the
|
||||
/// source limit, with [`Self::source_tag`] as its source's tag.
|
||||
pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc<Code>, crate::ModuleInfo), CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { max_source_units: remaining, ..self.options.clone() };
|
||||
let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?;
|
||||
let writes = self.writes_mode();
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
CompileFail::Internal(m) => CompileError::Internal(m),
|
||||
})?;
|
||||
Ok((code, info))
|
||||
}
|
||||
|
||||
/// Turns a compile failure inside a running script into what it throws.
|
||||
pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt {
|
||||
match e {
|
||||
@@ -3582,10 +3743,12 @@ impl Interp {
|
||||
self.prepare_source(s.len())?;
|
||||
let units = self.flat_reserved(s)?;
|
||||
self.observe_code(&units);
|
||||
// Inside a function the eval code reads the function's `new.target` (section 18.2.1.1).
|
||||
let new_target = self.caller_new_target()?;
|
||||
// The eval code may use `super` and `new.target` as the code that calls it may, and reads
|
||||
// the `new.target` of the function it is in (section 18.2.1.1).
|
||||
let supers = self.frame()?.code.supers;
|
||||
let new_target = if supers.new_target { self.caller_new_target()? } else { None };
|
||||
let writes = self.writes_mode();
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, supers).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
|
||||
@@ -3749,7 +3912,7 @@ impl Interp {
|
||||
|
||||
/// A [`LimitKind::Frames`] error when no other frame fits under the frame limit.
|
||||
fn check_frame_room(&self) -> JsResult<()> {
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
if self.frames.len() - self.pending_module_frames >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
Ok(())
|
||||
@@ -3775,10 +3938,127 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4,
|
||||
/// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global
|
||||
/// scope holds its variables and functions, and one inside that its `let` and `const` names,
|
||||
/// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary
|
||||
/// roots for the caller to remove.
|
||||
pub(crate) fn instantiate_module(&mut self, code: &Rc<Code>) -> JsResult<(EnvId, EnvId)> {
|
||||
// The code itself was counted when the module was loaded ([`Self::hold_module_code`]).
|
||||
self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?;
|
||||
let scope = self.global_lex;
|
||||
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
|
||||
self.temp_envs.push(env);
|
||||
let lex = self.instantiate_global(code, env, env, true)?;
|
||||
self.temp_envs.push(lex);
|
||||
Ok((lex, env))
|
||||
}
|
||||
|
||||
/// Adds `binding` (an import) to the module environment `env`, which must not have `name`.
|
||||
pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> {
|
||||
self.use_fuel()?;
|
||||
// The binding's value (a namespace object) stays reachable while room is made.
|
||||
self.temp_roots.push(binding.value.clone());
|
||||
let reserved = self.reserve_heap(binding_bytes(name.len()));
|
||||
self.temp_roots.pop();
|
||||
reserved?;
|
||||
self.env_insert(env, name, binding)
|
||||
}
|
||||
|
||||
/// The environment that holds `name` of a module whose code runs in `lex` inside `env`.
|
||||
pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option<EnvId> {
|
||||
[lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name)))
|
||||
}
|
||||
|
||||
/// A module namespace object for the exports `exports`, each `(name, binding)` with the
|
||||
/// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit
|
||||
/// order and distinct.
|
||||
pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult<ObjId> {
|
||||
let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::<usize>();
|
||||
let bindings = PROP_BYTES.saturating_mul(exports.len());
|
||||
let tag = self.well_known(|symbols| &symbols.to_string_tag);
|
||||
let tagged = if tag.is_some() { PROP_BYTES.saturating_add(string_bytes(6)) } else { 0 };
|
||||
let extra = bindings.saturating_add(names).saturating_add(tagged);
|
||||
self.reserve_heap(OBJECT_BYTES.saturating_add(bindings).saturating_add(extra))?;
|
||||
let mut object = Object::new(Class::ModuleNamespace(Box::default()), None);
|
||||
if let Some(tag) = tag {
|
||||
object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 });
|
||||
}
|
||||
object.extensible = false;
|
||||
for (name, _) in &exports {
|
||||
self.use_fuel()?;
|
||||
let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone());
|
||||
object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE });
|
||||
}
|
||||
object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports }));
|
||||
let namespace = self.heap.alloc_object(object);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
Ok(namespace)
|
||||
}
|
||||
|
||||
/// Pushes the frames of a run of modules: `modules` in the order they run, each with its code,
|
||||
/// the environment it runs in and the outer one. The last is the boundary frame, pushed first;
|
||||
/// each of the others is pushed above the one that runs after it, so the first to run is on
|
||||
/// top.
|
||||
pub(crate) fn push_module_frames(&mut self, modules: &[(Rc<Code>, EnvId, EnvId)]) -> JsResult<()> {
|
||||
for (i, (code, env, var_env)) in modules.iter().enumerate().rev() {
|
||||
let last = i + 1 == modules.len();
|
||||
self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?;
|
||||
if let Some(frame) = self.frames.last_mut() {
|
||||
frame.chained = !last;
|
||||
frame.pending_module = true;
|
||||
}
|
||||
self.pending_module_frames += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends module linking: drops the temporary roots from `mark` on.
|
||||
pub(crate) fn drop_temp_envs(&mut self, mark: usize) {
|
||||
self.temp_envs.truncate(mark);
|
||||
}
|
||||
|
||||
pub(crate) fn temp_envs_mark(&self) -> usize {
|
||||
self.temp_envs.len()
|
||||
}
|
||||
|
||||
/// Counts a loaded module's code against the heap once, when the module is loaded, and keeps
|
||||
/// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules
|
||||
/// load counts it too.
|
||||
pub(crate) fn hold_module_code(&mut self, code: &Rc<Code>) -> JsResult<()> {
|
||||
self.charge_code(code, 0)?;
|
||||
self.temp_codes.push(code.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn temp_codes_mark(&self) -> usize {
|
||||
self.temp_codes.len()
|
||||
}
|
||||
|
||||
/// Ends module linking: drops the modules' code held from `mark` on.
|
||||
pub(crate) fn drop_temp_codes(&mut self, mark: usize) {
|
||||
self.temp_codes.truncate(mark);
|
||||
}
|
||||
|
||||
/// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it.
|
||||
pub(crate) fn hold(&mut self, v: Value) {
|
||||
self.temp_roots.push(v);
|
||||
}
|
||||
|
||||
pub(crate) fn temp_roots_mark(&self) -> usize {
|
||||
self.temp_roots.len()
|
||||
}
|
||||
|
||||
pub(crate) fn drop_temp_roots(&mut self, mark: usize) {
|
||||
self.temp_roots.truncate(mark);
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
|
||||
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
|
||||
///
|
||||
@@ -4191,11 +4471,7 @@ impl Interp {
|
||||
}
|
||||
let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) };
|
||||
let k = self.to_prop_key(a)?;
|
||||
match &k {
|
||||
PropKey::Str(name) => self.has_property_indexed(*o, name),
|
||||
PropKey::Sym(_) => self.has_pk(*o, &k),
|
||||
}
|
||||
.map(Value::Bool)
|
||||
self.has_pk_indexed(*o, &k).map(Value::Bool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1048,6 +1048,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
own_name: None,
|
||||
method: false,
|
||||
generator: false,
|
||||
supers: crate::parser::SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,12 @@ impl Interp {
|
||||
Some(_) => Value::Undefined,
|
||||
None => return self.walk_record(v),
|
||||
};
|
||||
if !self.is_callable(&method) {
|
||||
self.get_iterator_with(v, &method)
|
||||
}
|
||||
|
||||
/// GetIterator (section 7.4.1) with `method`, the `@@iterator` method already read from `v`.
|
||||
pub(crate) fn get_iterator_with(&mut self, v: &Value, method: &Value) -> JsResult<ObjId> {
|
||||
if !self.is_callable(method) {
|
||||
let what = match v {
|
||||
Value::Undefined => "undefined",
|
||||
Value::Null => "null",
|
||||
@@ -67,7 +72,7 @@ impl Interp {
|
||||
};
|
||||
return Err(self.type_error(&format!("{what} is not iterable")));
|
||||
}
|
||||
let iterator = self.call(&method, v, &[])?;
|
||||
let iterator = self.call(method, v, &[])?;
|
||||
if !matches!(iterator, Value::Object(_)) {
|
||||
return Err(self.type_error("the iterator is not an object"));
|
||||
}
|
||||
@@ -187,6 +192,41 @@ impl Interp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Calls `f` with each value the iterator of `rec` gives, until it is done. When `f` throws,
|
||||
/// the iterator is closed ([`Interp::iter_close_after_throw`]) and the exception is thrown
|
||||
/// again; when a step throws, the iterator is not closed. `rec` and each value are kept
|
||||
/// reachable while `f` runs.
|
||||
pub(crate) fn for_each_value(&mut self, rec: ObjId, mut f: impl FnMut(&mut Self, Value) -> JsResult<()>) -> JsResult<()> {
|
||||
self.rooted(&[Value::Object(rec)], |i| {
|
||||
while let Some(v) = i.iter_next(rec)? {
|
||||
match i.rooted(std::slice::from_ref(&v), |i| f(i, v.clone())) {
|
||||
Ok(()) => {}
|
||||
Err(Abrupt::Throw(reason)) => return Err(i.iter_close_after_throw(rec, reason)),
|
||||
Err(other) => return Err(other),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// IteratorClose (section 7.4.6) with the exception `reason`: closes the iterator of `rec`
|
||||
/// unless it is done, and gives back `reason` to throw, with the position it was thrown from.
|
||||
/// What closing it throws is dropped, the lookup of `return` included (ECMA-262 2023 section
|
||||
/// 7.4.8, steps 4 to 6); running out of fuel, heap or time is not.
|
||||
pub(crate) fn iter_close_after_throw(&mut self, rec: ObjId, reason: Value) -> Abrupt {
|
||||
let site = self.throw_site.clone();
|
||||
let mark = self.thrown_mark;
|
||||
match self.rooted(std::slice::from_ref(&reason), |i| i.iter_close(rec)) {
|
||||
Ok(()) | Err(Abrupt::Throw(_)) => {
|
||||
self.throw_site = site;
|
||||
self.thrown_mark = mark;
|
||||
self.passing = reason.clone();
|
||||
Abrupt::Throw(reason)
|
||||
}
|
||||
Err(other) => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` → `record`.
|
||||
pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> {
|
||||
let v = self.peek(0)?;
|
||||
@@ -227,8 +267,9 @@ impl Interp {
|
||||
self.append_values(rec, a)
|
||||
}
|
||||
|
||||
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack.
|
||||
fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
|
||||
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack or
|
||||
/// otherwise kept reachable.
|
||||
pub(crate) fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
|
||||
while let Some(v) = self.iter_next(rec)? {
|
||||
let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") };
|
||||
let i = *length;
|
||||
|
||||
+57
-12
@@ -63,7 +63,17 @@
|
||||
//! closes its iterator. In a realm made without the option and later given it with
|
||||
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
|
||||
//! by index and strings by code point, and throw a `TypeError` for other values.
|
||||
//! Object rest properties (`{ a, ...rest }`) and modules stay syntax errors.
|
||||
//! Object rest properties (`{ a, ...rest }`) stay syntax errors, and so do `import` and `export`
|
||||
//! in a script.
|
||||
//!
|
||||
//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import`
|
||||
//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a
|
||||
//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module
|
||||
//! once, after the modules it imports, with each import reading the exporting module's binding. In
|
||||
//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does
|
||||
//! not wait for a module that is still waiting for its own imports, and reading a binding of that
|
||||
//! module before it is initialized throws a `ReferenceError`.
|
||||
//! Dynamic `import()` is a syntax error.
|
||||
//!
|
||||
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
|
||||
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
|
||||
@@ -103,10 +113,13 @@
|
||||
//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the
|
||||
//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine
|
||||
//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with
|
||||
//! a `next` method. Until the language has iterators, the collection constructors and
|
||||
//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by
|
||||
//! index. A typed array constructor reads an array or an object with a `length` the same way, and
|
||||
//! converts a first argument that is not an object to a length. A buffer longer than the heap
|
||||
//! a `next` method, and `Map`, `Set` and the typed arrays are iterable. The collection
|
||||
//! constructors read their argument through its `@@iterator` method (sections 23.1.1.1 to
|
||||
//! 23.4.1.1), so an object without one is a `TypeError`, and a `Map` entry that is not an object
|
||||
//! is a `TypeError` too. A typed array constructor given an object that is not a buffer or a typed
|
||||
//! array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator
|
||||
//! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A
|
||||
//! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap
|
||||
//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
@@ -126,6 +139,7 @@ mod host_classes;
|
||||
mod interp;
|
||||
mod iteration;
|
||||
mod lexer;
|
||||
mod module;
|
||||
mod number;
|
||||
mod number_builtins;
|
||||
mod parser;
|
||||
@@ -148,15 +162,16 @@ mod xmp_classes;
|
||||
mod xpath;
|
||||
|
||||
pub use ast::{
|
||||
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId,
|
||||
FunctionKind, LexKind, LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece,
|
||||
UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget,
|
||||
ForInit, Function, FunctionId, FunctionKind, ImportEntry, ImportName, LexKind, LogicalOp, MethodKind, ModuleInfo, ModuleRequest, Name, Program,
|
||||
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{
|
||||
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
|
||||
@@ -219,11 +234,39 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
|
||||
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs inside a function, where `new.target` is allowed
|
||||
/// (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_in_function(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
|
||||
/// Parses `source` as a module (ECMA-262 2015 section 15.2): strict mode code with
|
||||
/// [`Options::es2015`]'s forms, `import` and `export` declarations at its top, and no preprocessor
|
||||
/// lines, whatever `options` says about those three. Gives its statements and what it imports and
|
||||
/// exports.
|
||||
pub fn parse_module(source: &str, options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
|
||||
let units = to_utf16(source, options)?;
|
||||
parse_module_utf16(&units, options)
|
||||
}
|
||||
|
||||
/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]).
|
||||
pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program)
|
||||
parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info))
|
||||
}
|
||||
|
||||
/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module
|
||||
/// ([`parse_module`]). The source must be a valid module.
|
||||
pub fn tokenize_module(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
|
||||
let units = to_utf16(source, options)?;
|
||||
check_length(units.len(), options)?;
|
||||
parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens)
|
||||
}
|
||||
|
||||
/// `options` as a module is read with them.
|
||||
pub(crate) fn module_options(options: &Options) -> Options {
|
||||
Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() }
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
|
||||
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_supers(rules).parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and
|
||||
@@ -321,6 +364,8 @@ mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod module_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod reflect_tests;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports,
|
||||
//! linking their imports to the bindings their exports name, and readying them to run, each once,
|
||||
//! the modules a module imports before it.
|
||||
//!
|
||||
//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17,
|
||||
//! HostResolveImportedModule): it gives a key that names the module, and its source the first time
|
||||
//! it gives that key. Every module is parsed and compiled before any runs, and every import is
|
||||
//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host
|
||||
//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many
|
||||
//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each
|
||||
//! binding made in linking takes a unit.
|
||||
//!
|
||||
//! An import reads the exporting module's binding itself, so it sees each later assignment, and a
|
||||
//! read before that binding is initialized (a module that imports one that imports it back) is a
|
||||
//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no
|
||||
//! prototype, takes no writes and has the module's export names, in code unit order, as its
|
||||
//! properties. `export *` passes on every name but `default`; a name two `export *` give from
|
||||
//! different bindings is left out of a namespace and is a `SyntaxError` to import.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::ast::{ExportEntry, ImportName, ModuleInfo};
|
||||
use crate::bytecode::Code;
|
||||
use crate::heap::{Binding, Env, EnvId, ObjId, Prop, key};
|
||||
use crate::interp::{Abrupt, CompileError, ErrorType, Interp};
|
||||
use crate::value::Value;
|
||||
|
||||
/// What the host gives for a module a run imports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoadedModule {
|
||||
/// What names the module: two specifiers that give one key import one module, which runs once.
|
||||
pub key: String,
|
||||
/// The module's source, given the first time the host gives its key in a run. `None` for a key
|
||||
/// the host gave before in the same run.
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
/// Why the host cannot give a module, which ends the run before any module runs: the error the
|
||||
/// `import` raises, with its message.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LoadError {
|
||||
/// A specifier the host does not read: a `SyntaxError`.
|
||||
Syntax(String),
|
||||
/// A limit of the host's: a `RangeError`.
|
||||
Range(String),
|
||||
/// A module that is missing, refused or unreadable: an `Error`.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The host's map from a specifier to a module: called with the key of the importing module and
|
||||
/// the specifier as written.
|
||||
pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result<LoadedModule, LoadError> + 'a;
|
||||
|
||||
/// Bounds on the modules of one run.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleLimits {
|
||||
/// The most modules a run loads, the first included.
|
||||
pub modules: usize,
|
||||
/// The most imports from the first module to any other, along the shortest chain.
|
||||
pub depth: usize,
|
||||
}
|
||||
|
||||
impl Default for ModuleLimits {
|
||||
fn default() -> Self {
|
||||
Self { modules: 64, depth: 16 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The most modules a run loads, whatever its limits say: [`resolve_export`] and
|
||||
/// [`exported_names`] recurse once for each module at most.
|
||||
const MAX_MODULES: usize = 1024;
|
||||
/// The most `(module, name)` pairs one export's resolution visits.
|
||||
const MAX_RESOLVE_STEPS: usize = 1024;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ResolveSeen {
|
||||
pairs: HashSet<ResolveKey>,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
struct ResolveKey {
|
||||
module: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl PartialEq for ResolveKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(count.get() + 1));
|
||||
self.module == other.module && self.name == other.name
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ResolveKey {}
|
||||
|
||||
impl std::hash::Hash for ResolveKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(&(self.module, &self.name), state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
pub(crate) static RESOLVED_STAR_EDGES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static RESOLVE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static RESOLVE_MEMBERSHIP_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A loaded module.
|
||||
struct Record {
|
||||
key: String,
|
||||
info: ModuleInfo,
|
||||
code: Rc<Code>,
|
||||
tag: u32,
|
||||
/// The module each of `info.requests` names, by index.
|
||||
requested: Vec<usize>,
|
||||
/// The environment its code runs in and the outer one, once instantiated.
|
||||
envs: Option<(EnvId, EnvId)>,
|
||||
namespace: Option<ObjId>,
|
||||
/// Each name the module exports itself or re-exports by name, with its entry in
|
||||
/// `info.exports`.
|
||||
explicit: HashMap<String, usize>,
|
||||
/// Each `export *` request, replaced by distinct canonical targets after loading, in order.
|
||||
stars: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Why a module run could not start.
|
||||
pub(crate) enum LinkFail {
|
||||
/// A module does not parse; `tag` is its source's.
|
||||
Syntax { tag: u32, error: crate::SyntaxError },
|
||||
/// An exception, raised at `line` and `column` of the module whose source has `tag`.
|
||||
At { tag: u32, line: u32, column: u32, abrupt: Abrupt },
|
||||
/// A limit or an internal error, not at any place.
|
||||
Run(Abrupt),
|
||||
}
|
||||
|
||||
/// Where an export resolves to (ResolvedBinding).
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum Resolution {
|
||||
/// The binding `name` of module `module`.
|
||||
Binding { module: usize, name: String },
|
||||
/// The namespace object of module `module` (`export * as ns from`).
|
||||
Namespace(usize),
|
||||
}
|
||||
|
||||
/// An export that two `export *` declarations give from different places.
|
||||
struct Ambiguous;
|
||||
|
||||
/// The modules of a run, loaded and linked.
|
||||
struct Graph<'a, 'l> {
|
||||
interp: &'a mut Interp,
|
||||
records: Vec<Record>,
|
||||
by_key: HashMap<String, usize>,
|
||||
load: &'a mut ModuleLoader<'l>,
|
||||
}
|
||||
|
||||
/// Loads the module `key` with `source` and every module it imports, instantiates and links them,
|
||||
/// and gives them in the order they run, each with its code, the environment it runs in and the
|
||||
/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes
|
||||
/// the next tag. The environments stay in the interpreter's temporary roots for the caller to
|
||||
/// remove once their frames are pushed.
|
||||
pub(crate) fn link(
|
||||
interp: &mut Interp,
|
||||
key_name: &str,
|
||||
source: &str,
|
||||
entry_tag: u32,
|
||||
limits: ModuleLimits,
|
||||
load: &mut ModuleLoader<'_>,
|
||||
) -> Result<Vec<(Rc<Code>, EnvId, EnvId)>, LinkFail> {
|
||||
let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load };
|
||||
if limits.modules == 0 {
|
||||
return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached"));
|
||||
}
|
||||
graph.add(key_name.to_string(), source, entry_tag)?;
|
||||
graph.load_imports(limits)?;
|
||||
graph.instantiate()?;
|
||||
graph.link_imports()?;
|
||||
Ok(graph.evaluation_order())
|
||||
}
|
||||
|
||||
impl Graph<'_, '_> {
|
||||
/// Parses and compiles a module's source under `tag`.
|
||||
fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result<usize, LinkFail> {
|
||||
let interp = &mut *self.interp;
|
||||
let minimum_units = source.len().div_ceil(3);
|
||||
if u64::try_from(minimum_units).unwrap_or(u64::MAX) > interp.fuel {
|
||||
interp.prepare_source(minimum_units).map_err(LinkFail::Run)?;
|
||||
}
|
||||
interp.prepare_source(0).map_err(LinkFail::Run)?;
|
||||
interp.prepare_source(source.encode_utf16().count()).map_err(LinkFail::Run)?;
|
||||
let saved = std::mem::replace(&mut interp.source_tag, tag);
|
||||
let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units));
|
||||
interp.source_tag = saved;
|
||||
let (code, info) = match compiled {
|
||||
Ok(c) => c,
|
||||
Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }),
|
||||
Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))),
|
||||
};
|
||||
// The record keeps the code from here on, so the heap counts it from here on.
|
||||
self.interp.hold_module_code(&code).map_err(LinkFail::Run)?;
|
||||
let mut explicit = HashMap::new();
|
||||
let mut stars = Vec::new();
|
||||
for (i, e) in info.exports.iter().enumerate() {
|
||||
match e {
|
||||
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
|
||||
explicit.entry(export_name.clone()).or_insert(i);
|
||||
}
|
||||
ExportEntry::Star { request, .. } => stars.push(*request),
|
||||
}
|
||||
}
|
||||
self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars });
|
||||
let index = self.records.len() - 1;
|
||||
self.by_key.insert(key_name, index);
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// An exception of type `t` with `message`, at the source offset `offset` of module `m`.
|
||||
fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail {
|
||||
let (tag, (line, column)) = match self.records.get(m) {
|
||||
Some(r) => (r.tag, r.code.source.lines.line_column(offset)),
|
||||
None => (crate::realm::UNKNOWN_SOURCE, (0, 0)),
|
||||
};
|
||||
LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) }
|
||||
}
|
||||
|
||||
/// Loads the modules each loaded module imports, breadth first, so a module's depth is the
|
||||
/// length of the shortest chain of imports to it.
|
||||
fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> {
|
||||
let max_modules = limits.modules.min(MAX_MODULES);
|
||||
let mut depths = vec![0usize];
|
||||
let mut i = 0;
|
||||
while i < self.records.len() {
|
||||
let requests: Vec<(String, bool, u32)> = self.records[i]
|
||||
.info
|
||||
.requests
|
||||
.iter()
|
||||
.map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start))
|
||||
.collect();
|
||||
let depth = depths.get(i).copied().unwrap_or(0);
|
||||
for (specifier, text, offset) in requests {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
// The host maps text to modules, and a specifier with an unpaired surrogate is not
|
||||
// text, so it is refused here, as a host refuses a specifier it does not read.
|
||||
if !text {
|
||||
let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Syntax, &message));
|
||||
}
|
||||
let referrer = self.records[i].key.clone();
|
||||
let loaded = match (self.load)(&referrer, &specifier) {
|
||||
Ok(loaded) => loaded,
|
||||
Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)),
|
||||
Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)),
|
||||
Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)),
|
||||
};
|
||||
let target = match (self.by_key.get(&loaded.key), loaded.source) {
|
||||
(Some(&j), _) => j,
|
||||
(None, None) => {
|
||||
let message = format!("the module '{specifier}' was given without its source");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Error, &message));
|
||||
}
|
||||
(None, Some(source)) => {
|
||||
if depth >= limits.depth {
|
||||
let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth);
|
||||
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
|
||||
}
|
||||
if self.records.len() >= max_modules {
|
||||
let message = format!("module limit ({max_modules}) reached at '{specifier}'");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
|
||||
}
|
||||
let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag));
|
||||
self.interp.evaluated = tag;
|
||||
depths.push(depth + 1);
|
||||
self.add(loaded.key, &source, tag)?
|
||||
}
|
||||
};
|
||||
self.records[i].requested.push(target);
|
||||
}
|
||||
let mut seen_targets = HashSet::new();
|
||||
let targets: Vec<usize> = self.records[i]
|
||||
.stars
|
||||
.iter()
|
||||
.filter_map(|&request| self.records[i].requested.get(request).copied())
|
||||
.filter(|target| seen_targets.insert(*target))
|
||||
.collect();
|
||||
self.records[i].stars = targets;
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Makes each module's environments, with its variables, functions and `let` and `const`
|
||||
/// names.
|
||||
fn instantiate(&mut self) -> Result<(), LinkFail> {
|
||||
for i in 0..self.records.len() {
|
||||
let code = self.records[i].code.clone();
|
||||
let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?;
|
||||
self.records[i].envs = Some(envs);
|
||||
for import in &self.records[i].info.imports {
|
||||
if matches!(&import.import, ImportName::Namespace) {
|
||||
self.interp.add_import(envs.1, key(&import.local.name), Binding::lexical(true)).map_err(LinkFail::Run)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The module the request `request` of module `m` names.
|
||||
fn target(&self, m: usize, request: usize) -> Option<usize> {
|
||||
self.records.get(m).and_then(|r| r.requested.get(request)).copied()
|
||||
}
|
||||
|
||||
/// The specifier of request `request` of module `m`, as written.
|
||||
fn specifier(&self, m: usize, request: usize) -> String {
|
||||
self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from,
|
||||
/// `None` when the module has no such export (or only through a cycle).
|
||||
fn resolve_export(&mut self, m: usize, name: &str, seen: &mut ResolveSeen) -> Result<Result<Option<Resolution>, Ambiguous>, LinkFail> {
|
||||
#[cfg(test)]
|
||||
RESOLVE_CALLS.with(|count| count.set(count.get() + 1));
|
||||
let visit = ResolveKey { module: m, name: name.to_string() };
|
||||
if seen.pairs.contains(&visit) {
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
if seen.count >= MAX_RESOLVE_STEPS {
|
||||
let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'");
|
||||
return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message)));
|
||||
}
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
seen.pairs.insert(visit);
|
||||
seen.count += 1;
|
||||
let Some(record) = self.records.get(m) else { return Ok(Ok(None)) };
|
||||
// The module's own export of the name, looked up in its index, comes before any `export *`.
|
||||
let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i));
|
||||
match explicit {
|
||||
Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))),
|
||||
Some(ExportEntry::Indirect { request, import, .. }) => {
|
||||
let (request, import) = (*request, import.clone());
|
||||
let Some(t) = self.target(m, request) else { return Ok(Ok(None)) };
|
||||
return match import {
|
||||
ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))),
|
||||
ImportName::Name(n) => self.resolve_export(t, &n, seen),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if name == "default" {
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
let mut star = None;
|
||||
let stars = record.stars.clone();
|
||||
for t in stars {
|
||||
#[cfg(test)]
|
||||
RESOLVED_STAR_EDGES.with(|count| count.set(count.get() + 1));
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
match self.resolve_export(t, name, seen)? {
|
||||
Err(Ambiguous) => return Ok(Err(Ambiguous)),
|
||||
Ok(None) => {}
|
||||
Ok(Some(r)) => match &star {
|
||||
None => star = Some(r),
|
||||
Some(s) if *s == r => {}
|
||||
Some(_) => return Ok(Err(Ambiguous)),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(Ok(star))
|
||||
}
|
||||
|
||||
/// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its
|
||||
/// `export *` modules but `default` included, each once.
|
||||
fn exported_names(
|
||||
&mut self,
|
||||
m: usize,
|
||||
star: bool,
|
||||
visited: &mut Vec<usize>,
|
||||
names: &mut Vec<String>,
|
||||
seen: &mut HashSet<String>,
|
||||
) -> Result<(), LinkFail> {
|
||||
if visited.contains(&m) {
|
||||
return Ok(());
|
||||
}
|
||||
visited.push(m);
|
||||
let count = self.records.get(m).map_or(0, |r| r.info.exports.len());
|
||||
for i in 0..count {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break };
|
||||
match e {
|
||||
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
|
||||
if !(star && export_name == "default") && !seen.contains(export_name) {
|
||||
seen.insert(export_name.clone());
|
||||
names.push(export_name.clone());
|
||||
}
|
||||
}
|
||||
ExportEntry::Star { request, .. } => {
|
||||
if let Some(t) = self.target(m, *request) {
|
||||
self.exported_names(t, true, visited, names, seen)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The environment and name of the binding `name` of module `m`.
|
||||
fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> {
|
||||
let (lex, env) = self.records.get(m)?.envs?;
|
||||
let k = key(name);
|
||||
self.interp.module_binding(lex, env, &k).map(|e| (e, k))
|
||||
}
|
||||
|
||||
/// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time.
|
||||
fn namespace(&mut self, m: usize) -> Result<ObjId, LinkFail> {
|
||||
if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) {
|
||||
return Ok(ns);
|
||||
}
|
||||
let mut names = Vec::new();
|
||||
self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?;
|
||||
let mut resolved = Vec::new();
|
||||
for name in names {
|
||||
if let Ok(Some(r)) = self.resolve_export(m, &name, &mut ResolveSeen::default())? {
|
||||
resolved.push((key(&name), r));
|
||||
}
|
||||
}
|
||||
resolved.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let mut exports = Vec::new();
|
||||
let mut later = Vec::new();
|
||||
for (k, r) in resolved {
|
||||
match r {
|
||||
Resolution::Binding { module, name } => match self.binding_of(module, &name) {
|
||||
Some(b) => exports.push((k, Some(b))),
|
||||
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
|
||||
},
|
||||
Resolution::Namespace(module) => {
|
||||
exports.push((k.clone(), None));
|
||||
later.push((k, module));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?;
|
||||
self.interp.hold(Value::Object(ns));
|
||||
if let Some(r) = self.records.get_mut(m) {
|
||||
r.namespace = Some(ns);
|
||||
}
|
||||
// A namespace that holds another is made first, so two that hold each other end.
|
||||
for (k, module) in later {
|
||||
let inner = self.namespace(module)?;
|
||||
let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE;
|
||||
self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?;
|
||||
}
|
||||
Ok(ns)
|
||||
}
|
||||
|
||||
/// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that
|
||||
/// each re-export resolves.
|
||||
fn link_imports(&mut self) -> Result<(), LinkFail> {
|
||||
for m in 0..self.records.len() {
|
||||
let exports = self.records[m].info.exports.clone();
|
||||
for e in &exports {
|
||||
let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue };
|
||||
if self.target(m, *request).is_none() {
|
||||
continue;
|
||||
}
|
||||
match self.resolve_export(m, export_name, &mut ResolveSeen::default())? {
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => {
|
||||
let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request));
|
||||
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
Err(Ambiguous) => {
|
||||
let message = format!("the export '{export_name}' is ambiguous");
|
||||
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
}
|
||||
}
|
||||
let imports = self.records[m].info.imports.clone();
|
||||
let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) };
|
||||
for imp in imports {
|
||||
let Some(t) = self.target(m, imp.request) else { continue };
|
||||
let local = key(&imp.local.name);
|
||||
let binding = match &imp.import {
|
||||
ImportName::Namespace => self.namespace_binding(t)?,
|
||||
ImportName::Name(n) => match self.resolve_export(t, n, &mut ResolveSeen::default())? {
|
||||
Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) {
|
||||
Some((target_env, target_name)) => Binding::import(target_env, target_name),
|
||||
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
|
||||
},
|
||||
Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?,
|
||||
Ok(None) => {
|
||||
let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request));
|
||||
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
Err(Ambiguous) => {
|
||||
let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request));
|
||||
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
},
|
||||
};
|
||||
if matches!(&imp.import, ImportName::Namespace) {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
let Some(Env::Decl { bindings, .. }) = self.interp.heap.env_mut(env) else {
|
||||
return Err(LinkFail::Run(Abrupt::Internal("namespace import environment not found".into())));
|
||||
};
|
||||
let Some(slot) = bindings.get_mut(&local) else {
|
||||
return Err(LinkFail::Run(Abrupt::Internal("namespace import binding not found".into())));
|
||||
};
|
||||
*slot = binding;
|
||||
} else {
|
||||
self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An immutable binding of module `m`'s namespace object.
|
||||
fn namespace_binding(&mut self, m: usize) -> Result<Binding, LinkFail> {
|
||||
let ns = self.namespace(m)?;
|
||||
Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) })
|
||||
}
|
||||
|
||||
/// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module
|
||||
/// after the modules it imports, in the order it imports them, and each once; a module an
|
||||
/// import cycle reaches again while it waits is not waited for.
|
||||
fn evaluation_order(&self) -> Vec<(Rc<Code>, EnvId, EnvId)> {
|
||||
let mut state = vec![0u8; self.records.len()];
|
||||
let mut order = Vec::new();
|
||||
let mut stack = vec![(0usize, 0usize)];
|
||||
if let Some(s) = state.first_mut() {
|
||||
*s = 1;
|
||||
}
|
||||
while let Some(top) = stack.last_mut() {
|
||||
let m = top.0;
|
||||
let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice());
|
||||
if let Some(&t) = requested.get(top.1) {
|
||||
top.1 += 1;
|
||||
if let Some(s @ 0) = state.get_mut(t) {
|
||||
*s = 1;
|
||||
stack.push((t, 0));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
stack.pop();
|
||||
if let Some(r) = self.records.get(m)
|
||||
&& let Some((lex, env)) = r.envs
|
||||
{
|
||||
order.push((r.code.clone(), lex, env));
|
||||
}
|
||||
}
|
||||
order
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{
|
||||
JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module,
|
||||
};
|
||||
|
||||
fn es() -> Realm {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
// Modules declare no globals, so they report through this array.
|
||||
assert!(realm.run("var out = [];").is_ok());
|
||||
realm
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_var_records_survive_deleting_only_an_inherited_property() {
|
||||
let mut realm = es();
|
||||
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
|
||||
assert_eq!(realm.run("var w; delete this.w; Object.prototype.w = 7; delete w;"), Ok(JsValue::Bool(true)));
|
||||
let error = realm.run("let w = 2; w;").unwrap_err();
|
||||
assert!(matches!(error.kind, RunErrorKind::Syntax | RunErrorKind::Thrown), "{error:?}");
|
||||
|
||||
let mut realm = es();
|
||||
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
|
||||
assert_eq!(realm.run("var w; delete w;"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(realm.run("let w = 2; w;"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_allocations_charge_binding_tables_and_symbols() {
|
||||
use crate::heap::{OBJECT_BYTES, PROP_BYTES, key};
|
||||
let mut realm = es();
|
||||
let interp = realm.interp();
|
||||
let before = interp.heap.bytes;
|
||||
let exports = (0..128).map(|n| (key(&format!("v{n}")), None)).collect();
|
||||
let namespace = interp.module_namespace(exports, &[]).unwrap();
|
||||
let symbols = interp.heap.object(namespace).unwrap().syms.as_ref().map_or(0, |symbols| symbols.len());
|
||||
let required = OBJECT_BYTES + PROP_BYTES * (128 * 2 + symbols);
|
||||
assert!(interp.heap.bytes - before >= required, "namespace charged {} bytes, needs at least {required}", interp.heap.bytes - before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_resolution_membership_work_is_bounded_per_visit() {
|
||||
let mut files: Vec<(String, String)> = (0..31).map(|n| (format!("./m{n}.mjs"), format!("export * from './m{}.mjs';", n + 1))).collect();
|
||||
let source = (0..32).map(|n| format!("export var v{n} = {n};")).collect();
|
||||
files.push(("./m31.mjs".into(), source));
|
||||
let references: Vec<_> = files.iter().map(|(name, source)| (name.as_str(), source.as_str())).collect();
|
||||
let mut load = loader(&references);
|
||||
let mut realm = es();
|
||||
crate::module::RESOLVE_CALLS.with(|count| count.set(0));
|
||||
crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(0));
|
||||
realm
|
||||
.run_module("main.mjs", "import * as ns from './m0.mjs'; out.push(ns.v0, ns.v31);", ModuleLimits { modules: 64, depth: 64 }, &mut load)
|
||||
.unwrap();
|
||||
let visits = crate::module::RESOLVE_CALLS.with(std::cell::Cell::get);
|
||||
let checks = crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(std::cell::Cell::get);
|
||||
assert!(visits > 32);
|
||||
assert!(checks <= visits * 4, "{checks} membership checks for {visits} export visits");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("0|31".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_aliases_resolve_each_canonical_target_once_per_name() {
|
||||
let exports: String = (0..100).map(|n| format!("export var v{n} = {n};")).collect();
|
||||
let stars: String = (0..100).map(|n| format!("export * from './alias{n}.mjs';")).collect();
|
||||
let mut supplied = HashSet::new();
|
||||
let mut load = |_: &str, specifier: &str| {
|
||||
let (key, source) = if specifier == "./stars.mjs" { ("stars", &stars) } else { ("canonical", &exports) };
|
||||
Ok(LoadedModule { key: key.into(), source: supplied.insert(key).then(|| source.clone()) })
|
||||
};
|
||||
let mut realm = es();
|
||||
crate::module::RESOLVED_STAR_EDGES.with(|count| count.set(0));
|
||||
realm
|
||||
.run_module("main.mjs", "import * as ns from './stars.mjs'; out.push(ns.v99, Object.keys(ns).length);", ModuleLimits::default(), &mut load)
|
||||
.unwrap();
|
||||
let steps = crate::module::RESOLVED_STAR_EDGES.with(|count| count.get());
|
||||
assert!(steps <= 200, "{steps} star edges inspected");
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("99|100".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ending_a_module_queue_restores_normal_frame_accounting() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
|
||||
let mut load = loader(&[("./m.mjs", "for (var i = 0; i < 1000; i++) {}")]);
|
||||
realm.start_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load).unwrap();
|
||||
assert!(matches!(realm.advance(1), Ok(Progress::Paused)));
|
||||
realm.end();
|
||||
assert_eq!(realm.run("function f() { return 1; } f();"), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_module_bodies_do_not_consume_active_call_frames() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
|
||||
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "function f() { return 1; } f();")];
|
||||
let mut load = loader(&files);
|
||||
let result = realm.run_module("main.mjs", "import './a.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(result, Ok(JsValue::Undefined));
|
||||
let mut load = loader(&[]);
|
||||
let result = realm.run_module("main.mjs", "function f() { return f(); } f();", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(result.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Frames)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_stack_excludes_bodies_waiting_to_run() {
|
||||
let mut realm = es();
|
||||
realm.define_host_object("$", [("stack".to_string(), crate::HostItem::Script(crate::ScriptItem::Stack))].into_iter().collect()).unwrap();
|
||||
let (result, out) = run_with(
|
||||
&mut realm,
|
||||
"import './m.mjs';",
|
||||
&[("./m.mjs", "function trace() { var s = $.stack; out.push(s.split('[global]').length - 1, s.indexOf('trace:') >= 0); } trace();")],
|
||||
ModuleLimits::default(),
|
||||
);
|
||||
assert_eq!(result, Ok(JsValue::Undefined));
|
||||
assert_eq!(out, "1|true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_sources_charge_utf16_units_instead_of_utf8_bytes() {
|
||||
let mut remaining = Vec::new();
|
||||
for character in ['a', 'é', '界'] {
|
||||
let source = format!("/*{}*/ export var value = 1;", character.to_string().repeat(1000));
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
let mut load = loader(&[]);
|
||||
realm.start_module("main.mjs", &source, ModuleLimits::default(), &mut load).unwrap();
|
||||
remaining.push(realm.fuel_left());
|
||||
}
|
||||
assert!(remaining.windows(2).all(|pair| pair[0] == pair[1]), "{remaining:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_exported_functions_keep_their_public_names() {
|
||||
for (source, name) in [
|
||||
("export default function () {}", "default"),
|
||||
("export default () => {};", "default"),
|
||||
("export default (function () {});", "default"),
|
||||
("export default function named() {}", "named"),
|
||||
] {
|
||||
let out = run("import value from './m.mjs'; out.push(value.name);", &[("./m.mjs", source)]);
|
||||
assert_eq!(out, name, "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_writes_through_namespace_prototypes_are_refused() {
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs'; var k = Symbol('new'), child = Object.create(ns); \
|
||||
try { child[k] = 1; } catch (e) { out.push(e.name); } \
|
||||
out.push(Object.getOwnPropertySymbols(child).length); \
|
||||
Object.defineProperty(child, k, {value: 3, writable: true}); child[k] = 4; out.push(child[k]);",
|
||||
&[("./m.mjs", "export var value = 1;")],
|
||||
);
|
||||
assert_eq!(out, "TypeError|0|4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_exposes_its_own_immutable_symbol_tag() {
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs'; \
|
||||
var d = Object.getOwnPropertyDescriptor(ns, Symbol.toStringTag); \
|
||||
out.push(ns[Symbol.toStringTag], Object.getOwnPropertySymbols(ns).length, \
|
||||
d && d.writable, d && d.enumerable, d && d.configurable);",
|
||||
&[("./m.mjs", "export var value = 1;")],
|
||||
);
|
||||
assert_eq!(out, "Module|1|false|false|false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_reject_await_identifiers_before_running_dependencies() {
|
||||
for source in ["export const await = 1;", "var aw\\u0061it = 1;", "await;", "function await() {}"] {
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./effect.mjs", "out.push('dependency');")]);
|
||||
let result = realm.run_module("main.mjs", "import './effect.mjs'; export const await = 1;", ModuleLimits::default(), &mut load);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(realm.run("out.length").unwrap(), JsValue::Number(0.0));
|
||||
assert!(realm.run("var await = 1; await").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synchronous_and_sliced_modules_drain_promise_jobs() {
|
||||
let source = "out.push('body'); Promise.resolve().then(function () { out.push('resolved'); }); \
|
||||
Promise.reject('rejected').catch(function (e) { out.push(e); });";
|
||||
for sliced in [false, true] {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[]);
|
||||
if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
loop {
|
||||
match realm.advance(100).unwrap() {
|
||||
Progress::Paused => {}
|
||||
Progress::Done(value) => {
|
||||
assert_eq!(value, JsValue::Undefined);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
assert_eq!(realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap(), JsValue::Undefined);
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("body|resolved|rejected".into()), "sliced={sliced}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_a_module_discards_a_paused_script() {
|
||||
for (sliced, invalid) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let mut realm = es();
|
||||
realm.start("out.push('old');").unwrap();
|
||||
assert_eq!(realm.advance(1).unwrap(), Progress::Paused);
|
||||
let mut load = loader(&[]);
|
||||
let source = if invalid { "var = ;" } else { "out.push('new');" };
|
||||
if invalid {
|
||||
let result = if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load)
|
||||
} else {
|
||||
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).map(drop)
|
||||
};
|
||||
assert!(result.is_err());
|
||||
assert!(!realm.is_running(), "sliced={sliced}");
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String(String::new()));
|
||||
continue;
|
||||
}
|
||||
if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
loop {
|
||||
if let Progress::Done(_) = realm.advance(100).unwrap() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("new".into()), "sliced={sliced}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A loader over `files`: each specifier is its own key, given with its source the first time.
|
||||
fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result<LoadedModule, LoadError> + use<> {
|
||||
let map: HashMap<String, String> = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
let mut given = HashSet::new();
|
||||
move |_, specifier| {
|
||||
if !specifier.starts_with('.') && specifier != "main" {
|
||||
return Err(LoadError::Syntax(format!("bare specifier: {specifier}")));
|
||||
}
|
||||
let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?;
|
||||
let first = given.insert(specifier.to_string());
|
||||
Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`.
|
||||
fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result<JsValue, RunError>, String) {
|
||||
let mut load = loader(files);
|
||||
let result = realm.run_module("main.mjs", entry, limits, &mut load);
|
||||
let out = match realm.run("out.join('|')") {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
(result, out)
|
||||
}
|
||||
|
||||
fn run(entry: &str, files: &[(&str, &str)]) -> String {
|
||||
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
|
||||
(Ok(v), out) => {
|
||||
assert_eq!(v, JsValue::Undefined);
|
||||
out
|
||||
}
|
||||
(Err(e), _) => panic!("{entry}\n{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The run ends with an error whose message starts with `start`, and `out` holds `ran`.
|
||||
fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError {
|
||||
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
|
||||
(Err(e), out) => {
|
||||
assert!(e.message.starts_with(start), "{entry}: {e:?}");
|
||||
assert_eq!(out, ran, "{entry}");
|
||||
e
|
||||
}
|
||||
(Ok(_), out) => panic!("{entry}: completed with {out}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn syntax(src: &str) {
|
||||
assert!(parse_module(src, &Options::default()).is_err(), "{src}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_reads_the_exporting_binding_each_time() {
|
||||
let counter = "export let count = 0; export function inc() { count++; }";
|
||||
let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]);
|
||||
assert_eq!(out, "0|2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_can_be_renamed_and_combined() {
|
||||
let m = "export default 'd'; export var a = 1; export const b = 2;";
|
||||
let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "d|1|2");
|
||||
let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "d|1|d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destructuring_declaration_exports_every_name_it_binds() {
|
||||
let m = "export const { a, b: [c, ...d] } = { a: 1, b: [2, 3, 4] }; export var [e = 5] = [];";
|
||||
let out = run("import { a, c, d, e } from './m.mjs'; out.push(a, c, d.join('+'), e);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "1|2|3+4|5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_exports_of_expressions_and_functions() {
|
||||
let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]);
|
||||
assert_eq!(out, "42");
|
||||
let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]);
|
||||
assert_eq!(out, "anon");
|
||||
// A named default function is a declaration: hoisted, and its name is bound in the module.
|
||||
let f = "out.push(typeof g); export default function g() { return 'g'; }";
|
||||
let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]);
|
||||
assert_eq!(out, "function|g");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() {
|
||||
let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null);
|
||||
try { ns.alpha = 5; } catch (e) { out.push(e.name); }
|
||||
try { ns.added = 5; } catch (e) { out.push(e.name); }
|
||||
try { delete ns.alpha; } catch (e) { out.push(e.name); }
|
||||
out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() {
|
||||
let m = "export var alpha = 1;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
var o = Object.create(ns);
|
||||
Object.defineProperty(o, 'own', { value: 1, writable: true });
|
||||
o.own = 2;
|
||||
try { o.alpha = 5; } catch (e) { out.push(e.name); }
|
||||
try { o.fresh = 5; } catch (e) { out.push(e.name); }
|
||||
try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); }
|
||||
out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1");
|
||||
// A script's sloppy write is ignored.
|
||||
let mut realm = es();
|
||||
let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default());
|
||||
assert_eq!(out, (Ok(JsValue::Undefined), String::new()));
|
||||
// A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`.
|
||||
let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \
|
||||
[own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()";
|
||||
assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_takes_only_definitions_that_change_nothing() {
|
||||
let m = "export var a = 1;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns));
|
||||
out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns);
|
||||
var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }];
|
||||
for (var i = 0; i < ds.length; i++) {
|
||||
try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); }
|
||||
}
|
||||
try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); }
|
||||
try { Object.freeze(ns); } catch (e) { out.push(e.name); }
|
||||
out.push(ns.a);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_reads_live_values() {
|
||||
let m = "export var n = 1; export function bump() { n = n + 1; }";
|
||||
let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_to_an_import_is_a_type_error() {
|
||||
let m = "export var a = 1;";
|
||||
let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "TypeError|1");
|
||||
let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_of_two_modules_runs_each_once_dependency_first() {
|
||||
// main imports b, b imports main back: b runs first and sees main's hoisted function.
|
||||
let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';";
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./b.mjs", b), ("main", "")]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) }
|
||||
};
|
||||
let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);";
|
||||
let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_an_import_before_its_module_ran_is_a_reference_error() {
|
||||
let b = "import { a } from 'main'; out.push('b'); out.push(a);";
|
||||
let mut realm = es();
|
||||
let mut inner = loader(&[("./b.mjs", b)]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
|
||||
match r {
|
||||
Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() {
|
||||
let b = "import * as ns from 'main';
|
||||
var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'),
|
||||
() => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns),
|
||||
() => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns),
|
||||
() => Object.create(ns).a, () => Object.create(Object.create(ns)).a];
|
||||
tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } });
|
||||
// Listing the export names reads none of them.
|
||||
var names = [];
|
||||
for (var k in ns) names.push(k);
|
||||
out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());";
|
||||
let mut realm = es();
|
||||
let mut inner = loader(&[("./b.mjs", b)]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
let errors = "ReferenceError|".repeat(13);
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_two_modules_import_runs_once() {
|
||||
let shared = "out.push('shared'); export var s = 1;";
|
||||
let a = "import { s } from './shared.mjs'; out.push('a' + s);";
|
||||
let b = "import { s } from './shared.mjs'; out.push('b' + s);";
|
||||
let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]);
|
||||
assert_eq!(out, "shared|a1|b1|main");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn re_exports_pass_names_on() {
|
||||
let base = "export var x = 1, y = 2; export default 'base';";
|
||||
let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';";
|
||||
let out = run(
|
||||
"import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));",
|
||||
&[("./base.mjs", base), ("./mid.mjs", mid)],
|
||||
);
|
||||
// `export *` does not pass `default` on.
|
||||
assert_eq!(out, "1|1|2|base|all,renamed,x,y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_import_is_a_re_export() {
|
||||
let base = "export var v = 'v';";
|
||||
let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };";
|
||||
let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]);
|
||||
assert_eq!(out, "v|v");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_two_stars_give_is_ambiguous() {
|
||||
let files =
|
||||
[("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")];
|
||||
fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", "");
|
||||
// The namespace leaves the name out.
|
||||
let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files);
|
||||
assert_eq!(out, "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_export_ends_the_run_before_any_module_runs() {
|
||||
let files = [("./m.mjs", "out.push('m'); export var a = 1;")];
|
||||
let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", "");
|
||||
assert_eq!((e.line, e.column), (1, 10));
|
||||
let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")];
|
||||
fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_loader_cannot_give_is_named_in_the_error() {
|
||||
let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", "");
|
||||
assert_eq!(e.line, 2);
|
||||
fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_syntax_error_in_an_imported_module_names_its_source() {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]);
|
||||
let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load);
|
||||
let e = r.err().unwrap_or_else(|| panic!("ran"));
|
||||
assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2));
|
||||
// The entry is source 0, then each module in the order it was loaded.
|
||||
assert_eq!(realm.error_source(), 2);
|
||||
assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_code_is_strict_and_its_this_is_undefined() {
|
||||
let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]);
|
||||
assert_eq!(out, "true|true|ReferenceError");
|
||||
// Its declarations stay in the module.
|
||||
let mut realm = es();
|
||||
let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default());
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() {
|
||||
let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")];
|
||||
fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_count_and_import_depth_are_limited() {
|
||||
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")];
|
||||
let mut realm = es();
|
||||
let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}");
|
||||
assert_eq!(out, "");
|
||||
let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}");
|
||||
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 });
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() {
|
||||
let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")];
|
||||
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_limit_of_zero_runs_no_module() {
|
||||
let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}");
|
||||
assert_eq!(out, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_run_is_held_to_the_fuel_limit() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() });
|
||||
let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]);
|
||||
let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]);
|
||||
let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');";
|
||||
assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(()));
|
||||
let mut slices = 0;
|
||||
loop {
|
||||
match realm.advance(10) {
|
||||
Ok(Progress::Paused) => slices += 1,
|
||||
Ok(Progress::Done(v)) => {
|
||||
assert_eq!(v, JsValue::Undefined);
|
||||
break;
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(slices > 20, "{slices}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_es5_realm_runs_no_module() {
|
||||
let mut realm = Realm::new();
|
||||
let mut load = loader(&[]);
|
||||
let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_does_not_read_import_or_export() {
|
||||
for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] {
|
||||
assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}");
|
||||
assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_early_errors() {
|
||||
for src in [
|
||||
"export var a; export { a };",
|
||||
"export { undeclared };",
|
||||
"export default 1; export default 2;",
|
||||
"import { a } from './x.mjs'; var a;",
|
||||
"var a; import a from './x.mjs';",
|
||||
"import { a, a } from './x.mjs';",
|
||||
"function f() { import a from './x.mjs'; }",
|
||||
"{ export var a; }",
|
||||
"import { default } from './x.mjs';",
|
||||
"export { default };",
|
||||
"import a from x;",
|
||||
"import * from './x.mjs';",
|
||||
"with (a) {}",
|
||||
"export default class {}",
|
||||
"import('./x.mjs');",
|
||||
"#include 'x.js'\n",
|
||||
// Top-level functions are lexical declarations in a module.
|
||||
"function f() {} function f() {}",
|
||||
"var f; function f() {}",
|
||||
"function f() {} var f;",
|
||||
"let f; function f() {}",
|
||||
] {
|
||||
syntax(src);
|
||||
}
|
||||
for src in [
|
||||
"import { default as d, if as i } from './x.mjs'; export { d as default, i as if };",
|
||||
"import {} from './x.mjs'; export {};",
|
||||
"export function f() {} export { f as g };",
|
||||
"var as = 1, from = 2; export { as, from };",
|
||||
"export * as default from './x.mjs';",
|
||||
"function f() {} { function f() {} } function g() { var g; function h() {} var h; }",
|
||||
] {
|
||||
assert!(parse_module(src, &Options::default()).is_ok(), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_lists_what_it_imports_and_exports() {
|
||||
let (_, info) =
|
||||
match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default())
|
||||
{
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect();
|
||||
assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]);
|
||||
assert_eq!(info.imports.len(), 2);
|
||||
assert!(
|
||||
matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() {
|
||||
let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';";
|
||||
let (_, info) = match parse_module(src, &Options::default()) {
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect();
|
||||
let dot = [u16::from(b'.'), u16::from(b'/')];
|
||||
let ext: Vec<u16> = ".mjs".encode_utf16().collect();
|
||||
let with = |u: u16| [&dot[..], &[u], &ext[..]].concat();
|
||||
assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]);
|
||||
assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs");
|
||||
// The run stops when the module is to be loaded, before any module runs, and the loader is
|
||||
// not asked for it.
|
||||
let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", "");
|
||||
assert_eq!(e.line, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_of_many_exports_lists_each_once_in_order() {
|
||||
let names: Vec<String> = (0..3000).rev().map(|i| format!("e{i}")).collect();
|
||||
let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect();
|
||||
let star = "export * from './m.mjs'; export var e5 = 'own';";
|
||||
let out = run(
|
||||
"import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);",
|
||||
&[("./m.mjs", m.as_str()), ("./star.mjs", star)],
|
||||
);
|
||||
assert_eq!(out, "3000|e0|e999|own|e2999");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_survive_a_collection_while_they_link() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() });
|
||||
assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok());
|
||||
let m = "export var v = 'kept'; export function f() { return v; }";
|
||||
let mut load = loader(&[("./m.mjs", m)]);
|
||||
// A collection runs at every heap reservation while the modules load and link, before any
|
||||
// of their code runs.
|
||||
let before = realm.interp().heap.collections;
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let started = realm.start_module(
|
||||
"main.mjs",
|
||||
"import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());",
|
||||
ModuleLimits::default(),
|
||||
&mut load,
|
||||
);
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert_eq!(started, Ok(()));
|
||||
assert!(realm.interp().heap.collections > before);
|
||||
assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined))));
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_heap_counts_each_module_from_when_it_loads() {
|
||||
// Each module holds about 4 MB of code (its text and its string). The heap holds one of them,
|
||||
// and not two, so the run stops while the second loads and never asks for the third.
|
||||
let body = format!("export var v = '{}';", "x".repeat(1_000_000));
|
||||
let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() };
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
|
||||
assert!(realm.run("var out = [];").is_ok());
|
||||
let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default());
|
||||
assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string()));
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
|
||||
let asked = std::cell::RefCell::new(Vec::new());
|
||||
let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
asked.borrow_mut().push(specifier.to_string());
|
||||
inner(referrer, specifier)
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}");
|
||||
assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_keeps_no_expression_value_alive_after_its_statement() {
|
||||
// The heap holds one of these arrays and not two, so each must be collectable once the
|
||||
// expression statement that made it ends.
|
||||
let big = "function big() { var a = []; for (var i = 0; i < 50000; i++) a[i] = { i: i }; return a; }";
|
||||
let mut realm = es();
|
||||
assert!(realm.run(&format!("{big} var held = big();")).is_ok());
|
||||
let with_one = realm.collect_garbage();
|
||||
assert!(realm.run("held = null;").is_ok());
|
||||
let without = realm.collect_garbage();
|
||||
let one = with_one - without;
|
||||
realm.set_limits(Limits { heap_bytes: without + one * 3 / 2, ..Limits::default() });
|
||||
let entry = format!("{big} big(); big(); try {{ big(); }} finally {{ big(); }} out.push('done');");
|
||||
let (r, out) = run_with(&mut realm, &entry, &[], ModuleLimits::default());
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "done"));
|
||||
// Script and eval code still complete with the value of their last expression statement.
|
||||
assert_eq!(realm.run("1; 2;"), Ok(JsValue::Number(2.0)));
|
||||
assert_eq!(realm.run("eval('3; 4;')"), Ok(JsValue::Number(4.0)));
|
||||
assert_eq!(realm.run("try { 5; } finally { 6; }"), Ok(JsValue::Number(5.0)));
|
||||
}
|
||||
+41
-10
@@ -7,6 +7,7 @@
|
||||
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
|
||||
//! runs of them do not nest at all.
|
||||
|
||||
mod module;
|
||||
mod pattern;
|
||||
mod xml;
|
||||
|
||||
@@ -68,14 +69,23 @@ struct Scope {
|
||||
|
||||
/// What `super` and `new.target` may do where the parser is (ECMA-262 2015 sections 12.3.5.1,
|
||||
/// 12.3.8.1, 14.1.2, 14.5.1 and 15.1.1): set for each function body and kept by arrow functions.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct SuperRules {
|
||||
/// Eval code run by a direct `eval` has the rules of the code that calls it (section 18.2.1.1).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct SuperRules {
|
||||
/// `super.property` and `super[index]`: in a class's methods, accessors and constructor.
|
||||
property: bool,
|
||||
pub(crate) property: bool,
|
||||
/// `super(arguments)`: in a derived class's constructor.
|
||||
call: bool,
|
||||
pub(crate) call: bool,
|
||||
/// `new.target`: in any function other than an arrow function at the top of a script.
|
||||
new_target: bool,
|
||||
pub(crate) new_target: bool,
|
||||
}
|
||||
|
||||
impl SuperRules {
|
||||
/// The rules in the body of a function that is not an arrow function: `home` for one with a
|
||||
/// home object, `derived` for a derived class's constructor.
|
||||
pub(crate) fn function(home: bool, derived: bool) -> Self {
|
||||
Self { property: home, call: derived, new_target: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of a function as they are read: names or patterns, each one's default value,
|
||||
@@ -125,6 +135,9 @@ pub(crate) struct Parser<'s> {
|
||||
scopes: Vec<Scope>,
|
||||
/// What `super` and `new.target` may do in the function being read.
|
||||
supers: SuperRules,
|
||||
/// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical
|
||||
/// declarations (ECMA-262 2015 section 15.2.1.11).
|
||||
module: bool,
|
||||
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
|
||||
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
|
||||
cover_inits: Vec<u32>,
|
||||
@@ -166,6 +179,7 @@ impl<'s> Parser<'s> {
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
supers: SuperRules::default(),
|
||||
module: false,
|
||||
cover_inits: Vec::new(),
|
||||
cover_ok: false,
|
||||
rest_commas: HashSet::new(),
|
||||
@@ -176,9 +190,12 @@ impl<'s> Parser<'s> {
|
||||
Ok(parser)
|
||||
}
|
||||
|
||||
/// Allows `new.target` at the top of the source: eval code run inside a function.
|
||||
pub(crate) fn with_new_target(mut self) -> Self {
|
||||
self.supers.new_target = self.es2015;
|
||||
/// Reads the top of the source with `rules`: eval code run by a direct `eval` inside a
|
||||
/// function. Without [`crate::Options::es2015`] the rules stay the default.
|
||||
pub(crate) fn with_supers(mut self, rules: SuperRules) -> Self {
|
||||
if self.es2015 {
|
||||
self.supers = rules;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -190,7 +207,15 @@ impl<'s> Parser<'s> {
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 };
|
||||
let program = Program {
|
||||
ast: self.ast,
|
||||
body,
|
||||
strict: self.ctx.strict,
|
||||
directives: self.directives,
|
||||
lines: self.lines,
|
||||
es2015: self.es2015,
|
||||
supers: self.supers,
|
||||
};
|
||||
Ok((program, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -312,6 +337,9 @@ impl<'s> Parser<'s> {
|
||||
/// Checks a name used as an identifier: not a reserved word written with escapes, and not a
|
||||
/// strict-mode reserved word in strict code.
|
||||
fn check_identifier(&self, token: &Token, name: &str) -> Result<()> {
|
||||
if self.module && name == "await" {
|
||||
return Err(self.error_at_token(token, "'await' is a reserved word in modules"));
|
||||
}
|
||||
if token.escaped && Keyword::from_word(name).is_some() {
|
||||
return Err(self.error_at_token(token, format!("keyword '{name}' must not contain escaped characters")));
|
||||
}
|
||||
@@ -411,6 +439,9 @@ impl<'s> Parser<'s> {
|
||||
/// body or the script, lexical in a block.
|
||||
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
|
||||
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
|
||||
if self.module && self.scopes.len() == 1 {
|
||||
return self.declare_lexical(&name, true);
|
||||
}
|
||||
match self.scopes.last_mut() {
|
||||
Some(scope) if scope.function => {
|
||||
if scope.lexical.contains_key(&name.name) {
|
||||
@@ -1149,7 +1180,7 @@ impl<'s> Parser<'s> {
|
||||
generator: bool,
|
||||
) -> Result<crate::ast::FunctionId> {
|
||||
self.enter()?;
|
||||
let rules = SuperRules { property: home, call: kind == FunctionKind::DerivedConstructor, new_target: true };
|
||||
let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor);
|
||||
let outer = std::mem::replace(&mut self.supers, rules);
|
||||
// The parameters are read with the function's own `yield` rule, not the enclosing code's.
|
||||
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a
|
||||
//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1).
|
||||
//!
|
||||
//! A module is strict mode code throughout. An import binds its names as lexical declarations at
|
||||
//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name
|
||||
//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an
|
||||
//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be
|
||||
//! exported once, and a name an `export { … }` list exports from the module itself must be one it
|
||||
//! declares or imports.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{Parser, Result, describe};
|
||||
use crate::ast::{
|
||||
Binding, DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId,
|
||||
VarDecl,
|
||||
};
|
||||
use crate::token::{Keyword, Punct, Span, Token, TokenKind};
|
||||
|
||||
/// A name an `export { … }` list without `from` exports: the module's own binding (or import)
|
||||
/// `local`, exported as `export_name`.
|
||||
struct ClauseExport {
|
||||
export_name: String,
|
||||
local: String,
|
||||
span: Span,
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
struct RequestUnits(Vec<u16>);
|
||||
|
||||
impl std::hash::Hash for RequestUnits {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(&self.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for RequestUnits {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
REQUEST_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
struct ImportLocal<'a>(&'a str);
|
||||
|
||||
impl std::hash::Hash for ImportLocal<'_> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(self.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ImportLocal<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
EXPORT_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static REQUEST_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static EXPORT_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
/// Reads the source as a module: its statements, without its import and export declarations
|
||||
/// but with the declarations they export, and what it imports and exports.
|
||||
pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec<Token>)> {
|
||||
self.module = true;
|
||||
#[cfg(test)]
|
||||
REQUEST_SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let mut info = ModuleInfo::default();
|
||||
let mut requests = HashMap::new();
|
||||
let mut clause = Vec::new();
|
||||
let mut body = Vec::new();
|
||||
while self.tok.kind != TokenKind::Eof {
|
||||
if self.at_keyword(Keyword::Import) {
|
||||
self.import_declaration(&mut info, &mut requests)?;
|
||||
} else if self.at_keyword(Keyword::Export) {
|
||||
if let Some(stmt) = self.export_declaration(&mut info, &mut clause, &mut requests)? {
|
||||
body.push(stmt);
|
||||
}
|
||||
} else {
|
||||
body.push(self.parse_statement_item()?);
|
||||
}
|
||||
}
|
||||
self.finish_exports(&mut info, clause)?;
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program =
|
||||
Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015, supers: self.supers };
|
||||
Ok((program, info, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// The current token is the contextual keyword `word` (`as` or `from`), written without escapes.
|
||||
fn at_contextual(&self, word: &str) -> bool {
|
||||
self.tok.ident() == Some(word) && !self.tok.escaped
|
||||
}
|
||||
|
||||
fn expect_contextual(&mut self, word: &str) -> Result<()> {
|
||||
if self.at_contextual(word) {
|
||||
self.bump()?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok))))
|
||||
}
|
||||
|
||||
/// A module specifier: a string literal, added to the module's requests once. → its index.
|
||||
/// Any string value is a specifier here; the host decides which it can load.
|
||||
fn module_specifier(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<usize> {
|
||||
let TokenKind::String(units) = &self.tok.kind else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok))));
|
||||
};
|
||||
if self.tok.legacy_octal {
|
||||
return Err(self.error_at_token(&self.tok, "octal escape sequences are not allowed in strict mode"));
|
||||
}
|
||||
let units = RequestUnits(units.to_vec());
|
||||
let span = self.bump()?.span;
|
||||
if let Some(index) = requests.get(&units) {
|
||||
return Ok(*index);
|
||||
}
|
||||
let specifier = String::from_utf16_lossy(&units.0);
|
||||
let index = info.requests.len();
|
||||
info.requests.push(ModuleRequest { specifier, units: units.0.clone(), span });
|
||||
requests.insert(units, index);
|
||||
Ok(info.requests.len() - 1)
|
||||
}
|
||||
|
||||
/// A name as an import or export list gives it: any identifier name, keywords included. → the
|
||||
/// name and whether it was an identifier (not a keyword).
|
||||
fn list_name(&mut self) -> Result<(Name, bool)> {
|
||||
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok))));
|
||||
};
|
||||
let ident = matches!(self.tok.kind, TokenKind::Ident(_));
|
||||
let token = self.bump()?;
|
||||
Ok((Name { name, span: token.span }, ident))
|
||||
}
|
||||
|
||||
/// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope.
|
||||
fn import_declaration(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<()> {
|
||||
let import = self.bump()?;
|
||||
if self.at(Punct::LParen) {
|
||||
return Err(self.error_at_token(&import, "import() is not supported"));
|
||||
}
|
||||
if matches!(self.tok.kind, TokenKind::String(_)) {
|
||||
self.module_specifier(info, requests)?;
|
||||
return self.semicolon();
|
||||
}
|
||||
let mut bound: Vec<(ImportName, Name)> = Vec::new();
|
||||
let mut list = true;
|
||||
if matches!(self.tok.kind, TokenKind::Ident(_)) {
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name("default".into()), local));
|
||||
list = self.eat(Punct::Comma)?;
|
||||
}
|
||||
if list {
|
||||
if self.eat(Punct::Star)? {
|
||||
self.expect_contextual("as")?;
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Namespace, local));
|
||||
} else {
|
||||
self.expect(Punct::LBrace)?;
|
||||
while !self.at(Punct::RBrace) {
|
||||
if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() {
|
||||
// A name without `as` binds itself, so it must be one a declaration may bind.
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name(local.name.clone()), local));
|
||||
} else {
|
||||
let (imported, _) = self.list_name()?;
|
||||
self.expect_contextual("as")?;
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name(imported.name), local));
|
||||
}
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RBrace)?;
|
||||
}
|
||||
}
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
for (import, local) in bound {
|
||||
self.declare_lexical(&local, false)?;
|
||||
info.imports.push(ImportEntry { request, import, local });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The token after the current one is the contextual keyword `as`.
|
||||
fn next_is_as(&self) -> bool {
|
||||
self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as"))
|
||||
}
|
||||
|
||||
/// `export …` (section 15.2.3). → the declaration it exports, which runs in place.
|
||||
fn export_declaration(
|
||||
&mut self,
|
||||
info: &mut ModuleInfo,
|
||||
clause: &mut Vec<ClauseExport>,
|
||||
requests: &mut HashMap<RequestUnits, usize>,
|
||||
) -> Result<Option<StmtId>> {
|
||||
let export = self.bump()?;
|
||||
let span = export.span;
|
||||
if self.eat(Punct::Star)? {
|
||||
if self.at_contextual("as") {
|
||||
self.bump()?;
|
||||
let (name, _) = self.list_name()?;
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span });
|
||||
return Ok(None);
|
||||
}
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
info.exports.push(ExportEntry::Star { request, span });
|
||||
return Ok(None);
|
||||
}
|
||||
if self.at(Punct::LBrace) {
|
||||
self.bump()?;
|
||||
// Each name: the name it refers to (and whether that was an identifier) and the name it
|
||||
// is exported as.
|
||||
let mut names: Vec<(Name, bool, Name)> = Vec::new();
|
||||
while !self.at(Punct::RBrace) {
|
||||
let (local, ident) = self.list_name()?;
|
||||
let exported = if self.at_contextual("as") {
|
||||
self.bump()?;
|
||||
self.list_name()?.0
|
||||
} else {
|
||||
local.clone()
|
||||
};
|
||||
names.push((local, ident, exported));
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RBrace)?;
|
||||
if self.at_contextual("from") {
|
||||
self.bump()?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
for (local, _, exported) in names {
|
||||
let import = ImportName::Name(local.name);
|
||||
info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
self.semicolon()?;
|
||||
for (local, ident, exported) in names {
|
||||
// Without `from`, each name refers to a binding of the module (section 15.2.3.1).
|
||||
if !ident || crate::token::strict_reserved(&local.name) {
|
||||
return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name)));
|
||||
}
|
||||
clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
if self.at_keyword(Keyword::Default) {
|
||||
self.bump()?;
|
||||
return self.export_default(info, span).map(Some);
|
||||
}
|
||||
let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some();
|
||||
if !exportable {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok))));
|
||||
}
|
||||
let stmt = self.parse_statement_item()?;
|
||||
let names: Vec<Name> = match self.ast.stmt(stmt) {
|
||||
Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).collect(),
|
||||
Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(),
|
||||
_ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")),
|
||||
};
|
||||
for name in names {
|
||||
info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span });
|
||||
}
|
||||
Ok(Some(stmt))
|
||||
}
|
||||
|
||||
/// `export default …` after `default`: a function declaration (named or not) or an expression.
|
||||
fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result<StmtId> {
|
||||
if self.at_keyword(Keyword::Class) {
|
||||
return Err(self.error_at_token(&self.tok, "classes are not supported"));
|
||||
}
|
||||
if self.at_keyword(Keyword::Function) {
|
||||
self.enter()?;
|
||||
let result = self.default_function();
|
||||
self.leave();
|
||||
let (stmt, fid, local) = result?;
|
||||
self.declare_function(fid)?;
|
||||
info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span });
|
||||
return Ok(stmt);
|
||||
}
|
||||
let start = self.tok.span;
|
||||
let value = self.parse_assignment(false)?;
|
||||
self.semicolon()?;
|
||||
let target = Binding::Name(Name { name: DEFAULT_BINDING.into(), span: start });
|
||||
let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { target, init: Some(value) }]), self.span_from(start));
|
||||
info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span });
|
||||
Ok(stmt)
|
||||
}
|
||||
|
||||
/// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of
|
||||
/// `name`, or of [`DEFAULT_BINDING`] for a function without one.
|
||||
fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> {
|
||||
let keyword = self.expect_keyword(Keyword::Function)?;
|
||||
let start = keyword.span;
|
||||
let generator = self.es2015 && self.eat(Punct::Star)?;
|
||||
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) {
|
||||
self.function_name()?
|
||||
} else {
|
||||
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
|
||||
};
|
||||
let local = name.0.name.clone();
|
||||
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
|
||||
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
|
||||
Ok((stmt, fid, local))
|
||||
}
|
||||
|
||||
/// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and
|
||||
/// each name an `export { … }` list takes from the module itself declared or imported there. An
|
||||
/// exported named import becomes a re-export of its imported binding (section 15.2.1.16.1).
|
||||
/// A namespace import keeps its local binding.
|
||||
fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec<ClauseExport>) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
EXPORT_SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let mut imports = HashMap::with_capacity(info.imports.len());
|
||||
for import in &info.imports {
|
||||
imports.entry(ImportLocal(&import.local.name)).or_insert(import);
|
||||
}
|
||||
let top = self.scopes.first();
|
||||
for c in clause {
|
||||
let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local));
|
||||
if !declared {
|
||||
return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local)));
|
||||
}
|
||||
let imported = imports.get(&ImportLocal(&c.local));
|
||||
let entry = match imported {
|
||||
Some(i) if matches!(&i.import, ImportName::Name(_)) => {
|
||||
ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }
|
||||
}
|
||||
_ => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span },
|
||||
};
|
||||
info.exports.push(entry);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for e in &info.exports {
|
||||
let (name, span) = match e {
|
||||
ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span),
|
||||
ExportEntry::Star { .. } => continue,
|
||||
};
|
||||
if !seen.insert(name.as_str()) {
|
||||
return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{EXPORT_SEARCH_STEPS, REQUEST_SEARCH_STEPS};
|
||||
use crate::{Options, parse_module};
|
||||
|
||||
fn run_namespace_modules(main: &str, files: &[(&str, &str)]) -> (Result<crate::JsValue, crate::RunError>, crate::Realm) {
|
||||
let mut realm = crate::Realm::with_options(Options { es2015: true, ..Options::default() }, crate::Limits::default());
|
||||
realm.run("var out = [];").unwrap();
|
||||
let mut load = |_: &str, specifier: &str| {
|
||||
files.iter().find(|(name, _)| *name == specifier).map_or_else(
|
||||
|| Err(crate::LoadError::Other(format!("missing module {specifier}"))),
|
||||
|(_, source)| Ok(crate::LoadedModule { key: specifier.into(), source: Some((*source).into()) }),
|
||||
)
|
||||
};
|
||||
let result = realm.run_module("main.mjs", main, crate::ModuleLimits::default(), &mut load);
|
||||
(result, realm)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_reexport_bindings_keep_their_origin() {
|
||||
let files = [
|
||||
("./a.mjs", "import * as ns from './shared.mjs'; export {ns};"),
|
||||
("./b.mjs", "import * as ns from './shared.mjs'; export {ns};"),
|
||||
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
|
||||
("./shared.mjs", "export var value = 7;"),
|
||||
];
|
||||
let (result, _) = run_namespace_modules("import {ns} from './barrel.mjs'; out.push(ns.value);", &files);
|
||||
assert!(result.as_ref().is_err_and(|error| error.message.contains("ambiguous")), "{result:?}");
|
||||
let files = [
|
||||
("./a.mjs", "import {value} from './shared.mjs'; export {value};"),
|
||||
("./b.mjs", "import {value} from './shared.mjs'; export {value};"),
|
||||
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
|
||||
("./shared.mjs", "export var value = 7; export function change() { value = 9; }"),
|
||||
];
|
||||
let (result, mut realm) =
|
||||
run_namespace_modules("import {value} from './barrel.mjs'; import {change} from './shared.mjs'; change(); out.push(value);", &files);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("9".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_reexports_link_through_cycles() {
|
||||
let files = [("./a.mjs", "import * as ns from './b.mjs'; export {ns};"), ("./b.mjs", "import * as ns from './a.mjs'; export {ns};")];
|
||||
let (result, mut realm) = run_namespace_modules("import * as a from './a.mjs'; out.push(a.ns.ns === a);", &files);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_specifiers_reject_legacy_octal_escapes() {
|
||||
for source in
|
||||
[r"import './\141.mjs';", r"import value from './\141.mjs';", r"export * from './\141.mjs';", r"export { value } from './\141.mjs';"]
|
||||
{
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
for source in [r"import './\u0061.mjs';", r"export * from './\x61.mjs';", r"import './\uD800.mjs';"] {
|
||||
assert!(parse_module(source, &Options::default()).is_ok(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_request_search_work_is_bounded_by_request_count() {
|
||||
let count = 1_000;
|
||||
let mut source = String::new();
|
||||
for index in 0..count {
|
||||
source.push_str(&format!("import './{index}.mjs';"));
|
||||
}
|
||||
source.push_str(r"import './\u0030.mjs'; import './\uD800.mjs'; import './\uFFFD.mjs'; import './\uDC00.mjs'; import './\uD800.mjs';");
|
||||
let (_, info) = match parse_module(&source, &Options::default()) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => panic!("{error:?}"),
|
||||
};
|
||||
assert_eq!(info.requests.len(), count + 3);
|
||||
for (index, request) in info.requests.iter().take(count).enumerate() {
|
||||
assert_eq!(request.specifier, format!("./{index}.mjs"));
|
||||
}
|
||||
assert_eq!(info.requests[count].units[2], 0xD800);
|
||||
assert_eq!(info.requests[count + 1].units[2], 0xFFFD);
|
||||
assert_eq!(info.requests[count + 2].units[2], 0xDC00);
|
||||
let steps = REQUEST_SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
assert!(steps > 0, "the repeated requests compare their exact UTF-16 keys");
|
||||
assert!(steps <= 2 * (count + 5), "{steps} request-search steps for {} requests", count + 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_export_resolution_work_is_bounded_by_binding_count() {
|
||||
let count = 1_000;
|
||||
let bindings = (0..count).map(|index| format!("value as local{index}")).collect::<Vec<_>>().join(",");
|
||||
let exports = (0..count).map(|index| format!("local{index} as exported{index}")).collect::<Vec<_>>().join(",");
|
||||
let source = format!(
|
||||
"import {{{bindings}}} from './values.mjs'; import * as ns from './namespace.mjs'; export {{{exports},ns as namespace,local0 as again}};"
|
||||
);
|
||||
let (_, info) = match parse_module(&source, &Options::default()) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => panic!("{error:?}"),
|
||||
};
|
||||
assert_eq!(info.imports.len(), count + 1);
|
||||
assert_eq!(info.exports.len(), count + 2);
|
||||
for (index, export) in info.exports.iter().take(count).enumerate() {
|
||||
assert!(matches!(export, crate::ExportEntry::Indirect { export_name, request: 0, import: crate::ast::ImportName::Name(name), .. }
|
||||
if export_name == &format!("exported{index}") && name == "value"));
|
||||
}
|
||||
assert!(matches!(&info.exports[count], crate::ExportEntry::Local { export_name, local, .. } if export_name == "namespace" && local == "ns"));
|
||||
assert!(
|
||||
matches!(&info.exports[count + 1], crate::ExportEntry::Indirect { request: 0, import: crate::ast::ImportName::Name(name), .. } if name == "value")
|
||||
);
|
||||
let steps = EXPORT_SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
assert!(steps > 0);
|
||||
assert!(steps <= 3 * (count + 2), "{steps} import-local comparisons for {} exports", count + 2);
|
||||
for source in [
|
||||
"import {value as x} from './values.mjs'; export {x,x};",
|
||||
"import {value as x} from './values.mjs'; import * as x from './namespace.mjs';",
|
||||
] {
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user