mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge main into feat/scripts-startup-scripts
This commit is contained in:
199 files changed
+12399
-961
No files matched your search
Generated
+307
-24
@@ -123,10 +123,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cipher 0.4.4",
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
"cpubits",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
@@ -247,6 +258,17 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "apple-native-keyring-store"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02e465454e78fda6f7cd9dab7eb47518ca28c59b1bc392ca865af61452741dd3"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"log",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -606,6 +628,24 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -718,6 +758,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
@@ -808,6 +854,15 @@ dependencies = [
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.9.0"
|
||||
@@ -902,8 +957,18 @@ version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"crypto-common 0.1.7",
|
||||
"inout 0.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"inout 0.2.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -935,6 +1000,12 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "cmpv2"
|
||||
version = "0.2.0"
|
||||
@@ -953,7 +1024,7 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"spki",
|
||||
"x509-cert",
|
||||
@@ -1029,6 +1100,12 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1113,6 +1190,12 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -1216,12 +1299,12 @@ dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"hmac 0.12.1",
|
||||
"log",
|
||||
"png 0.17.16",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
@@ -1447,7 +1530,7 @@ dependencies = [
|
||||
"ruzstd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tar",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2154,7 +2237,7 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
@@ -2317,6 +2400,24 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -2335,7 +2436,7 @@ version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468",
|
||||
@@ -2378,11 +2479,23 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid 0.10.3",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "7.0.0"
|
||||
@@ -3597,13 +3710,31 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3645,6 +3776,15 @@ version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
@@ -4101,6 +4241,16 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inventory"
|
||||
version = "0.3.25"
|
||||
@@ -4458,6 +4608,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring-core"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "6.0.0"
|
||||
@@ -4721,7 +4880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4952,12 +5111,75 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-complex",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -6684,6 +6906,25 @@ dependencies = [
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "secret-service"
|
||||
version = "5.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8"
|
||||
dependencies = [
|
||||
"aes 0.9.4",
|
||||
"cbc",
|
||||
"futures-util",
|
||||
"getrandom 0.4.3",
|
||||
"hkdf",
|
||||
"hybrid-array",
|
||||
"num",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"sha2 0.11.1",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -6823,7 +7064,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6834,7 +7075,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6894,12 +7146,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.22.1",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
"pem",
|
||||
"rand_core 0.10.1",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"signature",
|
||||
"sigstore-types",
|
||||
"spki",
|
||||
@@ -6968,7 +7220,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"cmpv2",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"hex",
|
||||
"rand",
|
||||
@@ -7007,7 +7259,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"hex",
|
||||
"pem",
|
||||
"rustls-pki-types",
|
||||
@@ -8277,6 +8529,7 @@ dependencies = [
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"apple-native-keyring-store",
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-cdr",
|
||||
@@ -8290,12 +8543,15 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"hayro-ccitt",
|
||||
"heic-rs",
|
||||
"hmac 0.12.1",
|
||||
"image",
|
||||
"jxl-color",
|
||||
"jxl-grid",
|
||||
"jxl-oxide",
|
||||
"keyring-core",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -8305,6 +8561,7 @@ dependencies = [
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
@@ -8331,6 +8588,8 @@ dependencies = [
|
||||
"vectorcraft-tools",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
"windows-native-keyring-store",
|
||||
"zbus-secret-service-keyring-store",
|
||||
"zune-core",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
@@ -8479,7 +8738,7 @@ dependencies = [
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes 0.8.4",
|
||||
"chrono",
|
||||
"craft",
|
||||
"craft-image-codecs",
|
||||
@@ -8497,7 +8756,7 @@ dependencies = [
|
||||
"objc2-core-graphics",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"siphasher",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
@@ -8522,7 +8781,7 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
@@ -9464,6 +9723,19 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-native-keyring-store"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"keyring-core",
|
||||
"regex",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
@@ -9821,7 +10093,7 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"sha1",
|
||||
"signature",
|
||||
@@ -10041,6 +10313,17 @@ dependencies = [
|
||||
"zvariant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus-secret-service-keyring-store"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"secret-service",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus_macros"
|
||||
version = "5.19.0"
|
||||
|
||||
@@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
|
||||
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
|
||||
/// installed from now on there.
|
||||
/// installed from now on there. The key of the grants kept there is in the system's key store.
|
||||
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Plug-ins") {
|
||||
vectorcraft_engine::store::grant_keys::use_os_grant_keys();
|
||||
session.attach_plugin_store(dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="13" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="11" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 321 B After Width: | Height: | Size: 323 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 8H12A4 4 0 0 1 12 16H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M12 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M2 7H13A5 5 0 0 1 13 17H2Z" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 318 B After Width: | Height: | Size: 319 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="17" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="16" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 321 B After Width: | Height: | Size: 323 B |
@@ -406,8 +406,10 @@ impl Document {
|
||||
/// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A
|
||||
/// line at any other angle becomes a guide path with that line, on the guide's layer, named
|
||||
/// as the guide was; `sel` then holds the path as a selected object instead of the guide.
|
||||
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are.
|
||||
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) {
|
||||
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. Returns the ids
|
||||
/// of the guide paths it adds, in the order it adds them.
|
||||
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) -> Vec<NodeId> {
|
||||
let mut paths = vec![];
|
||||
for id in sel.guides.clone() {
|
||||
let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue };
|
||||
let (a, b) = match self.transformed_guide(&g, xf) {
|
||||
@@ -431,7 +433,9 @@ impl Document {
|
||||
}
|
||||
self.retain_guides(sel, |g| g.id != Some(id));
|
||||
sel.objects.push(path);
|
||||
paths.push(path);
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// The ruler guide node `g` names, if this document has it.
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! stay attached and deleted objects leave nothing stale behind.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::{Homography, Rect};
|
||||
use vectorcraft_geom::{Homography, Point, Rect};
|
||||
|
||||
use crate::{Node, NodeKind};
|
||||
use crate::symbols::SYMBOL_SQUARE;
|
||||
use crate::{Node, NodeKind, SymbolBoxes};
|
||||
|
||||
/// The plane an object in perspective lies on.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -58,6 +59,33 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners of the box a symbol instance or type is drawn in, on the page (top left, top
|
||||
/// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or
|
||||
/// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both
|
||||
/// through the projection of type or an instance in perspective. Joined by straight lines,
|
||||
/// they outline the box as drawn. When the projection sends a corner to infinity the corners
|
||||
/// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other
|
||||
/// objects and for type without bounds.
|
||||
pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> {
|
||||
let flat = match &self.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric);
|
||||
[(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y))
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
let b = t.bounds()?;
|
||||
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let Some(h) = self.projection() else { return Some(flat) };
|
||||
let [a, b, c, d] = flat.map(|p| h.apply(p));
|
||||
Some(match (a, b, c, d) {
|
||||
(Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d],
|
||||
_ => flat,
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An
|
||||
/// invertible `a` that the projection cannot follow removes it, and the art is drawn flat.
|
||||
pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) {
|
||||
|
||||
@@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2};
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
|
||||
mod area;
|
||||
mod attr_ranges;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod file_fonts;
|
||||
@@ -18,6 +19,9 @@ mod tabs_lists;
|
||||
mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
pub use attr_ranges::{
|
||||
AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE,
|
||||
};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! The ranges the character and paragraph style commands keep each numeric attribute to, checked
|
||||
//! in one place: the style commands check the attributes a call changes, and type a plug-in
|
||||
//! returns has every attribute checked.
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use super::{CharStyle, JustificationOptions, ParaStyle, TabStop};
|
||||
|
||||
/// Font size ([`CharStyle::size`]), in points.
|
||||
pub const FONT_SIZE: RangeInclusive<f64> = 0.1..=1296.0;
|
||||
/// Leading ([`CharStyle::leading`]) other than Auto, in points.
|
||||
pub const LEADING: RangeInclusive<f64> = 0.1..=5000.0;
|
||||
/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
|
||||
pub const CHAR_SCALE: RangeInclusive<f64> = 1.0..=10000.0;
|
||||
/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`],
|
||||
/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em.
|
||||
pub const CHAR_SPACING: RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points.
|
||||
pub const MAX_BASELINE_SHIFT: f64 = 1296.0;
|
||||
/// Character rotation ([`CharStyle::rotation`]), in degrees.
|
||||
pub const CHAR_ROTATION: RangeInclusive<f64> = -360.0..=360.0;
|
||||
/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
|
||||
pub const CHAR_MITER_LIMIT: RangeInclusive<f64> = 1.0..=500.0;
|
||||
/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points.
|
||||
pub const MAX_PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// An attribute outside the range the style commands keep it to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AttrRangeError {
|
||||
/// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`).
|
||||
pub key: String,
|
||||
/// What is wrong, naming the attribute.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for AttrRangeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AttrRangeError {}
|
||||
|
||||
fn out(key: &str, message: String) -> AttrRangeError {
|
||||
AttrRangeError { key: key.to_string(), message }
|
||||
}
|
||||
|
||||
/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside).
|
||||
fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
}
|
||||
|
||||
impl CharStyle {
|
||||
/// Checks each numeric attribute `check` names, by its JSON key, against the range the
|
||||
/// character style commands keep it to: size, leading, scales, tracking, kerning, baseline
|
||||
/// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert
|
||||
/// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the
|
||||
/// variable font axes. The first attribute out of its range is the error.
|
||||
pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> {
|
||||
for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] {
|
||||
if check(key) {
|
||||
within(key, value, *range.start(), *range.end())?;
|
||||
}
|
||||
}
|
||||
if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) {
|
||||
let (lo, hi) = (LEADING.start(), LEADING.end());
|
||||
return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto")));
|
||||
}
|
||||
let shift = MAX_BASELINE_SHIFT;
|
||||
for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] {
|
||||
if check(key) {
|
||||
within(key, value, -shift, shift)?;
|
||||
}
|
||||
}
|
||||
let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))];
|
||||
for (key, value) in spacing {
|
||||
if check(key)
|
||||
&& let Some(value) = value
|
||||
{
|
||||
within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?;
|
||||
}
|
||||
}
|
||||
if check("rotation") {
|
||||
within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?;
|
||||
}
|
||||
for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] {
|
||||
if check(key) {
|
||||
within(key, value, 0.0, super::MAX_AKI)?;
|
||||
}
|
||||
}
|
||||
if check("tsume") {
|
||||
within("tsume", self.tsume, 0.0, super::MAX_TSUME)?;
|
||||
}
|
||||
let hi = super::MAX_DIACRITIC_POSITION;
|
||||
for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] {
|
||||
if check(key) {
|
||||
within(key, value, -hi, hi)?;
|
||||
}
|
||||
}
|
||||
let lines = super::WARICHU_LINES;
|
||||
if check("warichuLines") && !lines.contains(&self.warichu_lines) {
|
||||
return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = super::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in
|
||||
[("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())]
|
||||
{
|
||||
if check(key) {
|
||||
within(key, value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("stroke_width") {
|
||||
within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("stroke_miter_limit") {
|
||||
within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?;
|
||||
}
|
||||
if check("stroke_dash")
|
||||
&& let Some(dash) = &self.stroke_dash
|
||||
{
|
||||
for value in &dash.pattern {
|
||||
within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("small_caps")
|
||||
&& let Some(value) = self.small_caps
|
||||
{
|
||||
within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?;
|
||||
}
|
||||
if check("fontAxes")
|
||||
&& let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite())
|
||||
{
|
||||
return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParaStyle {
|
||||
/// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its
|
||||
/// field, against the range the paragraph style commands keep it to: the indents and the space
|
||||
/// before and after, each Hyphenation option, each Justification option in `justification`
|
||||
/// (the options as given, since reading a paragraph style brings them into range) with
|
||||
/// Minimum, Desired and Maximum in order, and the number of tab stops with the position and
|
||||
/// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the
|
||||
/// error.
|
||||
pub fn check_ranges(
|
||||
&self,
|
||||
justification: Option<&JustificationOptions>,
|
||||
kept_tabs: &[TabStop],
|
||||
check: impl Fn(&str, Option<&str>) -> bool,
|
||||
) -> Result<(), AttrRangeError> {
|
||||
for (key, value) in [
|
||||
("left_indent", self.left_indent),
|
||||
("right_indent", self.right_indent),
|
||||
("first_line_indent", self.first_line_indent),
|
||||
("space_before", self.space_before),
|
||||
("space_after", self.space_after),
|
||||
] {
|
||||
if check(key, None) {
|
||||
within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &self.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, MAX_PARA_DISTANCE),
|
||||
] {
|
||||
if check("hyphenation", Some(field)) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if let Some(j) = justification {
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !check("justification", Some(field)) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if check("justification", Some("auto_leading")) {
|
||||
let (lo, hi) = JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("tabs", None) {
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if self.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(out("tabs", format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(out("tabs.leader", format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() {
|
||||
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
|
||||
}
|
||||
|
||||
/// The default character and paragraph styles are in range, and each number outside its range,
|
||||
/// one that is not a number included, is the error naming its attribute; an attribute the check
|
||||
/// is not asked about is not checked.
|
||||
#[test]
|
||||
fn style_ranges_name_the_attribute_out_of_range() {
|
||||
let all = |_: &str| true;
|
||||
assert_eq!(CharStyle::default().check_ranges(all), Ok(()));
|
||||
let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key);
|
||||
let d = CharStyle::default();
|
||||
assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into()));
|
||||
assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into()));
|
||||
assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into()));
|
||||
assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into()));
|
||||
assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into()));
|
||||
assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into()));
|
||||
assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into()));
|
||||
assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into()));
|
||||
let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect();
|
||||
assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into()));
|
||||
let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false });
|
||||
assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into()));
|
||||
assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(()));
|
||||
|
||||
let all = |_: &str, _: Option<&str>| true;
|
||||
let p = ParaStyle::default();
|
||||
assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(()));
|
||||
let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key);
|
||||
assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into()));
|
||||
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into()));
|
||||
let far = TabStop { position: -1.0, ..stop.clone() };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into()));
|
||||
assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop");
|
||||
let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() };
|
||||
assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into()));
|
||||
let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() };
|
||||
assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
|
||||
use super::file_fonts::*;
|
||||
|
||||
@@ -80,11 +80,28 @@ rustix = { workspace = true, features = ["std", "process"] }
|
||||
# (walkdir), so this adds no new crate.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
same-file = "1.0.6"
|
||||
# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below).
|
||||
windows-native-keyring-store = "1.1"
|
||||
|
||||
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
|
||||
rayon = { version = "1.12", optional = true }
|
||||
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
|
||||
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
|
||||
# Linux. All MIT OR Apache-2.0.
|
||||
hmac = "0.12.1"
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
getrandom = "0.4"
|
||||
keyring-core = "1.1"
|
||||
|
||||
# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same
|
||||
# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies]
|
||||
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill Area",
|
||||
[],
|
||||
None,
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
has_doc,
|
||||
sb_copy_region
|
||||
),
|
||||
|
||||
@@ -141,7 +141,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`)} 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`), 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)} 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}}",
|
||||
always,
|
||||
contrast
|
||||
),
|
||||
@@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
|
||||
.transpose()
|
||||
};
|
||||
let drawing;
|
||||
// Selected objects that share a color but draw it differently have no one answer.
|
||||
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) {
|
||||
// Selected objects that share a color but draw it differently have no one answer. While the
|
||||
// active tool paints with the proxy's color, the selection does not draw it.
|
||||
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) {
|
||||
let item = s.appearance_item();
|
||||
// Every painted object inside a selected group counts, as the proxy's color comes from all,
|
||||
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
|
||||
|
||||
@@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
// Without a choice nothing can fail.
|
||||
apply_open_policies_choosing(d, None).unwrap_or_default()
|
||||
apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
|
||||
@@ -879,10 +879,14 @@ impl ProfileQuestion {
|
||||
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
|
||||
/// choice tags the document after the policies ran. A choice for the other kind of question, or
|
||||
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
|
||||
/// to assign is not a profile of that model.
|
||||
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
|
||||
let working = cms::working_settings();
|
||||
let question = ProfileQuestion::of(d, &working);
|
||||
/// to assign is not a profile of that model. `working` is the settings snapshot the question is
|
||||
/// built from and the policies are read from.
|
||||
pub(crate) fn apply_open_policies_choosing(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
choice: Option<&ProfileChoice>,
|
||||
working: &ColorSettings,
|
||||
) -> Result<(Vec<String>, bool)> {
|
||||
let question = ProfileQuestion::of(d, working);
|
||||
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
|
||||
// A mismatch answer stands in for the policy of the document's color mode.
|
||||
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
|
||||
@@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({"name": name, "spot": spot}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The policies come from the settings snapshot the question was built from, not from the
|
||||
/// working settings as they are when the policies run.
|
||||
#[test]
|
||||
fn open_policies_use_the_snapshot_they_are_given() {
|
||||
let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string());
|
||||
let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() };
|
||||
let mut d = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
tagged(&mut d);
|
||||
let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap();
|
||||
assert!(changed, "the Off policy of the snapshot takes the profile off");
|
||||
assert_eq!(d.color_profiles.rgb, None);
|
||||
assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}");
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
|
||||
@@ -256,6 +256,11 @@ struct RasterOptions {
|
||||
dither: Option<String>,
|
||||
dither_amount: Option<u8>,
|
||||
transparency: Option<bool>,
|
||||
/// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by
|
||||
/// [`RasterOptions::transparency_dither`] (other formats do not check it).
|
||||
transparency_dither: Option<Value>,
|
||||
/// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is.
|
||||
transparency_dither_amount: Option<Value>,
|
||||
matte: Option<Value>,
|
||||
lossless: Option<bool>,
|
||||
lzw: Option<bool>,
|
||||
@@ -295,6 +300,26 @@ impl RasterOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not
|
||||
/// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error.
|
||||
fn transparency_dither(&self) -> Result<(Dither, u8)> {
|
||||
const IDS: &str = "none, diffusion, pattern or noise";
|
||||
let method = match &self.transparency_dither {
|
||||
None | Some(Value::Null) => PaletteOptions::default().transparency_dither,
|
||||
Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?,
|
||||
Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))),
|
||||
};
|
||||
let amount = match &self.transparency_dither_amount {
|
||||
None | Some(Value::Null) => 100,
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.filter(|n| *n <= 100)
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?,
|
||||
};
|
||||
Ok((method, amount))
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
if matches!(format, RasterFormat::Gif | RasterFormat::Png8) {
|
||||
(settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?;
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
|
||||
@@ -195,6 +195,20 @@ const TRANSPARENCY: FormatOption = FormatOption {
|
||||
description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER: FormatOption = FormatOption {
|
||||
name: "transparencyDither",
|
||||
ty: "string",
|
||||
default: "\"none\"",
|
||||
description: "with transparency, how partly transparent pixels are split between the transparent entry and their color: none (cut at half opacity), diffusion, pattern (8×8 ordered) or noise",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER_AMOUNT: FormatOption = FormatOption {
|
||||
name: "transparencyDitherAmount",
|
||||
ty: "integer",
|
||||
default: "100",
|
||||
description: "the diffusion transparency dither's strength 0–100 (0 cuts at half opacity; more than 100 is refused)",
|
||||
};
|
||||
|
||||
const MATTE: FormatOption = FormatOption {
|
||||
name: "matte",
|
||||
ty: "string",
|
||||
@@ -235,6 +249,8 @@ const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
DITHER,
|
||||
DITHER_AMOUNT,
|
||||
TRANSPARENCY,
|
||||
TRANSPARENCY_DITHER,
|
||||
TRANSPARENCY_DITHER_AMOUNT,
|
||||
MATTE,
|
||||
];
|
||||
|
||||
|
||||
@@ -884,14 +884,16 @@ impl ReadFile {
|
||||
if self.rest.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// One snapshot of the working settings serves the reply and the policies.
|
||||
let working = vectorcraft_color::cms::working_settings();
|
||||
// The question the answer was given to, for the reply's `profileChoice`.
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings());
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working);
|
||||
let answered = match (&self.choice, &question) {
|
||||
(Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })),
|
||||
_ => None,
|
||||
};
|
||||
// A failure leaves the file waiting, unchanged.
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?;
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?;
|
||||
let Some(rest) = self.rest.take() else { return Ok(()) };
|
||||
self.answered = answered;
|
||||
self.loaded.warnings.extend(notes);
|
||||
|
||||
@@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shares of opaque pixels in the left and right halves of a 40×30 image file.
|
||||
fn opaque_halves(file: &[u8]) -> [f64; 2] {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
assert_eq!(img.dimensions(), (40, 30));
|
||||
let alpha: Vec<u8> = img.to_rgba8().chunks(4).map(|p| p[3]).collect();
|
||||
[0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0)
|
||||
}
|
||||
|
||||
/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`.
|
||||
#[test]
|
||||
fn palette_exports_take_the_transparency_dither() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 25})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 75})).unwrap();
|
||||
for format in ["gif", "png8"] {
|
||||
let mut file = |extra: Value| {
|
||||
let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra);
|
||||
b64(&s.execute("document.export", &p).unwrap())
|
||||
};
|
||||
// By default the pixels under half opacity are transparent and the others opaque.
|
||||
let none = file(json!({}));
|
||||
assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
|
||||
for method in ["diffusion", "pattern", "noise"] {
|
||||
let dithered = file(json!({"transparencyDither": method}));
|
||||
let [left, right] = opaque_halves(&dithered);
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
|
||||
// Without transparency the dither does nothing.
|
||||
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
|
||||
assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}");
|
||||
}
|
||||
let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})));
|
||||
assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}");
|
||||
// null is the same as leaving a key out.
|
||||
assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}");
|
||||
for bad in [
|
||||
json!({"transparencyDither": "spray"}),
|
||||
json!({"transparencyDither": 3}),
|
||||
json!({"transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDitherAmount": -1}),
|
||||
json!({"transparencyDitherAmount": "50"}),
|
||||
json!({"transparencyDitherAmount": 50.5}),
|
||||
] {
|
||||
assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}");
|
||||
}
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}");
|
||||
}
|
||||
// Formats without a palette do not read the keys: their values are not checked, and the
|
||||
// warnings name them.
|
||||
for format in ["png", "jpg", "tiff"] {
|
||||
for keys in [
|
||||
json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}),
|
||||
] {
|
||||
let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone()));
|
||||
let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string();
|
||||
assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_formats_reach_export_as_and_screens() {
|
||||
let mut s = session();
|
||||
@@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() {
|
||||
let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone();
|
||||
assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false)));
|
||||
assert_eq!(f("gif")["write"], true);
|
||||
for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] {
|
||||
for k in
|
||||
["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"]
|
||||
{
|
||||
assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}");
|
||||
}
|
||||
assert_eq!(format_for_name("a.png").unwrap().id, "png");
|
||||
|
||||
@@ -172,8 +172,9 @@ fn apply_transform_moving_guides(
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
let mut ids = ids;
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
ids.extend(crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?);
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -181,7 +182,7 @@ fn apply_transform_moving_guides(
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
let targets = match &kept {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
Some(k) => {
|
||||
@@ -231,7 +232,9 @@ fn apply_transform_moving_guides(
|
||||
d.edit_ruler_guide(i, |g| *g = g.moved(delta));
|
||||
}
|
||||
} else if with_guides && !is_translation {
|
||||
d.transform_ruler_guides(sel, xf);
|
||||
// The guide paths are made already transformed, so they join the reply after the
|
||||
// loop above.
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
|
||||
@@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector
|
||||
// ---------- text ----------
|
||||
|
||||
/// Largest indent or paragraph spacing (points; Illustrator's limit).
|
||||
const MAX_PARA: f64 = 1296.0;
|
||||
const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE;
|
||||
|
||||
/// `text.setFormat`'s `bullet` values and the bullets they pick.
|
||||
const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [
|
||||
|
||||
@@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res
|
||||
|
||||
/// [`transform_selected`] on the active document's selection, as one undo step `label`. A
|
||||
/// transform other than a move also transforms the selected ruler guides
|
||||
/// ([`Document::transform_ruler_guides`]).
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds.
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<Vec<NodeId>> {
|
||||
let sel = s.doc()?.selection.clone();
|
||||
// As [`transform_selected`] tells a move apart, which moves the guides itself.
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
s.edit(label, |doc, live| {
|
||||
transform_selected(doc, &sel, xf, sc, interpolate)?;
|
||||
if !is_translation {
|
||||
doc.transform_ruler_guides(live, xf);
|
||||
}
|
||||
Ok(())
|
||||
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+126
-28
@@ -42,7 +42,9 @@
|
||||
//!
|
||||
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
|
||||
//! images or symbol instances of those kinds, to read only: its output must return each of them
|
||||
//! unchanged ([`objects::decode_output_with`]).
|
||||
//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds
|
||||
//! among them it may change: type's runs and paragraph styles, an image's transform and opacity,
|
||||
//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]).
|
||||
//!
|
||||
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
|
||||
//! also given the parts of the active document it names in `_context.document`, whether or not
|
||||
@@ -53,7 +55,7 @@ use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Document, Effect, Node};
|
||||
use vectorcraft_doc::{Document, Effect, Node, NodeKind};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
@@ -113,6 +115,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.writes.is_empty() {
|
||||
v["writes"] = json!(m.writes);
|
||||
}
|
||||
if !m.context.is_empty() {
|
||||
v["context"] = json!(m.context);
|
||||
}
|
||||
@@ -377,7 +382,7 @@ impl FilterRun {
|
||||
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
|
||||
let m = self.plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
|
||||
let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?;
|
||||
if out.document_data.is_some() && !may.contains(&Permission::State) {
|
||||
return Err(not_granted(&m.name, Permission::State));
|
||||
}
|
||||
@@ -393,18 +398,52 @@ impl FilterRun {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
// Typing whose text Real-time Drawing off left out of the document isn't in what the
|
||||
// plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it
|
||||
// before the run is prepared).
|
||||
if unapplied_typing(s) {
|
||||
return Err(err(vectorcraft_plugins::Error::Output(
|
||||
"typing in progress isn't in what the plug-in was given: nothing was changed".into(),
|
||||
)));
|
||||
}
|
||||
let data = out.document_data;
|
||||
// The output applied to `now`, with the checks that refuse it.
|
||||
let build = |now: &Document, objects: Vec<objects::OutObject>| -> Result<(Document, Vec<NodeId>)> {
|
||||
let mut d = now.clone();
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
// Type whose text the output changed is laid out again.
|
||||
let retyped: Vec<NodeId> = ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) {
|
||||
(Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para,
|
||||
_ => false,
|
||||
})
|
||||
.collect();
|
||||
super::typecmd::refresh_bounds_of(&mut d, &retyped);
|
||||
if let Some(data) = data.clone() {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
}
|
||||
Ok((d, ids))
|
||||
};
|
||||
// Typing in progress, its text already in the document, is kept as `s.edit` keeps it once
|
||||
// nothing can refuse the output, so a refused output leaves it in progress. Keeping it can
|
||||
// change the document, and the output is then applied to the document as kept.
|
||||
let typing = !s.previewing && super::typing_in_progress(s);
|
||||
let again = typing.then(|| out.objects.clone());
|
||||
let mut now = s.doc()?.doc.clone();
|
||||
let (mut d, mut ids) = build(&now, out.objects)?;
|
||||
if let Some(objects) = again {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
let now = s.doc()?.doc.clone();
|
||||
let mut d = (*now).clone();
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
if let Some(data) = out.document_data {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
let kept = s.doc()?.doc.clone();
|
||||
if !Arc::ptr_eq(&kept, &now) {
|
||||
now = kept;
|
||||
(d, ids) = build(&now, objects)?;
|
||||
}
|
||||
}
|
||||
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
|
||||
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
|
||||
@@ -447,6 +486,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError {
|
||||
err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed")))
|
||||
}
|
||||
|
||||
/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a
|
||||
/// preview's run)? A run prepared now isn't given that text.
|
||||
pub fn unapplied_typing(s: &Session) -> bool {
|
||||
!s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some()
|
||||
}
|
||||
|
||||
/// Keeps typing in progress whose text Real-time Drawing off left out of the document
|
||||
/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the
|
||||
/// typed text; one prepared before it is prepared again.
|
||||
pub fn keep_unapplied_typing(s: &mut Session) -> Result<bool> {
|
||||
if !unapplied_typing(s) {
|
||||
return Ok(false);
|
||||
}
|
||||
super::settle_interaction(s)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
|
||||
/// parameters and `_context` (what it keeps with the document included), and applies its output as
|
||||
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with
|
||||
@@ -464,6 +520,8 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r };
|
||||
return r.run_with_calls(s);
|
||||
}
|
||||
// Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it.
|
||||
let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r };
|
||||
// Handed in for this very run (the app ran it in the background), it is what running the
|
||||
// plug-in again would return.
|
||||
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
|
||||
@@ -887,6 +945,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
};
|
||||
return r.run_with_calls(s).map_err(failed);
|
||||
}
|
||||
let r = match keep_unapplied_typing(s)? {
|
||||
true => {
|
||||
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
FilterRun::prepare_with(s, plugin, Some(command), id, p)?
|
||||
}
|
||||
false => r,
|
||||
};
|
||||
let output = r.run().map_err(&failed)?;
|
||||
r.finish(s, &output).map_err(failed)
|
||||
}
|
||||
@@ -1808,18 +1873,49 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
// A module stored for an id that isn't installed (one no grant covers is skipped at startup)
|
||||
// counts as removed once its file is gone.
|
||||
let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id);
|
||||
// An installed plug-in's stored module is deleted with its grant too, so that one that can't be
|
||||
// deleted leaves the plug-in installed. Without a plug-in folder it has none.
|
||||
let unstore = module || (installed && s.plugin_dir.is_some());
|
||||
// The grant the store keeps for an installed plug-in, which may differ from the one the session
|
||||
// holds (an update whose module couldn't be stored): written back when its module can't be
|
||||
// deleted, so that the stored module still loads at the next launch.
|
||||
let kept_grant = if installed { s.stored_plugin_grant(id) } else { None };
|
||||
let module_left = std::cell::Cell::new(false);
|
||||
let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default());
|
||||
// Installed again, it asks again. A grant that can't be removed may still approve the module, and
|
||||
// so may a grants file that can't be opened or read, or a signed copy of the file put back when
|
||||
// the generation couldn't be raised (the key store can't be reached). Without a plug-in folder
|
||||
// nothing keeps a grant. The stored module is deleted next, while its settings and cache can
|
||||
// still be moved back.
|
||||
let forget = || {
|
||||
if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() {
|
||||
return false;
|
||||
}
|
||||
let deleted = !unstore || s.unstore_plugin(&turn, id);
|
||||
if !deleted
|
||||
&& let Some(grant) = kept_grant.clone()
|
||||
&& !s.store_grant_in(&turn, id, Some(grant))
|
||||
{
|
||||
log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch");
|
||||
}
|
||||
module_left.set(!deleted);
|
||||
deleted
|
||||
};
|
||||
// Its settings and cache are moved aside, its grant removed and its stored module deleted before
|
||||
// anything else is deleted: when one of them can't be done, the settings and cache are moved back,
|
||||
// the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id
|
||||
// names no grant and no module.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
} else if vectorcraft_plugins::manifest::valid_id(id) {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e });
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
@@ -1827,8 +1923,10 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
registry::revoke(id);
|
||||
s.unstore_plugin(&turn, id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
if !s.unstore_plugin(&turn, id) && module {
|
||||
return Err(EngineError::Other(cant_delete()));
|
||||
}
|
||||
if !stored && !module && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
}
|
||||
Ok(json!({"removed": id}))
|
||||
@@ -1860,7 +1958,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1878,7 +1976,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
@@ -1887,7 +1985,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -1905,7 +2003,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -711,6 +711,12 @@ impl Prefs {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a
|
||||
/// reset of every category. A frontend resets the settings it keeps itself in them.
|
||||
pub fn take_prefs_resets(&mut self) -> Vec<Option<&'static str>> {
|
||||
std::mem::take(&mut self.prefs_resets)
|
||||
}
|
||||
|
||||
/// Replace the preferences and push the ones with engine-side consumers into open documents
|
||||
/// and the renderer (grid, history depth, render threads).
|
||||
pub fn apply_prefs(&mut self, mut p: Prefs) {
|
||||
@@ -818,7 +824,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
|
||||
cmd!(
|
||||
query "prefs.export",
|
||||
@@ -1001,15 +1007,17 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cat = str_param(p, "category");
|
||||
if let Some(c) = cat
|
||||
&& !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c))
|
||||
{
|
||||
return Err(bad("prefs.reset", format!("unknown category `{c}`")));
|
||||
}
|
||||
let cat = text_param(p, "category", "prefs.reset")?;
|
||||
let known = |c: &str| {
|
||||
PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`")))
|
||||
};
|
||||
let category = cat.map(known).transpose()?;
|
||||
let mut next = s.prefs.clone();
|
||||
next.reset(cat);
|
||||
s.apply_prefs(next);
|
||||
if !s.prefs_resets.contains(&category) {
|
||||
s.prefs_resets.push(category);
|
||||
}
|
||||
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
|
||||
}
|
||||
|
||||
|
||||
@@ -157,13 +157,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"charStyle",
|
||||
"Character Styles",
|
||||
"Character",
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings"
|
||||
);
|
||||
v.push(spec(
|
||||
"charStyle.edit",
|
||||
"Edit Character Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
@@ -636,52 +636,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
for (key, value, lo, hi) in
|
||||
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
|
||||
{
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
|
||||
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
|
||||
}
|
||||
let shift_max = 1296.0;
|
||||
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
|
||||
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
|
||||
}
|
||||
}
|
||||
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
|
||||
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME);
|
||||
if changed(key) && !(lo..=hi).contains(&st.tsume) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
|
||||
let lo = -hi;
|
||||
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let lines = vectorcraft_doc::text::WARICHU_LINES;
|
||||
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
|
||||
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = vectorcraft_doc::text::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in [
|
||||
("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP),
|
||||
("warichuScale", st.warichu_scale, *scale.start(), *scale.end()),
|
||||
] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
st.check_ranges(changed).map_err(|e| bad(&c, e.message))?;
|
||||
// A language of the list, stored as its tag (as text.setFormat takes it).
|
||||
if let Some(l) = &st.language
|
||||
&& kept.and_then(|k| k.get("language")) != m.get("language")
|
||||
@@ -693,10 +648,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
style_paint(d, paint, key, &c)?;
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
|
||||
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
if changed("features") {
|
||||
style_features(&st.features, kept, &c)?;
|
||||
}
|
||||
@@ -753,85 +704,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
|
||||
/// as `text.setFormat` keeps them.
|
||||
const PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options
|
||||
/// as `attrs` gives them. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
};
|
||||
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
|
||||
let nested_changed = |key: &str, field: &str| {
|
||||
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
|
||||
let check = |key: &str, field: Option<&str>| match field {
|
||||
None => changed(key),
|
||||
Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)),
|
||||
};
|
||||
for (key, value) in [
|
||||
("left_indent", st.left_indent),
|
||||
("right_indent", st.right_indent),
|
||||
("first_line_indent", st.first_line_indent),
|
||||
("space_before", st.space_before),
|
||||
("space_after", st.space_after),
|
||||
] {
|
||||
if changed(key) {
|
||||
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &st.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, PARA_DISTANCE),
|
||||
] {
|
||||
if nested_changed("hyphenation", field) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
// Read as given: a paragraph's attributes keep justification options in range as they load.
|
||||
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
|
||||
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !nested_changed("justification", field) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if nested_changed("justification", "auto_leading") {
|
||||
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
let given = attrs.get("justification").filter(|_| changed("justification"));
|
||||
let justification: Option<vectorcraft_doc::JustificationOptions> =
|
||||
given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?;
|
||||
st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message))
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
@@ -1204,17 +1090,22 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps,
|
||||
/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 24] = [
|
||||
const RANGED: [&str; 32] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
"leading",
|
||||
"tracking",
|
||||
"kerning",
|
||||
"kerningBefore",
|
||||
"baseline_shift",
|
||||
"rotation",
|
||||
"akiLeft",
|
||||
"akiRight",
|
||||
"tsume",
|
||||
@@ -1226,6 +1117,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
"warichuGap",
|
||||
"warichuScale",
|
||||
"stroke_width",
|
||||
"stroke_miter_limit",
|
||||
"stroke_dash",
|
||||
"small_caps",
|
||||
"fontAxes",
|
||||
"left_indent",
|
||||
"right_indent",
|
||||
"first_line_indent",
|
||||
|
||||
@@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
json!({"tsume": 100.1}),
|
||||
json!({"diacriticHorizontal": -1000.1}),
|
||||
json!({"diacriticVertical": 1000.1}),
|
||||
json!({"tracking": -1000.1}),
|
||||
json!({"kerning": 10000.1}),
|
||||
json!({"rotation": 360.1}),
|
||||
json!({"stroke_miter_limit": 0.9}),
|
||||
json!({"small_caps": 200.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
@@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
|
||||
"akiLeft": 0.0, "akiRight": 1000.0,
|
||||
"tsume": 100.0,
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0,
|
||||
"tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0,
|
||||
"stroke_miter_limit": 500.0, "small_caps": 200.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -830,8 +837,8 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is
|
||||
/// out of the range `charStyle.new` takes is skipped.
|
||||
/// 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]
|
||||
fn loaded_styles_out_of_range_are_skipped() {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
@@ -841,11 +848,17 @@ fn loaded_styles_out_of_range_are_skipped() {
|
||||
("Shifted", json!({"baseline_shift": 5000.0})),
|
||||
("Thick", json!({"stroke_width": -2.0})),
|
||||
("Gapped", json!({"warichuGap": 500.0})),
|
||||
("Spun", json!({"rotation": 720.0})),
|
||||
("Tracked", json!({"tracking": 50000.0})),
|
||||
("Kerned", json!({"kerning": -5000.0})),
|
||||
("Before", json!({"kerningBefore": 50000.0})),
|
||||
("Mitered", json!({"stroke_miter_limit": 0.5})),
|
||||
("Fine", json!({"size": 12.0, "h_scale": 50.0})),
|
||||
];
|
||||
let data = styles_file(&file, &[]);
|
||||
let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]}));
|
||||
let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"];
|
||||
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped}));
|
||||
assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection,
|
||||
use super::edit::selected_roots;
|
||||
use super::fileio::{absolute_path, read_file_head, write_file};
|
||||
use super::textedit::set_story_text;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links,
|
||||
str_param,
|
||||
};
|
||||
|
||||
mod csv;
|
||||
mod library;
|
||||
@@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.unbind";
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
// Explicit bindings can include both a group and its children; retain every supplied ID.
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? };
|
||||
let name = defined_variable(s, p, C)?;
|
||||
let n = edit_variables(s, "Unbind Variable", |vars| {
|
||||
let mut n = 0;
|
||||
|
||||
@@ -136,6 +136,8 @@ pub struct Session {
|
||||
/// Set when a command that draws a shape was journaled outside saved steps
|
||||
/// ([`Session::take_shape_drawn`]).
|
||||
shape_drawn: bool,
|
||||
/// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]).
|
||||
prefs_resets: Vec<Option<&'static str>>,
|
||||
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
|
||||
tool_panic: Option<EngineError>,
|
||||
/// How many times switching or closing documents, or replacing the active one, has started the
|
||||
|
||||
@@ -772,6 +772,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(open))
|
||||
}
|
||||
|
||||
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
|
||||
/// strings are the ones
|
||||
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
|
||||
/// lists, and `Fit Artboard to artwork bounds` is the one
|
||||
/// <https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee> gives for Object ›
|
||||
/// Artboards › Fit to Artwork Bounds.
|
||||
const MENU_COMMANDS: &[(&str, &str)] = &[
|
||||
("selectall", "select.all"),
|
||||
("deselectall", "select.none"),
|
||||
("group", "object.group"),
|
||||
("ungroup", "object.ungroup"),
|
||||
("makeMask", "object.clippingMask.make"),
|
||||
("releaseMask", "object.clippingMask.release"),
|
||||
("compoundPath", "object.compoundPath.make"),
|
||||
("noCompoundPath", "object.compoundPath.release"),
|
||||
("Fit Artboard to artwork bounds", "artboard.fitToArt"),
|
||||
];
|
||||
|
||||
/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names
|
||||
/// ([`MENU_COMMANDS`]) on the active document, as
|
||||
/// <https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts> describes the method. A
|
||||
/// name it does not list throws an error that names it. A menu item that is not available, with
|
||||
/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does
|
||||
/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error
|
||||
/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does
|
||||
/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims
|
||||
/// the item then ([`DocState::any_art_to_fit`]).
|
||||
fn app_menu_command(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the menu command is too long".into()));
|
||||
}
|
||||
let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else {
|
||||
return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\"")));
|
||||
};
|
||||
let params = {
|
||||
let s = h.session.borrow();
|
||||
let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) };
|
||||
if (spec.enabled)(&s).is_err() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
match (id, s.active()) {
|
||||
("artboard.fitToArt", Some(st)) => {
|
||||
let index = active_artboard(st);
|
||||
if !st.any_art_to_fit(&[index]) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
json!({"index": index})
|
||||
}
|
||||
_ => json!({}),
|
||||
}
|
||||
};
|
||||
command(h, id, ¶ms)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Documents ----
|
||||
|
||||
fn docs_length(h: &Host, _: &[Data]) -> Answer {
|
||||
@@ -1303,6 +1359,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());
|
||||
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()));
|
||||
let locks = d.locked_artboards();
|
||||
@@ -1317,7 +1374,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
|
||||
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
|
||||
}
|
||||
if !ids.contains(&item.id) {
|
||||
if seen.insert(item.id) {
|
||||
ids.push(item.id);
|
||||
}
|
||||
}
|
||||
@@ -1378,6 +1435,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("PageItems"))
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
@@ -2085,6 +2147,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("selection", property(l, app_selection, app_set_selection)),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords)),
|
||||
("getIsFileOpen", method(l, app_is_open)),
|
||||
("executeMenuCommand", method(l, app_menu_command)),
|
||||
("toString", class_text("Application")),
|
||||
]);
|
||||
application.push(later(l, "Application", "beep"));
|
||||
@@ -2148,7 +2211,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("index", method(l, items_index)),
|
||||
("getByName", method(l, items_by_name)),
|
||||
("removeAll", method(l, items_remove_all)),
|
||||
("toString", class_text("PageItems")),
|
||||
("toString", method(l, items_to_string)),
|
||||
]),
|
||||
Some(function(l, items_at)),
|
||||
));
|
||||
|
||||
@@ -1650,24 +1650,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in,
|
||||
/// with that file's name unless it is the run's own script.
|
||||
fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<str>>) {
|
||||
let map = |m: &include::SourceMap| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
|
||||
};
|
||||
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
|
||||
}
|
||||
placed(host, e, realm.error_source(), realm.error_tag())
|
||||
}
|
||||
|
||||
/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`]
|
||||
/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name
|
||||
/// unless it is the run's own script.
|
||||
fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option<Arc<str>>) {
|
||||
let map = |m: &include::SourceMap| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
|
||||
};
|
||||
if e.line == 0 {
|
||||
return (e.clone(), None);
|
||||
}
|
||||
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
|
||||
// is given without a place.
|
||||
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
|
||||
match realm.error_source() {
|
||||
match source {
|
||||
0 => {
|
||||
let (e, index, file) = map(&host.script_map.borrow());
|
||||
(e, (index > 0).then_some(file))
|
||||
@@ -1684,7 +1691,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
|
||||
// `$.evalFile` gave. A script given as text is named by that run's name.
|
||||
_ => {
|
||||
let kept = host.kept_maps.as_ref().map(|k| k.borrow());
|
||||
match kept.as_ref().and_then(|k| k.get(realm.error_tag())) {
|
||||
match kept.as_ref().and_then(|k| k.get(tag)) {
|
||||
Some(kept) => {
|
||||
let (e, index, file) = map(&kept.map);
|
||||
let file = match &kept.script {
|
||||
@@ -2044,7 +2051,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.
|
||||
// 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());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
@@ -2053,6 +2061,9 @@ impl Session {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
if es2015 {
|
||||
realm.add_es2015();
|
||||
}
|
||||
realm
|
||||
}
|
||||
None => {
|
||||
@@ -2382,6 +2393,11 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
let rejections = rejections_report(host, &job.realm);
|
||||
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
|
||||
o.insert("unhandledRejections".into(), Value::Array(rejections));
|
||||
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
|
||||
}
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
self.end_job(job, false);
|
||||
self.script_report = Some(report.clone());
|
||||
@@ -2427,6 +2443,29 @@ const NO_RUN: &str = "this function's script run has ended";
|
||||
const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped";
|
||||
const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web";
|
||||
const ENGINE_BUSY: &str = "the script engine is in use by another run";
|
||||
const UNHANDLED_REJECTION: &str = "unhandled promise rejection";
|
||||
const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections";
|
||||
|
||||
/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when
|
||||
/// known, the line, column and file it was rejected at.
|
||||
fn rejections_report(host: &Host, realm: &Realm) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
for r in realm.unhandled_rejections() {
|
||||
let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored };
|
||||
let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag);
|
||||
let mut o = json!({
|
||||
"message": e.message,
|
||||
"messageOrigin": if e.authored { "script" } else { "built-in" },
|
||||
"line": e.line,
|
||||
"column": e.column,
|
||||
});
|
||||
if let (Some(file), Some(map)) = (file, o.as_object_mut()) {
|
||||
map.insert("file".into(), json!(&*file));
|
||||
}
|
||||
out.push(o);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The report of a run that failed; `file` is the included file the error is in.
|
||||
fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
|
||||
@@ -2507,6 +2546,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
|
||||
if report["ok"] == false {
|
||||
each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
if let Some(rejections) = report["unhandledRejections"].as_array() {
|
||||
for r in rejections {
|
||||
let mut placed = r.clone();
|
||||
placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default()));
|
||||
each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64);
|
||||
if more > 0 {
|
||||
let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name);
|
||||
each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
}
|
||||
let timing = clock().is_some();
|
||||
let ms = millis(host.run_nanos.get());
|
||||
let slow = slowest(&host.commands.borrow());
|
||||
|
||||
@@ -78,6 +78,7 @@ impl Session {
|
||||
depth: 0,
|
||||
replaying: false,
|
||||
shape_drawn: false,
|
||||
prefs_resets: Vec::new(),
|
||||
tool_panic: None,
|
||||
tool_resets: 0,
|
||||
tool_set_since_reset: false,
|
||||
|
||||
+325
-37
@@ -20,7 +20,10 @@
|
||||
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional
|
||||
//! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
|
||||
//! stored there that list permissions (id, module hash, permissions); a stored plug-in whose
|
||||
//! permissions it doesn't grant is skipped with a log record, and stays in the folder.
|
||||
//! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file
|
||||
//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's
|
||||
//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the
|
||||
//! one the key store keeps for the folder, grants nothing.
|
||||
//! * **Plug-in settings and caches**: `storage/id-<id>/` in the plug-in store, the id written as
|
||||
//! [`case_safe`] writes it, holds what a plug-in
|
||||
//! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a
|
||||
@@ -52,6 +55,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
|
||||
use crate::Session;
|
||||
use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile};
|
||||
|
||||
pub mod grant_keys;
|
||||
|
||||
/// Files read from one store folder, at most (the rest are ignored).
|
||||
pub const MAX_STORE_FILES: usize = 1000;
|
||||
/// The largest PDF presets file read (a preset is a few kilobytes).
|
||||
@@ -463,6 +468,11 @@ fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool {
|
||||
if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) {
|
||||
return true;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if file == GRANTS_FILE && GRANTS_WRITE_FAILS.get() {
|
||||
log::warn!("can't save {}: the test fails it", path.display());
|
||||
return false;
|
||||
}
|
||||
let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes));
|
||||
if let Err(e) = &written {
|
||||
log::warn!("can't save {}: {e}", path.display());
|
||||
@@ -560,6 +570,9 @@ thread_local! {
|
||||
/// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when
|
||||
/// another program holds it open.
|
||||
pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: writing [`GRANTS_FILE`] fails on this thread and leaves the file as it was, as on a
|
||||
/// full volume.
|
||||
pub(crate) static GRANTS_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then
|
||||
/// reports a failure, as when the last flush of a copy fails.
|
||||
pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
@@ -810,18 +823,10 @@ impl Session {
|
||||
}
|
||||
let dir = load.dir.clone();
|
||||
// The grants file is read once for this turn. `written` holds whether it names each id
|
||||
// whose grant this turn removed or put back.
|
||||
// whose grant this turn removed or put back. Only a signed file grants anything
|
||||
// ([`signed_grants`]).
|
||||
let file = read_grants(&dir);
|
||||
let mut grants = self.counted(
|
||||
&dir,
|
||||
match &file {
|
||||
Ok(file) => file.grants.clone(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut grants = self.counted(&dir, signed_grants(&dir, &file));
|
||||
let mut written: BTreeMap<String, bool> = BTreeMap::new();
|
||||
let named = |written: &BTreeMap<String, bool>, id: &str| {
|
||||
written.get(id).copied().unwrap_or_else(|| match &file {
|
||||
@@ -1304,9 +1309,25 @@ impl Session {
|
||||
|
||||
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
|
||||
/// other grants as they are; with none left, remove the file. Entries this version can't use
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and
|
||||
/// are written back as they were, except one for `id`. The generation is raised, and the file is
|
||||
/// written at the generation after the raised one with the MAC of its grants for this folder
|
||||
/// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that
|
||||
/// generation ([`put_grants`]). A signed file left empty is removed after raising the generation
|
||||
/// ([`take_signed_grants`]). The generation is never lowered: when the file can't be written or
|
||||
/// removed after the raise, the file in place grants nothing and its plug-ins ask again. A file
|
||||
/// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant replaces it with a file that holds that grant alone, and removing one
|
||||
/// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the
|
||||
/// rest unsigned. Removing a grant when there is no file, or when the file grants nothing
|
||||
/// (unsigned, too large or not a list) and has no entry to take out, also raises the generation
|
||||
/// when the key store holds a key ([`retire_signed_copies`]), so that a signed copy put back
|
||||
/// doesn't grant it again. The generation is never read from the file; when it can't be raised,
|
||||
/// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or
|
||||
/// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry
|
||||
/// for `id` stays; a removal then reports a failure, also when the file doesn't name `id`. A
|
||||
/// grants file that is too large, can't be read or doesn't hold a list is left as it is, with a
|
||||
/// log record, and nothing is recorded; so is one whose new content would be larger than
|
||||
/// `MAX_GRANTS_FILE`. A removal still holds for a file that is too large or doesn't hold a list
|
||||
/// once the generation is raised ([`retire_signed_copies`]). The file is read and
|
||||
/// written in `turn`. → whether the store now holds what was asked (`false` without a folder,
|
||||
/// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every
|
||||
/// session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
@@ -1364,13 +1385,33 @@ impl Session {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
return false;
|
||||
// A file that is too large or doesn't hold a list grants nothing and is left as it
|
||||
// is, but a signed copy made before it must not grant `id` again once it is put back:
|
||||
// the removal holds once no such copy can.
|
||||
return grant.is_none() && !e.unread && retire_signed_copies(dir);
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANTS_READ.take() {
|
||||
between();
|
||||
}
|
||||
match (file.trust, &grant) {
|
||||
// Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for
|
||||
// the session only, and one the file may still hold for `id` can't be removed. A file
|
||||
// that doesn't name `id` may not be the one the kept generation was signed for, so the
|
||||
// removal isn't known to hold either.
|
||||
(Trust::Unknown, _) => return false,
|
||||
// The file grants nothing. A new grant replaces it with a signed file that holds that
|
||||
// grant alone; removing one takes its entry out and leaves the rest unsigned.
|
||||
(Trust::Unsigned, Some(_)) => {
|
||||
log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display());
|
||||
file.grants.clear();
|
||||
file.other.clear();
|
||||
}
|
||||
(Trust::Unsigned | Trust::Signed, _) => {}
|
||||
}
|
||||
let signed = file.trust == Trust::Signed || grant.is_some();
|
||||
let removing = grant.is_none();
|
||||
let others = file.other.len();
|
||||
file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id));
|
||||
let changed = match grant {
|
||||
@@ -1378,23 +1419,25 @@ impl Session {
|
||||
None => file.grants.remove(id).is_some(),
|
||||
} || file.other.len() != others;
|
||||
if !changed {
|
||||
return true;
|
||||
// Without a file, or with one that grants nothing, the last signed file may still be
|
||||
// around as a copy at the kept generation: a removal raises the generation so that the
|
||||
// copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id`
|
||||
// is the latest, so every copy that does is at an earlier generation already. The new
|
||||
// generation is past every one a file was signed at, so the file left in place grants
|
||||
// nothing either.
|
||||
return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir);
|
||||
}
|
||||
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
|
||||
entries.extend(file.other);
|
||||
if entries.is_empty() {
|
||||
return take(dir, GRANTS_FILE);
|
||||
if signed {
|
||||
return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) };
|
||||
}
|
||||
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
|
||||
// and not at all when that is too.
|
||||
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
|
||||
match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) {
|
||||
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
|
||||
None => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE));
|
||||
false
|
||||
}
|
||||
// An unsigned file loses an entry: the generation is raised first, so that no signed copy
|
||||
// made before brings the entry back, nor the file itself when it can't be rewritten.
|
||||
if raise_generation(dir).is_none() {
|
||||
return false;
|
||||
}
|
||||
if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) }
|
||||
}
|
||||
|
||||
/// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this
|
||||
@@ -1408,6 +1451,19 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// The grant the attached plug-in store's signed grants file holds for the plug-in `id` (`None`
|
||||
/// without a folder, and when the file grants nothing: unsigned, unreadable or without an entry
|
||||
/// for `id`).
|
||||
pub(crate) fn stored_plugin_grant(&self, id: &str) -> Option<vectorcraft_plugins::permissions::Grant> {
|
||||
self.plugin_dir.as_deref().and_then(|dir| stored_grants(dir).remove(id))
|
||||
}
|
||||
|
||||
/// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one
|
||||
/// that no grant covers is skipped at startup and stays in the folder)?
|
||||
pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| std::fs::symlink_metadata(dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)))).is_ok())
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a
|
||||
/// folder, and when `turn` isn't held).
|
||||
pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool {
|
||||
@@ -2049,10 +2105,16 @@ impl Storage for PluginStorage {
|
||||
/// What the grants file of a plug-in store holds.
|
||||
#[derive(Default)]
|
||||
struct GrantsFile {
|
||||
/// The grants this version can use, by plug-in id.
|
||||
/// The grants this version can use, by plug-in id. They grant something only when the file is
|
||||
/// [`Trust::Signed`].
|
||||
grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
/// The entries it can't use (a permission it doesn't know, an invalid id), as they were.
|
||||
other: Vec<serde_json::Value>,
|
||||
/// Whether VectorCraft wrote the grants for this folder.
|
||||
trust: Trust,
|
||||
/// Whether there is a grants file: `false` when there is none, and the file is then empty and
|
||||
/// [`Trust::Signed`].
|
||||
present: bool,
|
||||
}
|
||||
|
||||
impl GrantsFile {
|
||||
@@ -2062,6 +2124,207 @@ impl GrantsFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]).
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Trust {
|
||||
/// There is no file, or it is at the generation kept for its folder and carries the MAC of that
|
||||
/// generation, its grants and its folder made with the user's key.
|
||||
#[default]
|
||||
Signed,
|
||||
/// It doesn't: an older version wrote it, another program wrote or changed it, it was copied
|
||||
/// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept
|
||||
/// (its generation is not the one the key store keeps), or the key store holds no key. It grants
|
||||
/// nothing.
|
||||
Unsigned,
|
||||
/// The key store can't be reached, so it is not known which. It grants nothing, and is left as
|
||||
/// it is.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// The version of the grants file this version writes ([`SignedGrants::version`]).
|
||||
const GRANTS_VERSION: u64 = 1;
|
||||
|
||||
/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]),
|
||||
/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as
|
||||
/// compact JSON.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct SignedGrants {
|
||||
version: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
generation: Option<u64>,
|
||||
grants: Vec<serde_json::Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
mac: Option<String>,
|
||||
}
|
||||
|
||||
/// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it
|
||||
/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft
|
||||
/// writes one.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec<u8> {
|
||||
let entries: Vec<serde_json::Value> = serde_json::from_str(grants).unwrap_or_default();
|
||||
let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}"));
|
||||
let folder = plugin_store_key(dir);
|
||||
let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}"));
|
||||
let canonical = serde_json::to_vec(&entries).unwrap_or_default();
|
||||
let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default();
|
||||
format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes()
|
||||
}
|
||||
|
||||
/// Tests: the entries of the grants file `bytes`, signed or not.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn grant_entries(bytes: &[u8]) -> Vec<serde_json::Value> {
|
||||
match serde_json::from_slice::<serde_json::Value>(bytes) {
|
||||
Ok(serde_json::Value::Array(entries)) => entries,
|
||||
Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") {
|
||||
Some(serde_json::Value::Array(entries)) => entries,
|
||||
_ => vec![],
|
||||
},
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept
|
||||
/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key.
|
||||
/// A file at another generation, one behind or one ahead of the kept one included, is
|
||||
/// [`Trust::Unsigned`].
|
||||
fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust {
|
||||
let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned };
|
||||
let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned };
|
||||
let folder = plugin_store_key(dir);
|
||||
let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose());
|
||||
match kept {
|
||||
Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed,
|
||||
Ok(_) => Trust::Unsigned,
|
||||
Err(e) => {
|
||||
log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
Trust::Unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when
|
||||
/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the
|
||||
/// key or the generation can't be had or it is too large either way. When `signed`, the generation
|
||||
/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one
|
||||
/// with its MAC, and the key store keeps that generation once the file is written. Every signed write
|
||||
/// is then at a generation no file was signed at before, a write whose generation wasn't kept
|
||||
/// included, since that one is at most one past the generation the key store kept. A file too large
|
||||
/// either way is found before the raise, and then nothing changes. The kept generation only goes up:
|
||||
/// when the file isn't written after the raise, the generation stays raised, so the file in place
|
||||
/// grants nothing and its plug-ins ask again. When the file's generation can't be kept, the file is
|
||||
/// at a generation the key store doesn't hold, so it grants nothing either. Both report a failure.
|
||||
/// Call it in the store's turn ([`StoreTurn`]).
|
||||
fn put_grants(dir: &Path, entries: Vec<serde_json::Value>, signed: bool) -> bool {
|
||||
let path = dir.join(GRANTS_FILE);
|
||||
let folder = plugin_store_key(dir);
|
||||
if !signed {
|
||||
return match grants_bytes(serde_json::to_value(entries).ok()) {
|
||||
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
|
||||
None => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
false
|
||||
}
|
||||
};
|
||||
}
|
||||
let key = match grant_keys::signing_key() {
|
||||
Ok(key) => key,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {e}", path.display());
|
||||
return false;
|
||||
}
|
||||
};
|
||||
// A file too large to keep is found before the raise, at the generation it would be written at
|
||||
// (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place
|
||||
// keeps its grants when nothing can be written. When the kept generation can't be read, the raise
|
||||
// fails too.
|
||||
let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX);
|
||||
let mut file =
|
||||
SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) };
|
||||
if grants_bytes(serde_json::to_value(&file).ok()).is_none() {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
return false;
|
||||
}
|
||||
let Some(raised) = raise_generation(dir) else { return false };
|
||||
let Some(next) = raised.checked_add(1) else {
|
||||
log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display());
|
||||
return false;
|
||||
};
|
||||
file.generation = Some(next);
|
||||
file.mac = serde_json::to_vec(&file.grants).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants));
|
||||
let Some(bytes) = file.mac.as_ref().and_then(|_| grants_bytes(serde_json::to_value(&file).ok())) else {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
return false;
|
||||
};
|
||||
put(dir, GRANTS_FILE, &bytes) && keep_generation(dir, &folder, next)
|
||||
}
|
||||
|
||||
/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than
|
||||
/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap.
|
||||
fn grants_bytes(file: Option<serde_json::Value>) -> Option<Vec<u8>> {
|
||||
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
|
||||
file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits)))
|
||||
}
|
||||
|
||||
/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) →
|
||||
/// whether the key store kept it; a failure is logged.
|
||||
fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool {
|
||||
match grant_keys::set_current_generation(folder, generation) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is
|
||||
/// raised first, so that no copy of the file grants anything once it is gone. The generation stays
|
||||
/// raised when the file can't be removed: the file left in place then grants nothing, and its
|
||||
/// plug-ins ask again. The file holds no grant but the one being removed. Nothing is removed when
|
||||
/// the generation can't be raised. Call it in the store's turn ([`StoreTurn`]).
|
||||
fn take_signed_grants(dir: &Path) -> bool {
|
||||
raise_generation(dir).is_some() && take(dir, GRANTS_FILE)
|
||||
}
|
||||
|
||||
/// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that
|
||||
/// no signed copy of the file made before grants anything → the generation kept now; `None`, with a
|
||||
/// log record, when the key store can't read or keep it or the generation is within two of the
|
||||
/// largest 64-bit value. A signed write whose generation wasn't kept is at the generation after the
|
||||
/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the
|
||||
/// key store alone, never from a file, which anyone can edit, and it is never lowered again.
|
||||
fn raise_generation(dir: &Path) -> Option<u64> {
|
||||
let folder = plugin_store_key(dir);
|
||||
let raised = grant_keys::current_generation(&folder).and_then(|generation| {
|
||||
// A signed write goes one past the raised generation, so that one must fit too.
|
||||
let next = generation.checked_add(3).and(generation.checked_add(2));
|
||||
let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?;
|
||||
grant_keys::set_current_generation(&folder, next).map(|()| next)
|
||||
});
|
||||
match raised {
|
||||
Ok(generation) => Some(generation),
|
||||
Err(e) => {
|
||||
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything →
|
||||
/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key,
|
||||
/// and left as it is when it holds none, since no file is then signed. `false`, with a log record,
|
||||
/// when the key store can't read or keep it. Call it in the store's turn ([`StoreTurn`]).
|
||||
fn retire_signed_copies(dir: &Path) -> bool {
|
||||
match grant_keys::current_key() {
|
||||
Ok(None) => true,
|
||||
Ok(Some(_)) => raise_generation(dir).is_some(),
|
||||
Err(e) => {
|
||||
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the grants file of a plug-in store gave no grants.
|
||||
struct GrantsError {
|
||||
/// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is
|
||||
@@ -2072,8 +2335,10 @@ struct GrantsError {
|
||||
}
|
||||
|
||||
/// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too
|
||||
/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an
|
||||
/// invalid id, is kept in [`GrantsFile::other`] with a log record.
|
||||
/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it),
|
||||
/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An
|
||||
/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`]
|
||||
/// with a log record.
|
||||
fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
let path = dir.join(GRANTS_FILE);
|
||||
let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) {
|
||||
@@ -2084,8 +2349,23 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
if bytes.len() as u64 > MAX_GRANTS_FILE {
|
||||
return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) });
|
||||
}
|
||||
let entries = serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?;
|
||||
let mut file = GrantsFile::default();
|
||||
let not_a_list = |why: String| GrantsError { unread: false, why };
|
||||
let (entries, trust) = match serde_json::from_slice::<serde_json::Value>(&bytes).map_err(|e| not_a_list(e.to_string()))? {
|
||||
serde_json::Value::Array(entries) => (entries, Trust::Unsigned),
|
||||
serde_json::Value::Object(_) => {
|
||||
let signed = serde_json::from_slice::<SignedGrants>(&bytes).map_err(|e| not_a_list(e.to_string()))?;
|
||||
let trust = trust_of(dir, &signed);
|
||||
(signed.grants, trust)
|
||||
}
|
||||
_ => return Err(not_a_list("not a list of grants".into())),
|
||||
};
|
||||
if trust == Trust::Unsigned {
|
||||
log::warn!(
|
||||
"the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() };
|
||||
let mut first_error = None;
|
||||
for entry in entries {
|
||||
let why = match serde_json::from_value::<vectorcraft_plugins::permissions::Grant>(entry.clone()) {
|
||||
@@ -2106,11 +2386,19 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
}
|
||||
|
||||
/// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when
|
||||
/// there is no grants file, and none, with a log record, when it is too large, can't be read or
|
||||
/// doesn't hold a list.
|
||||
/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked
|
||||
/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a
|
||||
/// list.
|
||||
fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
match read_grants(dir) {
|
||||
Ok(file) => file.grants,
|
||||
signed_grants(dir, &read_grants(dir))
|
||||
}
|
||||
|
||||
/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`]
|
||||
/// read it.
|
||||
fn signed_grants(dir: &Path, file: &Result<GrantsFile, GrantsError>) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
match file {
|
||||
Ok(file) if file.trust == Trust::Signed => file.grants.clone(),
|
||||
Ok(_) => BTreeMap::new(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
|
||||
@@ -0,0 +1,541 @@
|
||||
//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an
|
||||
//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of
|
||||
//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps
|
||||
//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one
|
||||
//! an older version wrote, one another program wrote or changed, one copied from another folder or
|
||||
//! machine) grants nothing.
|
||||
//!
|
||||
//! The key store also keeps a generation for each plug-in folder, raised on every signed write of
|
||||
//! its grants file and never lowered, and the file carries its generation inside the MAC. A file
|
||||
//! whose generation is not the one kept (an earlier copy put back over the current file, or a write
|
||||
//! whose generation the key store didn't keep or that failed after the raise) grants nothing either.
|
||||
//!
|
||||
//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's
|
||||
//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key
|
||||
//! store can't be reached: a grant holds for the session only.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
|
||||
/// The length of a key, in bytes, and of the MAC.
|
||||
pub const KEY_LEN: usize = 32;
|
||||
|
||||
/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct GrantKey([u8; KEY_LEN]);
|
||||
|
||||
impl GrantKey {
|
||||
/// The key with the bytes `bytes`.
|
||||
pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self {
|
||||
GrantKey(bytes)
|
||||
}
|
||||
|
||||
/// A new key from the system's random source.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn random() -> Result<Self, KeyStoreError> {
|
||||
let mut bytes = [0u8; KEY_LEN];
|
||||
getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?;
|
||||
Ok(GrantKey(bytes))
|
||||
}
|
||||
|
||||
/// The browser keeps no grants file.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn random() -> Result<Self, KeyStoreError> {
|
||||
Err(KeyStoreError("there is no key store".into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for GrantKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("GrantKey(..)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a key store gave no key or didn't keep one. The message never holds key bytes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{0}")]
|
||||
pub struct KeyStoreError(pub String);
|
||||
|
||||
/// Where the key of grants files is kept.
|
||||
pub trait GrantKeyStore: Send + Sync {
|
||||
/// The key kept, `None` when there is none; an error when the store can't be reached or read.
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError>;
|
||||
/// Keep `key` in place of any kept before.
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>;
|
||||
/// The key kept, after making and keeping a new one when there is none. The key returned is the
|
||||
/// one read back from the store, so a key another process kept first wins.
|
||||
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
|
||||
if let Some(key) = self.key()? {
|
||||
return Ok(key);
|
||||
}
|
||||
self.set_key(&GrantKey::random()?)?;
|
||||
self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
|
||||
}
|
||||
/// The generation kept for the grants file of the plug-in store whose folder is `folder`
|
||||
/// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept.
|
||||
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError>;
|
||||
/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`.
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>;
|
||||
}
|
||||
|
||||
/// A key store in memory: the key and the generations last as long as the store. For tests and
|
||||
/// embedders.
|
||||
#[derive(Default)]
|
||||
pub struct MemoryGrantKeys {
|
||||
key: Mutex<Option<GrantKey>>,
|
||||
generations: Mutex<BTreeMap<PathBuf, u64>>,
|
||||
}
|
||||
|
||||
impl MemoryGrantKeys {
|
||||
/// A store that holds `key`.
|
||||
pub fn with_key(key: GrantKey) -> Self {
|
||||
MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl GrantKeyStore for MemoryGrantKeys {
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone())
|
||||
}
|
||||
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
|
||||
*self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError> {
|
||||
Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied())
|
||||
}
|
||||
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The key store of the process ([`set_grant_key_store`]).
|
||||
static PROCESS_STORE: Mutex<Option<Arc<dyn GrantKeyStore>>> = Mutex::new(None);
|
||||
|
||||
/// The one memory store of [`keep_grant_keys_in_memory`].
|
||||
static SHARED_MEMORY: LazyLock<Arc<MemoryGrantKeys>> = LazyLock::new(Arc::default);
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the key store this thread uses in place of the process's.
|
||||
pub(crate) static THREAD_STORE: std::cell::RefCell<Option<Arc<dyn GrantKeyStore>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no
|
||||
/// key store, so grants hold for the session only).
|
||||
pub fn set_grant_key_store(store: Option<Arc<dyn GrantKeyStore>>) {
|
||||
*PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store;
|
||||
}
|
||||
|
||||
/// Keep the key in memory for the rest of the process, one key for every caller: grants files
|
||||
/// written in the process count in it, and not in another process. For tests.
|
||||
pub fn keep_grant_keys_in_memory() {
|
||||
let shared: Arc<dyn GrantKeyStore> = SHARED_MEMORY.clone();
|
||||
set_grant_key_store(Some(shared));
|
||||
}
|
||||
|
||||
/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the
|
||||
/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service
|
||||
/// `org.storytold.vectorcraft.plugin-grants`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn use_os_grant_keys() {
|
||||
set_grant_key_store(Some(Arc::new(OsGrantKeys::default())));
|
||||
}
|
||||
|
||||
/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory
|
||||
/// store when the process set none.
|
||||
fn current_store() -> Option<Arc<dyn GrantKeyStore>> {
|
||||
#[cfg(test)]
|
||||
if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) {
|
||||
return Some(store);
|
||||
}
|
||||
let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
#[cfg(test)]
|
||||
let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc<dyn GrantKeyStore>));
|
||||
store
|
||||
}
|
||||
|
||||
/// The key kept for grants files: `None` when there is none yet, an error when there is no key
|
||||
/// store or it can't be reached.
|
||||
pub(crate) fn current_key() -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key()
|
||||
}
|
||||
|
||||
/// The key to sign a grants file with: the one kept, else a new one, kept first
|
||||
/// ([`GrantKeyStore::create_key`]).
|
||||
pub(crate) fn signing_key() -> Result<GrantKey, KeyStoreError> {
|
||||
let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?;
|
||||
match store.key()? {
|
||||
Some(key) => Ok(key),
|
||||
None => store.create_key(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when
|
||||
/// none is kept yet, an error when there is no key store or it can't be reached.
|
||||
pub(crate) fn current_generation(folder: &Path) -> Result<u64, KeyStoreError> {
|
||||
Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept
|
||||
/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a
|
||||
/// lower one could match a file signed before.
|
||||
pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?;
|
||||
if store.generation(folder)?.is_some_and(|kept| generation < kept) {
|
||||
return Err(KeyStoreError("the key store keeps a later generation".into()));
|
||||
}
|
||||
store.set_generation(folder, generation)
|
||||
}
|
||||
|
||||
/// The start of every MAC input: what it is a MAC of, and the version of the file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0";
|
||||
|
||||
/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose
|
||||
/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation
|
||||
/// go in with their lengths first.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option<hmac::Hmac<sha2::Sha256>> {
|
||||
use hmac::Mac;
|
||||
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&key.0).ok()?;
|
||||
let folder = folder.as_os_str().as_encoded_bytes();
|
||||
let generation = generation.to_be_bytes();
|
||||
mac.update(DOMAIN);
|
||||
mac.update(&(folder.len() as u64).to_be_bytes());
|
||||
mac.update(folder);
|
||||
mac.update(&(generation.len() as u64).to_be_bytes());
|
||||
mac.update(&generation);
|
||||
mac.update(grants);
|
||||
Some(mac)
|
||||
}
|
||||
|
||||
/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option<String> {
|
||||
use hmac::Mac;
|
||||
Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]),
|
||||
/// compared in constant time; a shorter or longer tag is not.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool {
|
||||
use hmac::Mac;
|
||||
let Some(tag) = from_hex(tag) else { return false };
|
||||
mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok())
|
||||
}
|
||||
|
||||
/// The browser keeps no grants file.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The browser keeps no grants file.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them;
|
||||
/// `None` for anything else.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn from_hex(tag: &str) -> Option<Vec<u8>> {
|
||||
let digits = tag.as_bytes();
|
||||
let (pairs, rest) = digits.as_chunks::<2>();
|
||||
if !rest.is_empty() || pairs.len() > KEY_LEN {
|
||||
return None;
|
||||
}
|
||||
let digit = |d: u8| match d {
|
||||
b'0'..=b'9' => Some(d - b'0'),
|
||||
b'a'..=b'f' => Some(d - b'a' + 10),
|
||||
_ => None,
|
||||
};
|
||||
pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect()
|
||||
}
|
||||
|
||||
/// The system's key store, through `keyring-core` and the store crate of the platform. The key is
|
||||
/// read from the store each time it is needed. The key and the generations are kept as lower-case
|
||||
/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct OsGrantKeys {
|
||||
/// Held while a key is kept, so that the threads of the process that make the first key at the
|
||||
/// same time keep one.
|
||||
making: Mutex<()>,
|
||||
/// The connection to the system's key store, once one is made. A failed connection is not
|
||||
/// kept, and a kept one is dropped when the key store can't be reached through it or fails
|
||||
/// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after
|
||||
/// VectorCraft, or restarts, is used.
|
||||
store: Mutex<Option<Arc<keyring_core::CredentialStore>>>,
|
||||
/// How a connection is made ([`connect`]).
|
||||
connect: fn() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Default for OsGrantKeys {
|
||||
fn default() -> Self {
|
||||
OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl OsGrantKeys {
|
||||
const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants";
|
||||
const ACCOUNT: &str = "hmac-sha256-v1";
|
||||
|
||||
/// The system's key store: the connection made before, else a new one.
|
||||
fn store(&self) -> Result<Arc<keyring_core::CredentialStore>, KeyStoreError> {
|
||||
let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(store) = store.as_ref() {
|
||||
return Ok(store.clone());
|
||||
}
|
||||
Ok(store.insert((self.connect)().map_err(store_error)?).clone())
|
||||
}
|
||||
|
||||
/// What the key store error `e` says ([`store_error`]). When the key store can't be reached or
|
||||
/// fails, the connection is dropped first, so the next call makes a new one: the Secret Service
|
||||
/// loses the session of a connection when it restarts. An entry that isn't there keeps it.
|
||||
fn failed(&self, e: keyring_core::Error) -> KeyStoreError {
|
||||
if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) {
|
||||
*self.store.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
store_error(e)
|
||||
}
|
||||
|
||||
fn entry(&self, account: &str) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e))
|
||||
}
|
||||
|
||||
fn key_entry(&self) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
self.entry(Self::ACCOUNT)
|
||||
}
|
||||
|
||||
/// The key the system's key store keeps, read from it.
|
||||
fn stored(&self, entry: &keyring_core::Entry) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
match entry.get_secret() {
|
||||
// A secret that is not 64 hexadecimal digits is not a key this version made: there is none.
|
||||
Ok(secret) => Ok(std::str::from_utf8(&secret)
|
||||
.ok()
|
||||
.and_then(from_hex)
|
||||
.and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok())
|
||||
.map(GrantKey)),
|
||||
Err(keyring_core::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(self.failed(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the generation of the plug-in store whose folder is `folder`: the account
|
||||
/// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits.
|
||||
fn generation_entry(&self, folder: &Path) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
use sha2::Digest;
|
||||
let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes());
|
||||
self.entry(&format!("generation-v1-{}", to_hex(&digest)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the
|
||||
/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2
|
||||
/// uses, so entries it kept are read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn connect() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let store: Arc<keyring_core::CredentialStore> = apple_native_keyring_store::keychain::Store::new()?;
|
||||
Ok(store)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let store: Arc<keyring_core::CredentialStore> = windows_native_keyring_store::Store::new()?;
|
||||
Ok(store)
|
||||
}
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))]
|
||||
{
|
||||
let store: Arc<keyring_core::CredentialStore> = zbus_secret_service_keyring_store::Store::new()?;
|
||||
Ok(store)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))]
|
||||
Err(keyring_core::Error::NoDefaultStore)
|
||||
}
|
||||
|
||||
/// `bytes` as lower-case hexadecimal digits.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn to_hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl GrantKeyStore for OsGrantKeys {
|
||||
/// Read from the key store each time, so that a key removed or replaced there is not used.
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
self.stored(&self.key_entry()?)
|
||||
}
|
||||
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
|
||||
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e))
|
||||
}
|
||||
|
||||
/// Reads the key store again and makes the key only while holding [`creation_lock`], so that
|
||||
/// processes of this user that make the first key at the same time all keep the first one made.
|
||||
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
|
||||
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = self.key_entry()?;
|
||||
if let Some(key) = self.stored(&entry)? {
|
||||
return Ok(key);
|
||||
}
|
||||
let _turn = creation_lock()?;
|
||||
match self.stored(&entry)? {
|
||||
Some(key) => Ok(key),
|
||||
None => {
|
||||
entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?;
|
||||
self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read from the key store each time, since another process on the folder may have raised it.
|
||||
/// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed
|
||||
/// with it.
|
||||
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError> {
|
||||
match self.generation_entry(folder)?.get_secret() {
|
||||
Ok(secret) => std::str::from_utf8(&secret)
|
||||
.ok()
|
||||
.and_then(from_hex)
|
||||
.and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok())
|
||||
.map(|bytes| Some(u64::from_be_bytes(bytes)))
|
||||
.ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())),
|
||||
Err(keyring_core::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(self.failed(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e))
|
||||
}
|
||||
}
|
||||
|
||||
/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is
|
||||
/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary
|
||||
/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file
|
||||
/// can't be locked: no key is made then.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn creation_lock() -> Result<std::fs::File, KeyStoreError> {
|
||||
#[cfg(windows)]
|
||||
let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%");
|
||||
#[cfg(target_os = "macos")]
|
||||
let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR");
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR");
|
||||
let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute());
|
||||
let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?;
|
||||
let file = std::fs::File::options()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(dir.join("vectorcraft-plugin-grant-key.lock"))
|
||||
.map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?;
|
||||
file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// What a key store error says, without the secret some of them hold.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn store_error(e: keyring_core::Error) -> KeyStoreError {
|
||||
KeyStoreError(match e {
|
||||
keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"),
|
||||
keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"),
|
||||
keyring_core::Error::NoDefaultStore => "there is no key store".into(),
|
||||
_ => "the key store can't read or keep the key".into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use keyring_core::api::CredentialStoreApi;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Connections asked for from [`flaky`].
|
||||
static TRIES: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The store [`flaky`] connects to.
|
||||
static MOCK: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
|
||||
/// A key store that can't be reached on the first try and is reached on every later one.
|
||||
fn flaky() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
if TRIES.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
return Err(keyring_core::Error::NoDefaultStore);
|
||||
}
|
||||
let store: Arc<keyring_core::CredentialStore> = MOCK.clone();
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// Connections asked for from [`restarting`].
|
||||
static RESTARTS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The store [`restarting`] connects to first.
|
||||
static BEFORE: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
/// The store [`restarting`] connects to on every later try.
|
||||
static AFTER: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
|
||||
/// A key store that restarts after the first connection: later connections reach another store.
|
||||
fn restarting() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
let store: Arc<keyring_core::CredentialStore> = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() };
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// A connection that the key store can't be reached through is dropped, and the next call
|
||||
/// connects again; an entry that isn't there keeps the connection.
|
||||
#[test]
|
||||
fn the_system_key_store_reconnects_after_it_restarts() {
|
||||
let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() };
|
||||
assert_eq!(keys.key().unwrap(), None, "no key is kept yet");
|
||||
keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap();
|
||||
assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection");
|
||||
|
||||
AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap();
|
||||
let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap();
|
||||
let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap();
|
||||
cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into()));
|
||||
assert!(keys.key().is_err(), "the connection fails");
|
||||
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection");
|
||||
assert_eq!(RESTARTS.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// The secret `MOCK` keeps for `account`, as it is kept.
|
||||
fn kept(account: &str) -> Vec<u8> {
|
||||
MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap()
|
||||
}
|
||||
|
||||
/// The system key store is connected again after a connection fails, the key and the
|
||||
/// generations are kept as hexadecimal text, and the key is read from the store each time; a
|
||||
/// value kept as raw bytes is not read as a key or a generation.
|
||||
#[test]
|
||||
fn the_system_key_store_reconnects_and_keeps_text() {
|
||||
let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() };
|
||||
assert!(keys.key().is_err(), "the first connection fails");
|
||||
let key = GrantKey::from_bytes([0xa7; KEY_LEN]);
|
||||
keys.set_key(&key).unwrap();
|
||||
assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text");
|
||||
assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back");
|
||||
|
||||
let folder = Path::new("/plug-ins");
|
||||
keys.set_generation(folder, 0x1_0000_0005).unwrap();
|
||||
let account = format!("generation-v1-{}", to_hex(&<sha2::Sha256 as sha2::Digest>::digest(folder.as_os_str().as_encoded_bytes())));
|
||||
assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text");
|
||||
assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005));
|
||||
|
||||
MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap();
|
||||
assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error");
|
||||
MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap();
|
||||
assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read");
|
||||
MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap();
|
||||
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used");
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() {
|
||||
assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}");
|
||||
}
|
||||
|
||||
/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the
|
||||
/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no
|
||||
/// error.
|
||||
#[test]
|
||||
fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap();
|
||||
let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
let bucket = s.execute("color.contrast", &json!({})).unwrap();
|
||||
assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}");
|
||||
assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}");
|
||||
// A second selected object drawn at another opacity does not make the answer ambiguous.
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
|
||||
let both = s.execute("color.contrast", &json!({})).unwrap();
|
||||
assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_translucent_group_counts_for_the_art_inside_it() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -232,6 +232,29 @@ fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() {
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
|
||||
/// Parts of an outline that lie on the mask's edge show: a square without a fill, clipped by a mask
|
||||
/// of the same square, keeps all four sides and bounds its whole area. A square just outside the
|
||||
/// mask is hidden and bounds nothing.
|
||||
#[test]
|
||||
fn fill_area_keeps_outline_parts_on_the_mask_edge() {
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0);
|
||||
deselect(&mut s);
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
|
||||
assert!((area(&s, id_of(&r)) - 10000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
|
||||
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, -0.005, -0.005, 100.01, 100.01);
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0);
|
||||
deselect(&mut s);
|
||||
let (undo, kids) = (undo_len(&s), stack(&s));
|
||||
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).is_err());
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
|
||||
/// In a clipping group inside another, clipped art shows only where both masks show it.
|
||||
#[test]
|
||||
fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() {
|
||||
@@ -305,6 +328,39 @@ fn fill_area_stays_inside_the_isolated_group() {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer());
|
||||
}
|
||||
|
||||
/// In isolation mode, `ids` naming the isolated group, or the layer or a group that holds it, takes
|
||||
/// every path of the isolated group. The other paths of that layer or group, and other listed
|
||||
/// objects outside the isolated group, do not bound areas.
|
||||
#[test]
|
||||
fn fill_area_ids_naming_what_holds_the_isolated_group_take_its_paths() {
|
||||
let mut s = session();
|
||||
let outside =
|
||||
[line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))];
|
||||
let lines = triangle(&mut s);
|
||||
let ids: Vec<u64> = lines.iter().map(|l| l.0).collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let outer = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
deselect(&mut s);
|
||||
let layer = s.doc().unwrap().doc.default_layer().unwrap();
|
||||
let (undo, kids) = (undo_len(&s), stack(&s));
|
||||
for named in [vec![layer.0], vec![outer.0], vec![g.0], vec![layer.0, outside[0].0]] {
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named}));
|
||||
assert!(r.is_err(), "the area outside the isolated group, ids {named:?}");
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids.clone()));
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).unwrap();
|
||||
let new = id_of(&r);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g), "ids {named:?}");
|
||||
assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
let named: Vec<u64> = outside.iter().map(|l| l.0).collect();
|
||||
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).is_err(), "only art outside it listed");
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
|
||||
/// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and
|
||||
/// changes nothing: the compound path cannot hold the new path. The same goes for an isolated
|
||||
/// Objects on Path group, a group with a Transform effect and a group that is a clipping mask.
|
||||
|
||||
@@ -4644,6 +4644,47 @@ fn a_ruler_guide_rotates_with_the_selected_art() {
|
||||
assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s));
|
||||
}
|
||||
|
||||
/// The reply to a transform lists the guide paths it makes of ruler guides: for a guide alone,
|
||||
/// with a copy, beside selected art and beside direct-selected anchors.
|
||||
#[test]
|
||||
fn a_transform_replies_with_the_guide_paths_it_makes() {
|
||||
fn reply_ids(r: &Value) -> Vec<NodeId> {
|
||||
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
|
||||
}
|
||||
let mut s = session();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
// A copy keeps the ruler guide and adds a guide path, the only new object.
|
||||
let r = s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap();
|
||||
let [copy] = selected(&s)[..] else { panic!("the copy is selected") };
|
||||
assert_eq!(reply_ids(&r), vec![copy]);
|
||||
// Without a copy the guide becomes a guide path.
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let [path] = selected(&s)[..] else { panic!("one guide path selected") };
|
||||
assert_ne!(path, copy);
|
||||
assert_eq!(reply_ids(&r), vec![path]);
|
||||
// With art selected, the reply lists the art and then the guide path.
|
||||
let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
|
||||
sel(&mut s, &[a]);
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
let r = s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
let paths: Vec<NodeId> = selected(&s).into_iter().filter(|id| *id != a).collect();
|
||||
let [mixed] = paths[..] else { panic!("the guide path is selected with the art") };
|
||||
assert_eq!(reply_ids(&r), vec![a, mixed]);
|
||||
// With direct-selected anchors, the guide path joins the reply too.
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
assert!(!s.doc().unwrap().selection.anchors.is_empty());
|
||||
let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let anchored: Vec<NodeId> = selected(&s).into_iter().filter(|id| *id != a).collect();
|
||||
let [made] = anchored[..] else { panic!("the guide path is selected with the path") };
|
||||
assert!(line_ends(&s, made).1, "it is a guide path");
|
||||
assert!(reply_ids(&r).contains(&made), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruler_guides_and_lock() {
|
||||
let mut s = session();
|
||||
|
||||
+1323
-55
File diff suppressed because it is too large.
Load diff
@@ -216,6 +216,24 @@ fn reset_category_and_all() {
|
||||
assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err());
|
||||
}
|
||||
|
||||
/// `prefs.reset` records each category it reset once, `None` for every category, and a failed
|
||||
/// reset records nothing.
|
||||
#[test]
|
||||
fn prefs_reset_records_the_categories_it_reset() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.take_prefs_resets().is_empty());
|
||||
s.execute("prefs.reset", &json!({"category": "general"})).unwrap();
|
||||
s.execute("prefs.reset", &json!({"category": "General"})).unwrap();
|
||||
assert_eq!(s.take_prefs_resets(), vec![Some("General")]);
|
||||
assert!(s.take_prefs_resets().is_empty(), "taking clears the list");
|
||||
assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err());
|
||||
assert!(s.execute("prefs.reset", &json!({"category": 5})).is_err());
|
||||
assert!(s.take_prefs_resets().is_empty(), "a failed reset records nothing");
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
s.execute("prefs.reset", &json!({"category": "Type"})).unwrap();
|
||||
assert_eq!(s.take_prefs_resets(), vec![None, Some("Type")]);
|
||||
}
|
||||
|
||||
/// A rectangle made into a guide path; nothing is selected after.
|
||||
fn guide_path(s: &mut Session, x: f64) -> NodeId {
|
||||
let id = square(s, x, 0.0);
|
||||
|
||||
@@ -680,9 +680,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
fn stale_documents_throw_on_every_member() {
|
||||
let (mut s, _, _) = doc();
|
||||
run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap();
|
||||
for (member, message) in
|
||||
[("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")]
|
||||
{
|
||||
for (member, message) in [
|
||||
("d.typename", "Stale document"),
|
||||
("d.parent", "Stale document"),
|
||||
("p.typename", "Stale document"),
|
||||
("p.toString()", "Stale document"),
|
||||
("l.typename", "Stale"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("#targetengine keep\n{member};"));
|
||||
assert!(e.contains(message), "{member}: {e}");
|
||||
}
|
||||
@@ -1363,6 +1367,70 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_menu_command_runs_its_command_on_the_selection() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, "app.executeMenuCommand('ungroup'); vc.log(app.activeDocument.selection.length);");
|
||||
assert_eq!(out, vec![json!(2)]);
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(g).is_none(), "the group is gone");
|
||||
assert!(st.doc.node(a).is_some() && st.doc.node(b).is_some());
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
// With nothing selected the menu item does nothing and adds no undo step.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
log(&mut s, "app.executeMenuCommand('ungroup'); app.executeMenuCommand('releaseMask');");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "nothing changed");
|
||||
// selectall then group makes one group of both rectangles.
|
||||
let out = log(&mut s, "app.executeMenuCommand('selectall'); app.executeMenuCommand('group'); vc.log(app.activeDocument.selection[0].typename);");
|
||||
assert_eq!(out, vec![json!("GroupItem")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fit_to_artwork_menu_command_fits_the_artboard_to_the_art() {
|
||||
let (mut s, _, _) = doc();
|
||||
let before = s.active().unwrap().doc.artboards[0].rect;
|
||||
log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds');");
|
||||
let after = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert!(after.width() < before.width() && after.height() < before.height(), "{before:?} -> {after:?}");
|
||||
// An artboard that is locked, or has no art on it, leaves the menu item dimmed: it does nothing.
|
||||
let (mut s, _, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]);
|
||||
assert_eq!(s.active().unwrap().doc.artboards[0].rect, before);
|
||||
assert_eq!(undo_steps(&s), steps, "locked");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let empty = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]);
|
||||
assert_eq!(s.active().unwrap().doc.artboards[0].rect, empty);
|
||||
assert_eq!(undo_steps(&s), 0, "no art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_menu_command_throws_and_names_it() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');");
|
||||
assert!(e.contains("acmeNoSuchMenu"), "{e}");
|
||||
assert!(failure(&mut s, "app.executeMenuCommand('Ungroup');").contains("Ungroup"), "names are matched exactly");
|
||||
assert!(failure(&mut s, "app.executeMenuCommand(5);").contains("string"));
|
||||
assert!(failure(&mut s, "app.executeMenuCommand();").contains("string"));
|
||||
assert!(failure(&mut s, "app.executeMenuCommand(new Array(5000).join('a'));").contains("too long"));
|
||||
assert_eq!(undo_steps(&s), steps, "nothing changed");
|
||||
// With no document open a known menu item does nothing, and an unknown one still throws.
|
||||
let mut s = Session::new();
|
||||
assert_eq!(log(&mut s, "app.executeMenuCommand('selectall'); vc.log(app.documents.length);"), vec![json!(0)]);
|
||||
assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_dom_values_do_not_reenter_or_exceed_limits() {
|
||||
let (mut s, _, _) = doc();
|
||||
|
||||
@@ -692,3 +692,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_has_promise_and_a_jsx_script_does_not() {
|
||||
let base = folder("promise-realm");
|
||||
let main = base.join("main/main.js");
|
||||
write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);");
|
||||
let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["log"], json!(["function", 1, 2]));
|
||||
assert!(r.get("unhandledRejections").is_none(), "{r}");
|
||||
let r = run(&base, "vc.log(typeof Promise);").unwrap();
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() {
|
||||
let base = folder("promise-engine");
|
||||
let jsx = base.join("main/a.jsx");
|
||||
let js = base.join("main/b.js");
|
||||
let mut s = Session::new();
|
||||
let mut go = |path: &Path, text: &str| {
|
||||
write(path, text);
|
||||
s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone()
|
||||
};
|
||||
assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"]));
|
||||
assert_eq!(
|
||||
go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"),
|
||||
json!([1, "function", 2])
|
||||
);
|
||||
assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() {
|
||||
let base = folder("promise-rejections");
|
||||
write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n");
|
||||
let main = base.join("main/main.js");
|
||||
write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
let got: Vec<(String, u64, Option<bool>)> = r["unhandledRejections"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc"))))
|
||||
.collect();
|
||||
assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}");
|
||||
assert_eq!(r["unhandledRejectionCount"], 2);
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect();
|
||||
assert_eq!(errors.len(), 2, "{errors:?}");
|
||||
assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}");
|
||||
assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}");
|
||||
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: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"),
|
||||
("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window 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"),
|
||||
|
||||
@@ -267,6 +267,25 @@ fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
|
||||
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
|
||||
}
|
||||
|
||||
/// A shared Liquify brush size set through another Liquify tool during a held press survives the
|
||||
/// dropped press, also when the set value equals the size the press's drag has made current.
|
||||
#[test]
|
||||
fn a_shared_option_set_through_another_tool_during_a_dropped_press_is_kept() {
|
||||
let mut s = session();
|
||||
select(&mut s, "warp");
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
|
||||
let before = s.tool_options()["width"].as_f64().unwrap();
|
||||
// The press's own change to the shared size, not stored.
|
||||
s.tool.set_option("width", &json!(before + 40.0));
|
||||
let current = s.tool_options()["width"].clone();
|
||||
s.set_tool_option_cmd(&json!({"tool": "pucker", "key": "width", "value": before + 40.0})).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(s.tool_options()["width"], current, "the tool keeps the size set through the other tool");
|
||||
assert_eq!(s.prefs.tool_settings["liquify"]["width"], current, "and stores it");
|
||||
}
|
||||
|
||||
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
|
||||
/// the next click.
|
||||
#[test]
|
||||
|
||||
@@ -1582,7 +1582,15 @@ impl Session {
|
||||
let set = other.id();
|
||||
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
|
||||
}
|
||||
self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed);
|
||||
// Another tool's set also names the keys of the stores it shares with the pressed tool.
|
||||
let shared: Vec<&str> = match (self.pressed_tool().map(|t| t.id()), id) {
|
||||
(Some(pressed), Some(set)) if pressed != set => settings::stores(pressed)
|
||||
.filter(|(store, _)| settings::stores(set).any(|(s, _)| s == *store))
|
||||
.flat_map(|(_, keys)| keys.iter().copied())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed);
|
||||
// The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one.
|
||||
if (active || lender) && values.contains_key("stop") {
|
||||
let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper";
|
||||
|
||||
@@ -82,8 +82,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \
|
||||
selection selection= toString typename",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
|
||||
getIsFileOpen selection selection= toString typename",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
|
||||
@@ -39,6 +39,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() {
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let ids = ["test.clearcache.a", "test.clearcache.b"];
|
||||
vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory();
|
||||
let mut s = Session::new();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
|
||||
@@ -1011,6 +1011,7 @@ proptest! {
|
||||
let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id())));
|
||||
let _ = std::fs::remove_dir_all(&store.0);
|
||||
let folder = store.0.clone();
|
||||
vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory();
|
||||
let mut s = Session::new();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
s.attach_plugin_store(folder.clone());
|
||||
|
||||
@@ -59,11 +59,13 @@ fn installed(id: &str) -> bool {
|
||||
vectorcraft_plugins::registry::get(id).is_some()
|
||||
}
|
||||
|
||||
/// A new launch: nothing installed, the plug-in folder `dir` attached.
|
||||
/// A new launch: nothing installed, the plug-in folder `dir` attached, its grants' key kept in
|
||||
/// memory.
|
||||
fn launch(dir: &std::path::Path) -> Session {
|
||||
for p in vectorcraft_plugins::registry::list() {
|
||||
vectorcraft_plugins::registry::remove(p.id());
|
||||
}
|
||||
vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory();
|
||||
let mut s = Session::new();
|
||||
s.attach_plugin_store(dir.to_path_buf());
|
||||
s
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the
|
||||
//! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`,
|
||||
//! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex
|
||||
//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with
|
||||
//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in
|
||||
//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and
|
||||
//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in
|
||||
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and
|
||||
//! the iterators of arrays, strings and `arguments` objects (in `iterator`).
|
||||
//!
|
||||
@@ -17,6 +17,7 @@ pub(crate) mod iterator;
|
||||
mod json;
|
||||
mod math;
|
||||
mod object;
|
||||
pub(crate) mod promise;
|
||||
mod symbol;
|
||||
|
||||
use std::rc::Rc;
|
||||
@@ -242,6 +243,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
method(interp, function_proto, "bind", function_bind, 1)?;
|
||||
method(interp, function_proto, "toString", function_to_string, 0)?;
|
||||
|
||||
let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?;
|
||||
constructor(interp, "Boolean", boolean, boolean_proto)?;
|
||||
method(interp, boolean_proto, "toString", boolean_to_string, 0)?;
|
||||
method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?;
|
||||
|
||||
@@ -262,6 +265,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
if interp.options.e4x {
|
||||
crate::xml_builtins::install(interp)?;
|
||||
}
|
||||
if interp.options.es2015 {
|
||||
promise::install(interp)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -516,6 +522,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J
|
||||
Ok(Value::str(&format!("[object {class}]")))
|
||||
}
|
||||
|
||||
/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2).
|
||||
fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult<Value> {
|
||||
let b = args.first().is_some_and(Value::truthy);
|
||||
if !construct {
|
||||
return Ok(Value::Bool(b));
|
||||
}
|
||||
let proto = interp.intrinsics.boolean_proto;
|
||||
Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto)))))
|
||||
}
|
||||
|
||||
/// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a
|
||||
/// primitive, or the primitive value of a Boolean object.
|
||||
fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult<bool> {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -407,6 +407,21 @@ fn boolean_prototype_converts_booleans() {
|
||||
throws("Object.getPrototypeOf(true).valueOf.call({})", "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_boolean_constructor_converts_and_wraps() {
|
||||
// Called as a function it gives ToBoolean of its argument (section 15.6.1).
|
||||
truth("Boolean() === false && Boolean(0) === false && Boolean('') === false && Boolean(NaN) === false && Boolean(null) === false");
|
||||
truth("Boolean(1) === true && Boolean('false') === true && Boolean({}) === true && Boolean(new Boolean(false)) === true");
|
||||
truth("['', 'a', 0, 2].filter(Boolean).length === 2");
|
||||
// With new it makes a Boolean object (section 15.6.2), which is truthy whatever it holds.
|
||||
truth("var b = new Boolean(0); typeof b === 'object' && b.valueOf() === false && !!b && b instanceof Boolean");
|
||||
assert_eq!(string("Object.prototype.toString.call(new Boolean(1)) + new Boolean('')"), "[object Boolean]false");
|
||||
// The constructor and Boolean.prototype are linked, and true and false look methods up there.
|
||||
truth("Boolean.prototype === Object.getPrototypeOf(true) && Boolean.prototype.constructor === Boolean && true.constructor === Boolean");
|
||||
truth("Boolean.length === 1 && Object(false) instanceof Boolean");
|
||||
truth("!Object.getOwnPropertyDescriptor(this, 'Boolean').enumerable && !Object.getOwnPropertyDescriptor(Boolean, 'prototype').writable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_methods_overwriting_elements_need_no_heap_for_new_ones() {
|
||||
// With the heap exactly at its limit, an array method's write over an existing element
|
||||
|
||||
+21
-1
@@ -268,6 +268,10 @@ pub(crate) enum Class {
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
/// A promise (ECMA-262 11th edition, section 25.6) and its state.
|
||||
Promise(Box<crate::builtins::promise::PromiseData>),
|
||||
/// The state that the functions a promise operation makes share; scripts never see it.
|
||||
PromiseRecord(Box<crate::builtins::promise::Record>),
|
||||
}
|
||||
|
||||
/// What an XML value is.
|
||||
@@ -331,7 +335,8 @@ impl Class {
|
||||
Class::XmlList(_) => "XMLList",
|
||||
Class::Namespace(_) => "Namespace",
|
||||
Class::QName { .. } => "QName",
|
||||
Class::XmlFilter(_) => "Object",
|
||||
Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object",
|
||||
Class::Promise(_) => "Promise",
|
||||
Class::Math => "Math",
|
||||
Class::Json => "JSON",
|
||||
Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
|
||||
@@ -779,6 +784,21 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
Class::Promise(p) => {
|
||||
for v in p.values() {
|
||||
mark_value(&v, work, strings);
|
||||
}
|
||||
if let Some((code, _)) = &p.site {
|
||||
mark_code(code, strings);
|
||||
}
|
||||
extra = p.bytes();
|
||||
}
|
||||
Class::PromiseRecord(r) => {
|
||||
for v in r.values() {
|
||||
mark_value(&v, work, strings);
|
||||
}
|
||||
extra = crate::builtins::promise::RECORD_BYTES;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra
|
||||
|
||||
@@ -91,6 +91,8 @@ pub(crate) struct Entry {
|
||||
parent: Option<u32>,
|
||||
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
|
||||
own: Rc<HashSet<Key>>,
|
||||
/// The names of the members this class declares as unavailable.
|
||||
unavailable: Rc<HashSet<Key>>,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
@@ -143,7 +145,9 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
|
||||
|
||||
impl Interp {
|
||||
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
|
||||
/// class, and `k` names an available member of that class or of a class it descends from.
|
||||
/// class, and `k` names an available member of that class or of a class it descends from. The
|
||||
/// nearest class that declares `k` decides, so a member a class declares unavailable is not
|
||||
/// reported even when a class it descends from has it.
|
||||
pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(false) };
|
||||
let mut class = Some(h.class);
|
||||
@@ -152,6 +156,9 @@ impl Interp {
|
||||
if e.own.contains(k) {
|
||||
return Ok(true);
|
||||
}
|
||||
if e.unavailable.contains(k) {
|
||||
return Ok(false);
|
||||
}
|
||||
class = e.parent;
|
||||
}
|
||||
Ok(false)
|
||||
@@ -307,7 +314,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
let r = fill_class(i, proto, &class);
|
||||
i.temp_roots.truncate(mark);
|
||||
let ctor = r?;
|
||||
let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect();
|
||||
let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
|
||||
let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::<HashSet<Key>>();
|
||||
i.host_classes.push(Entry {
|
||||
name: class.name.as_str().into(),
|
||||
proto,
|
||||
@@ -315,7 +323,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
index: class.index,
|
||||
family,
|
||||
parent: parent_class,
|
||||
own: Rc::new(members),
|
||||
own: Rc::new(names(members)),
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
});
|
||||
let global = i.global;
|
||||
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
|
||||
@@ -756,6 +756,53 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
|
||||
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
|
||||
let base = HostClass {
|
||||
name: "Base".into(),
|
||||
parent: None,
|
||||
members: vec![("size".to_string(), HostMember::Get(value.clone())), ("grow".to_string(), HostMember::Method(value))],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let leaf = HostClass {
|
||||
name: "Leaf".into(),
|
||||
parent: Some("Base".into()),
|
||||
members: vec![("size".to_string(), HostMember::Unavailable(missing))],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
|
||||
r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), it.hasOwnProperty('grow')].join()").unwrap();
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
|
||||
let mut r = realm(1_000_000);
|
||||
let calls: Rc<Cell<u32>> = Rc::default();
|
||||
let seen = calls.clone();
|
||||
let index: HostFunction = Rc::new(move |a| {
|
||||
seen.set(seen.get() + 1);
|
||||
match a.get(1) {
|
||||
Some(Data::Number(_)) => Ok(Data::Undefined),
|
||||
_ => Err(HostError::Error("no such member".into())),
|
||||
}
|
||||
});
|
||||
let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("List", &[1.0]))]).unwrap();
|
||||
r.start("Object.prototype.extra = 1; it.extra = 2; it.extra").unwrap();
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::Number(1.0));
|
||||
assert_eq!(calls.get(), 0);
|
||||
// A name nothing has still goes to the indexer, which throws.
|
||||
r.start("it.nope = 2").unwrap();
|
||||
assert!(finish(&mut r, 1_000_000).0.is_err());
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_converted_function_reads_each_argument_as_its_list_says() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
+91
-12
@@ -55,12 +55,37 @@ pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
|
||||
|
||||
/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]).
|
||||
fn description_hash(text: &str) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
text.hash(&mut h);
|
||||
let mut h = DescriptionHash::default();
|
||||
h.text(text);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// A [`description_hash`] fed the description's code units a run at a time, so a long string is
|
||||
/// hashed without being copied.
|
||||
#[derive(Default)]
|
||||
struct DescriptionHash(std::hash::DefaultHasher);
|
||||
|
||||
impl DescriptionHash {
|
||||
fn units(&mut self, units: &[u16]) {
|
||||
use std::hash::Hasher;
|
||||
for &u in units {
|
||||
self.0.write_u16(u);
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&mut self, text: &str) {
|
||||
use std::hash::Hasher;
|
||||
for u in text.encode_utf16() {
|
||||
self.0.write_u16(u);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
use std::hash::Hasher;
|
||||
self.0.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds of error object the engine throws.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ErrorType {
|
||||
@@ -354,6 +379,8 @@ pub(crate) struct Interp {
|
||||
pub(crate) error_mark: Option<u32>,
|
||||
/// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs.
|
||||
pub(crate) strict_writes: bool,
|
||||
/// `Promise` and the run's promise job queue ([`crate::builtins::promise`]).
|
||||
pub(crate) promises: crate::builtins::promise::Promises,
|
||||
/// The well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a
|
||||
/// realm with [`crate::Options::es2015`].
|
||||
pub(crate) symbols: crate::symbol::Symbols,
|
||||
@@ -625,6 +652,7 @@ impl Interp {
|
||||
finally_sites: Vec::new(),
|
||||
error_mark: None,
|
||||
strict_writes: false,
|
||||
promises: crate::builtins::promise::Promises::default(),
|
||||
symbols: crate::symbol::Symbols::default(),
|
||||
};
|
||||
// With `Options::es2015`, the first run names the built-in functions, under the limits
|
||||
@@ -676,7 +704,7 @@ impl Interp {
|
||||
let Value::Object(o) = v else { return true };
|
||||
let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true };
|
||||
let hash = *hash;
|
||||
description_hash(&self.describe(v)) != hash
|
||||
self.describe_hash(*o) != hash
|
||||
}
|
||||
|
||||
pub(crate) fn type_error(&mut self, message: &str) -> Abrupt {
|
||||
@@ -854,6 +882,7 @@ impl Interp {
|
||||
pub(crate) fn collect_garbage(&mut self) {
|
||||
self.drop_left_finally_marks();
|
||||
self.drop_left_finally_sites(self.stack.len());
|
||||
self.promises.forget_handled(&self.heap);
|
||||
let mut roots = Roots::default();
|
||||
roots.values.extend(self.stack.iter());
|
||||
roots.values.extend(self.temp_roots.iter());
|
||||
@@ -890,13 +919,20 @@ impl Interp {
|
||||
}
|
||||
self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0));
|
||||
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
|
||||
self.promises.add_roots(&mut roots);
|
||||
self.heap.collect(&roots);
|
||||
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
|
||||
// The collection counts the live total again, so bytes already released are not in it.
|
||||
self.held.released.set(0);
|
||||
self.flattened.set(0);
|
||||
self.heap.bytes =
|
||||
self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(self.symbols.registry_bytes());
|
||||
let queued = self.promises.queue_bytes();
|
||||
self.heap.bytes = self
|
||||
.heap
|
||||
.bytes
|
||||
.saturating_add(self.held_bytes)
|
||||
.saturating_add(self.held.now.get())
|
||||
.saturating_add(self.symbols.registry_bytes())
|
||||
.saturating_add(queued);
|
||||
}
|
||||
|
||||
/// Runs frames until the boundary frame on top returns, and returns its value.
|
||||
@@ -1904,16 +1940,18 @@ impl Interp {
|
||||
None => {}
|
||||
}
|
||||
let proto = self.object(id)?.proto;
|
||||
match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() {
|
||||
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
|
||||
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"),
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"),
|
||||
_ => {}
|
||||
}
|
||||
if !self.object(id)?.extensible {
|
||||
// A name that an object of a host class with an indexer lacks is read with the indexer
|
||||
// first, so assigning it throws what reading it throws.
|
||||
if array_index(&k).is_none()
|
||||
// A name that an object of a host class with an indexer lacks, and its prototypes lack
|
||||
// too, is read with the indexer first, so assigning it throws what reading it throws.
|
||||
if inherited.is_none()
|
||||
&& array_index(&k).is_none()
|
||||
&& let Some(f) = self.host_indexer(id)?
|
||||
{
|
||||
self.host_index(&f, id, Self::indexer_key(&k), false)?;
|
||||
@@ -3247,6 +3285,21 @@ impl Interp {
|
||||
r
|
||||
}
|
||||
|
||||
/// Starts a call to `f` with no frame running, for a promise job: a native or host function
|
||||
/// runs now and gives `Some` with its result, and a function written in JavaScript gets a
|
||||
/// boundary frame that the caller runs, and gives `None`. A host function called here cannot
|
||||
/// wait for its result, since no script code is running; a function written in JavaScript
|
||||
/// runs as the script's own code does.
|
||||
pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec<Value>) -> JsResult<Option<Value>> {
|
||||
self.reentry += 1;
|
||||
let prepared = self.prepare_call(f, this, args);
|
||||
self.reentry -= 1;
|
||||
match prepared? {
|
||||
Prepared::Done(v) => Ok(Some(v)),
|
||||
Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_rooted(&mut self, f: Value, this: Value, args: Vec<Value>, saved: usize) -> JsResult<Value> {
|
||||
match self.prepare_call(f, this, args)? {
|
||||
Prepared::Done(v) => Ok(v),
|
||||
@@ -4082,9 +4135,15 @@ impl Interp {
|
||||
/// A description of a thrown value that runs no JavaScript: `Name: message` for an error,
|
||||
/// the text of a primitive.
|
||||
pub(crate) fn describe(&mut self, v: &Value) -> String {
|
||||
let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() };
|
||||
self.describe_prefix(v, usize::MAX)
|
||||
}
|
||||
|
||||
/// [`Interp::describe`] with each string it reads cut to its first `max_units` code units
|
||||
/// before it is copied.
|
||||
pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String {
|
||||
let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) };
|
||||
let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) {
|
||||
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()),
|
||||
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)),
|
||||
_ => None,
|
||||
};
|
||||
match (data(self, "name"), data(self, "message")) {
|
||||
@@ -4094,6 +4153,26 @@ impl Interp {
|
||||
(None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read
|
||||
/// along its strings without copying them.
|
||||
fn describe_hash(&self, o: ObjId) -> u64 {
|
||||
let data = |k: &str| match self.find_property(o, &key(k)) {
|
||||
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s),
|
||||
_ => None,
|
||||
};
|
||||
let mut h = DescriptionHash::default();
|
||||
match (data("name"), data("message")) {
|
||||
(Some(n), Some(m)) if m.len() != 0 => {
|
||||
n.for_each_chunk(|c| h.units(c));
|
||||
h.text(": ");
|
||||
m.for_each_chunk(|c| h.units(c));
|
||||
}
|
||||
(Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)),
|
||||
(None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))),
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A compile failure, before it becomes an exception or a run error.
|
||||
|
||||
+20
-7
@@ -26,7 +26,7 @@
|
||||
//! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these
|
||||
//! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`),
|
||||
//! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String`
|
||||
//! (15.5), `Boolean.prototype`'s `toString` and `valueOf` (15.6.4), `Number` (15.7), `Math` (15.8),
|
||||
//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8),
|
||||
//! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods
|
||||
//! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1
|
||||
//! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no
|
||||
@@ -78,6 +78,14 @@
|
||||
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
|
||||
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
|
||||
//! entry counts against the heap limit.
|
||||
//!
|
||||
//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section
|
||||
//! 25.6, <https://262.ecma-international.org/11.0/#sec-promise-objects>): the constructor, `then`,
|
||||
//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise
|
||||
//! jobs a script queues run in order once its code has ended, before its run ends, on the run's
|
||||
//! limits; a promise still rejected with no handler at the end is reported by
|
||||
//! [`Realm::unhandled_rejections`]. [`Realm::add_es2015`] gives a realm made without the option
|
||||
//! `Promise` for its next runs.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -121,7 +129,9 @@ pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostIte
|
||||
pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE};
|
||||
pub use realm::{
|
||||
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
|
||||
};
|
||||
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
|
||||
|
||||
/// How a script is read.
|
||||
@@ -145,11 +155,12 @@ pub struct Options {
|
||||
/// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a
|
||||
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
|
||||
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
|
||||
/// with Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects.
|
||||
/// A realm made with it off has the ES5.1 built-ins only, as the app's scripts expect. Those
|
||||
/// built-ins are chosen when the realm is made: turning the option on or off later with
|
||||
/// [`Realm::set_es2015`] changes the language later runs read, and does not add or remove
|
||||
/// them. Runs with it on also convert `0b` and `0o` strings to numbers.
|
||||
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, and
|
||||
/// `Promise` with its job queue. A realm made with it off has the ES5.1 built-ins only, as the
|
||||
/// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option
|
||||
/// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does
|
||||
/// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it.
|
||||
/// Runs with it on also convert `0b` and `0o` strings to numbers.
|
||||
pub es2015: bool,
|
||||
}
|
||||
|
||||
@@ -266,6 +277,8 @@ mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod symbol_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
//! `Promise` and the promise job queue in realms with [`Options::es2015`].
|
||||
|
||||
use super::*;
|
||||
|
||||
fn realm() -> Realm {
|
||||
Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default())
|
||||
}
|
||||
|
||||
fn run(src: &str) -> JsValue {
|
||||
match realm().run(src) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{src}\n{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn string(src: &str) -> String {
|
||||
match run(src) {
|
||||
JsValue::String(s) => s,
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran.
|
||||
fn log(src: &str) -> String {
|
||||
let mut r = realm();
|
||||
if let Err(e) = r.run(&format!("var log = [];\n{src}")) {
|
||||
panic!("{src}\n{e:?}");
|
||||
}
|
||||
match r.run("log.join(' ')") {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extendscript_realm_has_no_promise() {
|
||||
assert_eq!(Realm::new().run("typeof Promise").unwrap(), JsValue::String("undefined".into()));
|
||||
assert_eq!(string("typeof Promise"), "function");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() {
|
||||
let mut r = Realm::new();
|
||||
r.add_es2015();
|
||||
assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into()));
|
||||
assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into()));
|
||||
assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. })));
|
||||
r.set_es2015(true);
|
||||
assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_prototype_cannot_be_replaced() {
|
||||
let src = "var before = Promise.prototype; Promise.prototype = {}; \
|
||||
var p = new Promise(function () {}); \
|
||||
[Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()";
|
||||
assert_eq!(string(src), "true,true,true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn then_callbacks_run_after_the_scripts_code_in_order() {
|
||||
let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\
|
||||
new Promise(function (res) { log.push('executor'); res(2); }).then(function (v) { log.push('b' + v); });\n\
|
||||
log.push('sync');";
|
||||
assert_eq!(log(src), "executor sync a1 b2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jobs_run_first_in_first_out_and_a_jobs_jobs_join_the_end() {
|
||||
let src = "var p = Promise.resolve();\n\
|
||||
p.then(function () { log.push(1); Promise.resolve().then(function () { log.push(4); }); });\n\
|
||||
p.then(function () { log.push(2); });\n\
|
||||
p.then(function () { log.push(3); });";
|
||||
assert_eq!(log(src), "1 2 3 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thenable_is_adopted_in_a_later_job() {
|
||||
let src = "var thenable = { then: function (res) { log.push('then'); res(7); } };\n\
|
||||
Promise.resolve(thenable).then(function (v) { log.push('got' + v); });\n\
|
||||
log.push('sync');";
|
||||
assert_eq!(log(src), "sync then got7");
|
||||
let rejecting = "var t = { then: function (res, rej) { rej('no'); res(1); } };\n\
|
||||
new Promise(function (res) { res(t); }).then(null, function (r) { log.push('rejected ' + r); });";
|
||||
assert_eq!(log(rejecting), "rejected no");
|
||||
let throwing = "var t = { then: function (res) { res(1); throw new Error('late'); } };\n\
|
||||
Promise.resolve(t).then(function (v) { log.push('kept ' + v); });";
|
||||
assert_eq!(log(throwing), "kept 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promise_resolved_with_itself_rejects_with_a_type_error() {
|
||||
let src = "var res; var p = new Promise(function (r) { res = r; }); res(p);\n\
|
||||
p.then(null, function (e) { log.push(e instanceof TypeError); });";
|
||||
assert_eq!(log(src), "true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
|
||||
let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\
|
||||
for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }";
|
||||
let mut finished = 0;
|
||||
for spare in (40_000..240_000).step_by(641) {
|
||||
let mut r = realm();
|
||||
let live = r.collect_garbage();
|
||||
r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() });
|
||||
match r.run(src) {
|
||||
Ok(_) => finished += 1,
|
||||
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue,
|
||||
Err(e) => panic!("{spare}: {e:?}"),
|
||||
}
|
||||
r.set_limits(Limits::default());
|
||||
assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}");
|
||||
}
|
||||
assert!(finished > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
|
||||
let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\
|
||||
Promise.resolve(5).finally(function () { log.push('finally'); return 9; }).then(function (v) { log.push('kept ' + v); });\n\
|
||||
Promise.all([1, Promise.resolve(2), { then: function (r) { r(3); } }]).then(function (v) { log.push('all ' + v.join(',')); });\n\
|
||||
Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\
|
||||
Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\
|
||||
Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\
|
||||
Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\
|
||||
Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\
|
||||
Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });";
|
||||
let out = log(src);
|
||||
for part in [
|
||||
"caught x",
|
||||
"finally",
|
||||
"kept 5",
|
||||
"all 1,2,3",
|
||||
"rejected:r fulfilled:4",
|
||||
"race fast",
|
||||
"chars 2",
|
||||
"not a list true",
|
||||
"no length true",
|
||||
"bad length true",
|
||||
] {
|
||||
assert!(out.contains(part), "{part} in {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() {
|
||||
// `Promise.resolve` runs once for each input and appends to the input while it is read.
|
||||
let src = "var resolve = Promise.resolve; var input;\n\
|
||||
Promise.resolve = function (x) {\n\
|
||||
if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\
|
||||
return resolve.call(this, x);\n\
|
||||
};\n\
|
||||
input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\
|
||||
input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });";
|
||||
let out = log(src);
|
||||
assert!(out.contains("array 1,2,3"), "{out}");
|
||||
assert!(out.contains("object 1"), "{out}");
|
||||
assert!(!out.contains("object 1,"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() {
|
||||
// A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap
|
||||
// has room for. The combinator would stop at its first input.
|
||||
let mut r = realm();
|
||||
r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap();
|
||||
let live = r.collect_garbage();
|
||||
r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() });
|
||||
let e = r.run("Promise.race(s)").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
|
||||
r.set_limits(Limits::default());
|
||||
assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calling_promise_without_new_or_without_an_executor_is_a_type_error() {
|
||||
let mut r = realm();
|
||||
for src in [
|
||||
"Promise(function () {})",
|
||||
"new Promise(1)",
|
||||
"Promise.prototype.then.call({}, null)",
|
||||
"Promise.resolve.call(1, 2)",
|
||||
"Promise.all.call(Math.max, [])",
|
||||
"Promise.resolve.call(() => {}, 1)",
|
||||
"Promise.reject.call({ m() {} }.m, 1)",
|
||||
"Promise.race.call((() => {}).bind(null), [])",
|
||||
] {
|
||||
match r.run(src) {
|
||||
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"),
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unhandled_rejection_is_reported_with_its_line() {
|
||||
let mut r = realm();
|
||||
r.run("var a = 1;\nPromise.reject(new Error('lost'));\nnew Promise(function () {\n throw new TypeError('also');\n});\nPromise.reject(2).catch(function () {});")
|
||||
.unwrap();
|
||||
let got: Vec<(String, u32)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.line)).collect();
|
||||
assert_eq!(got, vec![("Error: lost".to_string(), 2), ("TypeError: also".to_string(), 4)]);
|
||||
assert_eq!(r.unhandled_rejection_count(), 2);
|
||||
assert!(r.unhandled_rejections().iter().all(|j| j.authored));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\
|
||||
var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
|
||||
Promise.reject(ab);\n\
|
||||
Promise.reject(new RangeError(ab));\n\
|
||||
Promise.reject(rep('\\ud83d\\ude00', 600));\n\
|
||||
Promise.reject(rep('x', 500));",
|
||||
)
|
||||
.unwrap();
|
||||
let got: Vec<String> = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect();
|
||||
let want = vec![
|
||||
format!("{}…", "ab".repeat(250)),
|
||||
format!("RangeError: {}…", "ab".repeat(244)),
|
||||
format!("{}…", "\u{1F600}".repeat(500)),
|
||||
"x".repeat(500),
|
||||
];
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
|
||||
var e; try { null.x; } catch (x) { e = x; }\n\
|
||||
e.message = ab;\n\
|
||||
Promise.reject(e);\n\
|
||||
try { null.x; } catch (x) { Promise.reject(x); }",
|
||||
)
|
||||
.unwrap();
|
||||
let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect();
|
||||
assert_eq!(got.len(), 2);
|
||||
assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true));
|
||||
assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]);
|
||||
let interp = r.interp();
|
||||
match interp.find_property(interp.global, &crate::heap::key("ab")) {
|
||||
Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejection_handled_in_a_later_job_is_not_reported() {
|
||||
let mut r = realm();
|
||||
r.run("var p = Promise.reject(1); Promise.resolve().then(function () { p.catch(function () {}); });").unwrap();
|
||||
assert!(r.unhandled_rejections().is_empty());
|
||||
assert_eq!(r.unhandled_rejection_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_fails_reports_no_rejections_and_drops_its_jobs() {
|
||||
let mut r = realm();
|
||||
let e = r.run("var ran = false; Promise.reject(1); Promise.resolve().then(function () { ran = true; }); throw 'stop';").unwrap_err();
|
||||
assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Thrown, "stop"));
|
||||
assert!(r.unhandled_rejections().is_empty());
|
||||
assert_eq!(r.run("ran").unwrap(), JsValue::Bool(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_endless_then_chain_is_stopped_by_fuel() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 200_000, ..Limits::default() });
|
||||
let e = r.run("function again() { return Promise.resolve().then(again); } again();").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
|
||||
let e = r.run("var res; var p = new Promise(function (r) { res = r; }); function loop() { p.then(loop); } p.then(loop); res(1);").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
|
||||
assert!(!r.is_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_job_takes_fuel() {
|
||||
// `then` on a settled promise queues a job, and on a pending one it does not; the difference in
|
||||
// fuel between 50 calls and none is the jobs' fuel.
|
||||
let used = |start: &str, calls: usize| {
|
||||
let mut r = realm();
|
||||
r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() });
|
||||
r.run(&format!("var p = {start};{}", "p.then();".repeat(calls))).unwrap();
|
||||
1_000_000 - r.fuel_left()
|
||||
};
|
||||
let settled = used("Promise.resolve()", 50) - used("Promise.resolve()", 0);
|
||||
let pending = used("new Promise(function () {})", 50) - used("new Promise(function () {})", 0);
|
||||
assert_eq!(settled - pending, 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_jobs_than_the_queue_holds_end_the_run_with_a_clear_error() {
|
||||
let mut r = realm();
|
||||
r.interp().promises.max_jobs = 100;
|
||||
let e = r.run("var p = Promise.resolve(); for (var i = 0; i < 200; i++) p.then(function () {});").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Jobs));
|
||||
assert!(e.message.contains("more than 100 promise jobs"), "{}", e.message);
|
||||
assert!(r.run("var q = Promise.resolve(); for (var i = 0; i < 50; i++) q.then(function () {}); 1").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() {
|
||||
let mut r = realm();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
r.start("var t = 0; Promise.resolve().then(function () { for (var i = 0; i < 5000; i++) t += i; }); 'done'").unwrap();
|
||||
let mut paused_in_jobs = 0;
|
||||
let v = loop {
|
||||
match r.advance(500).unwrap() {
|
||||
Progress::Paused => {
|
||||
if r.interp().promises.draining {
|
||||
paused_in_jobs += 1;
|
||||
}
|
||||
}
|
||||
Progress::Done(v) => break v,
|
||||
}
|
||||
};
|
||||
assert_eq!(v, JsValue::String("done".into()));
|
||||
assert!(paused_in_jobs > 1, "{paused_in_jobs}");
|
||||
assert!(!r.is_running());
|
||||
assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() {
|
||||
let mut r = realm();
|
||||
r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap();
|
||||
let v = loop {
|
||||
match r.advance(1).unwrap() {
|
||||
Progress::Paused => {
|
||||
let interp = r.interp();
|
||||
assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run");
|
||||
}
|
||||
Progress::Done(v) => break v,
|
||||
}
|
||||
};
|
||||
assert_eq!(v, JsValue::String("done".into()));
|
||||
assert!(!r.is_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() {
|
||||
let mut r = realm();
|
||||
let flag = r.pause_flag();
|
||||
r.define_function("pauseNow", move |_| {
|
||||
flag.set(true);
|
||||
Ok(JsValue::Undefined)
|
||||
});
|
||||
r.start("Promise.resolve().then(pauseNow); 'first'").unwrap();
|
||||
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into())));
|
||||
r.start("var a = 1; var b = 2; a + b").unwrap();
|
||||
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliced_run_pauses_inside_a_finally_callback() {
|
||||
let mut r = realm();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
r.set_unbroken_fuel(5_000);
|
||||
r.start(
|
||||
"var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\
|
||||
Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\
|
||||
Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\
|
||||
'done'",
|
||||
)
|
||||
.unwrap();
|
||||
let mut paused_in_jobs = 0;
|
||||
let v = loop {
|
||||
match r.advance(500).unwrap() {
|
||||
Progress::Paused => {
|
||||
if r.interp().promises.draining {
|
||||
paused_in_jobs += 1;
|
||||
}
|
||||
}
|
||||
Progress::Done(v) => break v,
|
||||
}
|
||||
};
|
||||
assert_eq!(v, JsValue::String("done".into()));
|
||||
assert!(paused_in_jobs > 10, "{paused_in_jobs}");
|
||||
assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"var log = [], settle = {};\n\
|
||||
function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\
|
||||
function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\
|
||||
var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\
|
||||
Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\
|
||||
Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\
|
||||
Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\
|
||||
Promise.reject(4).finally(wait('d')).then(d[0], d[1]);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into()));
|
||||
r.collect_garbage();
|
||||
r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap();
|
||||
assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_sliced_run_drops_its_jobs() {
|
||||
let mut r = realm();
|
||||
r.start(
|
||||
"var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });",
|
||||
)
|
||||
.unwrap();
|
||||
let mut slices = 0;
|
||||
while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining {
|
||||
slices += 1;
|
||||
assert!(slices < 1000);
|
||||
}
|
||||
assert!(r.is_running());
|
||||
assert_eq!(r.interp().promises.queue_size().0, 1);
|
||||
r.end();
|
||||
assert!(!r.is_running());
|
||||
assert_eq!(r.interp().promises.queue_bytes(), 0);
|
||||
assert_eq!(r.interp().promises.queue_size(), (0, 0));
|
||||
assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into()));
|
||||
assert_eq!(r.run("after").unwrap(), JsValue::Bool(false));
|
||||
}
|
||||
+72
-14
@@ -57,6 +57,23 @@ pub enum LimitKind {
|
||||
Unbroken,
|
||||
/// A host function ended the run ([`crate::HostError::Abort`]).
|
||||
Host,
|
||||
/// More promise jobs were waiting to run than a run may queue.
|
||||
Jobs,
|
||||
}
|
||||
|
||||
/// A promise the last run rejected that still had no rejection handler when the run ended
|
||||
/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`,
|
||||
/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Rejection {
|
||||
/// The reason, described as an uncaught exception's message is.
|
||||
pub message: String,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
/// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]).
|
||||
pub tag: u32,
|
||||
/// `message` is text the script supplied ([`RunError::authored`]).
|
||||
pub authored: bool,
|
||||
}
|
||||
|
||||
/// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an
|
||||
@@ -172,6 +189,8 @@ pub struct Realm {
|
||||
/// before the first script, for a script the realm did not compile, and once the tags are used
|
||||
/// up.
|
||||
script_tag: u32,
|
||||
/// The unhandled rejections of the last run that ended successfully, and how many there were.
|
||||
rejections: (Vec<Rejection>, usize),
|
||||
}
|
||||
|
||||
impl Default for Realm {
|
||||
@@ -189,7 +208,7 @@ impl Realm {
|
||||
/// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it
|
||||
/// counted together.
|
||||
pub fn with_options(options: Options, limits: Limits) -> Self {
|
||||
Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE }
|
||||
Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) }
|
||||
}
|
||||
|
||||
/// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default
|
||||
@@ -218,6 +237,14 @@ impl Realm {
|
||||
self.interp.reset_gc_threshold();
|
||||
}
|
||||
|
||||
/// Gives a realm made without [`Options::es2015`] the `Promise` that option adds, for its next
|
||||
/// runs; a realm that has it already is left as it is. It does not take it away again, and it
|
||||
/// does not add the option's other built-ins (`Symbol` and the iterators). Call it between
|
||||
/// runs.
|
||||
pub fn add_es2015(&mut self) {
|
||||
crate::builtins::promise::add_to(&mut self.interp);
|
||||
}
|
||||
|
||||
/// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
|
||||
/// `const` names earlier runs declared stay visible when it is turned off. A run begun with
|
||||
/// [`Realm::start`] that is still going keeps the language it started with for the code it
|
||||
@@ -247,19 +274,21 @@ impl Realm {
|
||||
let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN });
|
||||
}
|
||||
|
||||
/// Runs `source` as a script in the global environment and returns its completion value (the
|
||||
/// value of the last expression statement that ran). A realm whose built-ins could not be
|
||||
/// installed runs nothing and gives an internal error.
|
||||
/// Runs `source` as a script in the global environment, then the promise jobs it queued, and
|
||||
/// returns its completion value (the value of the last expression statement that ran). A realm
|
||||
/// whose built-ins could not be installed runs nothing and gives an internal error.
|
||||
pub fn run(&mut self, source: &str) -> Result<JsValue, RunError> {
|
||||
let code = self.compile(source)?;
|
||||
let result = self.interp.run_global(code, false);
|
||||
let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v));
|
||||
self.outcome(result)
|
||||
}
|
||||
|
||||
/// Compiles `source` and readies the realm for a run.
|
||||
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
|
||||
self.script_tag = UNKNOWN_SOURCE;
|
||||
self.rejections = (Vec::new(), 0);
|
||||
let interp = &mut self.interp;
|
||||
interp.end_jobs(false);
|
||||
if let Some(message) = &interp.install_error {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false });
|
||||
}
|
||||
@@ -330,11 +359,15 @@ impl Realm {
|
||||
interp.constructing = false;
|
||||
interp.resuming = None;
|
||||
interp.passing = Value::Undefined;
|
||||
interp.end_jobs(result.is_ok());
|
||||
if let Some(es2015) = interp.next_es2015.take() {
|
||||
interp.set_es2015(es2015);
|
||||
}
|
||||
match result {
|
||||
Ok(v) => Ok(interp.to_js_value(&v)),
|
||||
Ok(v) => {
|
||||
self.rejections = interp.take_unhandled();
|
||||
Ok(interp.to_js_value(&v))
|
||||
}
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
let message = interp.describe(&v);
|
||||
let authored = interp.thrown_by_script(&v);
|
||||
@@ -345,6 +378,11 @@ impl Realm {
|
||||
let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host));
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false })
|
||||
}
|
||||
Err(Abrupt::Limit(LimitKind::Jobs)) => {
|
||||
let max = interp.promises.max_jobs;
|
||||
let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)");
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false })
|
||||
}
|
||||
Err(Abrupt::Limit(kind)) => {
|
||||
Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false })
|
||||
}
|
||||
@@ -364,12 +402,14 @@ impl Realm {
|
||||
/// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one
|
||||
/// instruction), and pauses where it can resume: between two instructions of the script's own
|
||||
/// code. A getter, a built-in's callback or another nested run has native frames under it, so
|
||||
/// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned
|
||||
/// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code
|
||||
/// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback
|
||||
/// written in JavaScript, and the run is done once the queue is empty. Once this has returned
|
||||
/// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its
|
||||
/// result ([`Realm::waits`]), the run does not advance: this gives an internal error.
|
||||
pub fn advance(&mut self, slice: u64) -> Result<Progress, RunError> {
|
||||
let interp = &mut self.interp;
|
||||
if interp.frames.is_empty() {
|
||||
if !interp.running() {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false });
|
||||
}
|
||||
if interp.waiting {
|
||||
@@ -385,7 +425,7 @@ impl Realm {
|
||||
let cap = slice.saturating_add(self.unbroken_fuel).min(total);
|
||||
interp.fuel = cap;
|
||||
interp.in_slice = true;
|
||||
let r = interp.execute_slice(cap - slice.min(cap));
|
||||
let r = interp.execute_run_slice(cap - slice.min(cap));
|
||||
interp.in_slice = false;
|
||||
let used = cap - interp.fuel;
|
||||
interp.fuel = total - used;
|
||||
@@ -400,7 +440,28 @@ impl Realm {
|
||||
|
||||
/// Is a run begun with [`Realm::start`] still going?
|
||||
pub fn is_running(&self) -> bool {
|
||||
!self.interp.frames.is_empty()
|
||||
self.interp.running()
|
||||
}
|
||||
|
||||
/// The promises the last run rejected that still had no rejection handler when it ended
|
||||
/// successfully, in the order they were rejected: the first 20 of them. Empty after a run that
|
||||
/// ended with an error, and until a run ends.
|
||||
pub fn unhandled_rejections(&self) -> &[Rejection] {
|
||||
&self.rejections.0
|
||||
}
|
||||
|
||||
/// How many unhandled rejections the last run that ended successfully had, the ones
|
||||
/// [`Realm::unhandled_rejections`] leaves out included.
|
||||
pub fn unhandled_rejection_count(&self) -> usize {
|
||||
self.rejections.1
|
||||
}
|
||||
|
||||
/// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error.
|
||||
pub fn source_of(&self, tag: u32) -> u32 {
|
||||
match tag {
|
||||
UNKNOWN_SOURCE => UNKNOWN_SOURCE,
|
||||
tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's
|
||||
@@ -483,10 +544,7 @@ impl Realm {
|
||||
/// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which
|
||||
/// includes code from an earlier script and from the sources given during its run.
|
||||
pub fn error_source(&self) -> u32 {
|
||||
match self.interp.error_tag {
|
||||
UNKNOWN_SOURCE => UNKNOWN_SOURCE,
|
||||
tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE),
|
||||
}
|
||||
self.source_of(self.interp.error_tag)
|
||||
}
|
||||
|
||||
/// The source tag of the code the last error's `line` and `column` are in, which stays the same
|
||||
|
||||
@@ -221,6 +221,46 @@ impl Str {
|
||||
pub(crate) fn to_rust_string(&self) -> String {
|
||||
String::from_utf16_lossy(&self.flat())
|
||||
}
|
||||
|
||||
/// The first `max_units` code units as a Rust string, read along the rope without flattening
|
||||
/// it, so a long string is not copied whole.
|
||||
pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String {
|
||||
if self.len() <= max_units {
|
||||
return self.to_rust_string();
|
||||
}
|
||||
let mut units = Vec::with_capacity(max_units);
|
||||
let mut stack = vec![self.clone()];
|
||||
while let Some(s) = stack.pop() {
|
||||
let room = max_units - units.len();
|
||||
if room == 0 {
|
||||
break;
|
||||
}
|
||||
match &*s.0.borrow() {
|
||||
Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]),
|
||||
Node::Concat { left, right, .. } => {
|
||||
stack.push(right.clone());
|
||||
stack.push(left.clone());
|
||||
}
|
||||
Node::Taken => {}
|
||||
}
|
||||
}
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// Calls `f` with each run of code units in order, read along the rope without flattening it.
|
||||
pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) {
|
||||
let mut stack = vec![self.clone()];
|
||||
while let Some(s) = stack.pop() {
|
||||
match &*s.0.borrow() {
|
||||
Node::Flat(units) => f(units),
|
||||
Node::Concat { left, right, .. } => {
|
||||
stack.push(right.clone());
|
||||
stack.push(left.clone());
|
||||
}
|
||||
Node::Taken => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Str {
|
||||
|
||||
+146
-2
@@ -40,6 +40,12 @@
|
||||
//! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without
|
||||
//! `test/annexB/` skips them; a folder there with no test to parse or run fails them.
|
||||
//!
|
||||
//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`:
|
||||
//! those whose feature tags name only `Promise`, `Promise.allSettled` and
|
||||
//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests
|
||||
//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its
|
||||
//! failures go to `promise-failures.txt`.
|
||||
//!
|
||||
//! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of
|
||||
//! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with
|
||||
//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and
|
||||
@@ -58,7 +64,6 @@ use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize};
|
||||
|
||||
/// A test file's metadata, from its `/*--- … ---*/` block.
|
||||
#[derive(Default)]
|
||||
struct Meta {
|
||||
@@ -364,7 +369,7 @@ fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> {
|
||||
|
||||
/// Globals and method names the interpreter does not provide yet: a test that names one, in its
|
||||
/// own source or in a harness file it includes, is skipped.
|
||||
const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \
|
||||
const MISSING_BUILTINS: &str = "String Number Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \
|
||||
WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array charAt charCodeAt fromCharCode substring substr split replace \
|
||||
match search exec test toUpperCase toLowerCase trim toFixed toPrecision toExponential now";
|
||||
|
||||
@@ -899,6 +904,145 @@ fn run_annex_b(dir: &Path) {
|
||||
assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display());
|
||||
}
|
||||
|
||||
/// The feature tags a `test/built-ins/Promise` test may carry and still run: `Promise`,
|
||||
/// `Promise.allSettled` and `Promise.prototype.finally`.
|
||||
const PROMISE_FEATURES: &[&str] = &["Promise", "Promise.allSettled", "Promise.prototype.finally"];
|
||||
|
||||
#[test]
|
||||
fn promise_builtins_run() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
println!("test262 Promise: SKIPPED (no suite; run cargo xtask test262)");
|
||||
return;
|
||||
};
|
||||
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_promise(&dir)).unwrap();
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global
|
||||
/// `print` that collects its output; an `async` test passes when it prints
|
||||
/// `Test262:AsyncTestComplete`.
|
||||
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> {
|
||||
let options = Options { es2015: true, ..Options::default() };
|
||||
let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
|
||||
let out = printed.clone();
|
||||
realm.define_function("print", move |args| {
|
||||
let line = match args.first() {
|
||||
Some(JsValue::String(s)) => s.clone(),
|
||||
Some(other) => format!("{other:?}"),
|
||||
None => String::new(),
|
||||
};
|
||||
out.borrow_mut().push_str(&line);
|
||||
out.borrow_mut().push('\n');
|
||||
Ok(JsValue::Undefined)
|
||||
});
|
||||
let result = realm.run(script);
|
||||
if asynchronous && result.is_ok() && negative_type.is_none() {
|
||||
let printed = printed.borrow();
|
||||
return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("printed {:?}", printed.trim()))
|
||||
};
|
||||
}
|
||||
match (result, negative_type) {
|
||||
(Ok(_), None) => Ok(()),
|
||||
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
|
||||
(Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => {
|
||||
realm.bind_last_thrown("__thrown");
|
||||
match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) {
|
||||
Ok(JsValue::Bool(true)) => Ok(()),
|
||||
_ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)),
|
||||
}
|
||||
}
|
||||
(Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the tests under `test/built-ins/Promise` whose feature tags are all in
|
||||
/// [`PROMISE_FEATURES`], whose code parses as ES5 and uses only the built-ins present, as sloppy
|
||||
/// and strict code as [`run_tests`] does, `async` tests included. Prints the counts and writes the
|
||||
/// failures to `promise-failures.txt` beside the suite.
|
||||
fn run_promise(dir: &Path) {
|
||||
let root = or_fail(inside(dir, "test/built-ins/Promise"));
|
||||
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
// A harness file is named by the test's `includes:`, so it is read only inside `harness/`.
|
||||
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
|
||||
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
|
||||
let done = harness("doneprintHandle.js");
|
||||
let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]);
|
||||
let mut groups: std::collections::BTreeMap<String, RunCounts> = std::collections::BTreeMap::new();
|
||||
let (mut files, mut other_features) = (0usize, 0usize);
|
||||
for path in or_fail(test_files(&root)) {
|
||||
files += 1;
|
||||
let source = or_fail(read_source(&path));
|
||||
let meta = meta(&source);
|
||||
if meta.features.iter().any(|f| !PROMISE_FEATURES.contains(&f.as_str())) {
|
||||
other_features += 1;
|
||||
continue;
|
||||
}
|
||||
let asynchronous = meta.flags.iter().any(|f| f == "async");
|
||||
let tags = if meta.features.is_empty() { "no feature tag".to_string() } else { meta.features.join(", ") };
|
||||
let counts = groups.entry(format!("{tags}, {}", if asynchronous { "async" } else { "sync" })).or_default();
|
||||
let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution"));
|
||||
if negative_parse || meta.flags.iter().any(|f| f == "module") {
|
||||
counts.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
|
||||
if asynchronous {
|
||||
includes.push_str(&done);
|
||||
includes.push('\n');
|
||||
}
|
||||
if parse(&source, &Options::default()).is_err() || needs_missing_builtin(&[&source, &includes], &missing) {
|
||||
counts.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
counts.tests += 1;
|
||||
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
|
||||
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
for &strict in modes(&meta) {
|
||||
let mode = if strict { "strict" } else { "sloppy" };
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) {
|
||||
Ok(Ok(())) => counts.passed += 1,
|
||||
Ok(Err(why)) => {
|
||||
counts.failed += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): {why}\n"));
|
||||
}
|
||||
Err(_) => {
|
||||
counts.failed += 1;
|
||||
counts.panicked += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut all = RunCounts::default();
|
||||
for (group, counts) in &groups {
|
||||
println!("test262 built-ins/Promise, {group}: {}.", counts.summary());
|
||||
all.tests += counts.tests;
|
||||
all.skipped += counts.skipped;
|
||||
all.passed += counts.passed;
|
||||
all.failed += counts.failed;
|
||||
all.panicked += counts.panicked;
|
||||
all.failures.push_str(&counts.failures);
|
||||
}
|
||||
let report = dir.join("promise-failures.txt");
|
||||
if let Err(e) = std::fs::write(&report, &all.failures) {
|
||||
println!("could not write {}: {e}", report.display());
|
||||
}
|
||||
println!(
|
||||
"test262 built-ins/Promise through the interpreter: {files} files, {other_features} with other feature tags left out; {}. Failures: {}",
|
||||
all.summary(),
|
||||
report.display()
|
||||
);
|
||||
assert!(all.tests > 0, "no Promise tests ran under {}", root.display());
|
||||
assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display());
|
||||
}
|
||||
|
||||
/// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and
|
||||
/// strings, which run in a realm with [`Options::es2015`].
|
||||
const SYMBOL_BUILT_INS: &[&str] = &[
|
||||
|
||||
@@ -658,19 +658,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.toolbar.dock",
|
||||
"Dock Toolbar",
|
||||
"",
|
||||
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}",
|
||||
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` as a column of the dock along the window's left or right edge (omitted: the edge it docks at, else the edge it docked at last, the left at first), as dragging its title bar to that edge does; a hidden toolbar shows; `order` is its column's place in that edge's dock, 0 at the window's edge (omitted: the innermost, or where it is when it docks at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}, `pos` its top-left corner while it floats (else null)",
|
||||
),
|
||||
(
|
||||
"window.toolbar.float",
|
||||
"Float Toolbar",
|
||||
"",
|
||||
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}",
|
||||
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in window points (both or neither, each from -1000000 to 1000000; omitted: where the dock floats a panel, and a floating toolbar stays where it is), as dragging its title bar out of the dock does; a hidden toolbar shows; returns {toolbar, floating, side, order, pos}",
|
||||
),
|
||||
(
|
||||
"window.toolbar.list",
|
||||
"List Toolbars",
|
||||
"",
|
||||
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)",
|
||||
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
|
||||
),
|
||||
("window.taskBar", "Contextual Task Bar", "", "{}"),
|
||||
(
|
||||
@@ -1525,7 +1525,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.corners",
|
||||
"Corners…",
|
||||
"",
|
||||
"{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape",
|
||||
"{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radii (relative|absolute), radius (pt, or with relative radii a percentage of each corner's own maximum); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape, as one command.batch undo step when relative radii give the corners different lengths",
|
||||
),
|
||||
(
|
||||
"ui.simplifyAuto",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`,
|
||||
//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters).
|
||||
//! `group`, `help`, `helpUrl`, `visibleWhen` and `widget` keys of each one
|
||||
//! (docs/plugins.md › Parameters).
|
||||
//!
|
||||
//! These keys are presentation only. A host from before them ignores them, so a plug-in that
|
||||
//! declares them still installs there, and a plug-in is given every parameter whether its dialog
|
||||
@@ -58,6 +59,48 @@ pub struct ParamUi {
|
||||
/// Shown only while each parameter named here has one of the values listed for it.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub visible_when: BTreeMap<String, Vec<Value>>,
|
||||
/// The control that shows a number: [`Widget::Slider`] adds a slider beside its field.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub widget: Option<Widget>,
|
||||
}
|
||||
|
||||
/// The control a `number` or `int` parameter's row shows besides its number field (`widget`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Widget {
|
||||
/// A slider over `min..max`, beside the number field.
|
||||
Slider,
|
||||
}
|
||||
|
||||
/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range.
|
||||
const EXACT_INT: i64 = 1 << 53;
|
||||
|
||||
impl ParamUi {
|
||||
/// The range a slider shows `spec`'s value over, when the parameter asks for one
|
||||
/// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on.
|
||||
pub fn slider_range(&self, spec: &ParamSpec) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
if self.widget != Some(Widget::Slider) {
|
||||
return None;
|
||||
}
|
||||
match spec {
|
||||
ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max),
|
||||
ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `widget` against parameter `spec`; `bad` builds the error.
|
||||
fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> {
|
||||
if self.widget.is_none() || self.slider_range(spec).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
match spec {
|
||||
ParamSpec::Number { .. } | ParamSpec::Int { .. } => {
|
||||
bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}"))
|
||||
}
|
||||
_ => bad("a slider is only for `number` and `int` parameters"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless
|
||||
@@ -86,6 +129,9 @@ impl ParamUi {
|
||||
return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes"));
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = m.params.get(index) {
|
||||
self.validate_slider(&p.spec, bad)?;
|
||||
}
|
||||
if self.visible_when.len() > MAX_CONDITIONS {
|
||||
return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters"));
|
||||
}
|
||||
@@ -304,4 +350,46 @@ mod tests {
|
||||
let fine = with("help", r#""Two\nlines.""#);
|
||||
assert!(Manifest::parse(fine.as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
/// A `number` or `int` parameter with a range may ask for a slider; the key reads back as
|
||||
/// written, and a parameter without it asks for none.
|
||||
#[test]
|
||||
fn slider_key_parses_and_round_trips() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","params":{
|
||||
"area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"},
|
||||
"count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"},
|
||||
"plain":{"type":"number","min":0,"max":100,"default":10}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap());
|
||||
assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0));
|
||||
assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0));
|
||||
assert_eq!(plain.ui.slider_range(&plain.spec), None);
|
||||
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slider_keys_that_cannot_apply_are_refused() {
|
||||
let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#);
|
||||
for bad in [
|
||||
// Only numbers have a slider, over a range that has room to move.
|
||||
r#"{"type":"bool","widget":"slider"}"#,
|
||||
r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#,
|
||||
r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#,
|
||||
r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#,
|
||||
r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#,
|
||||
// A control the host doesn't have.
|
||||
r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#,
|
||||
] {
|
||||
assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}");
|
||||
}
|
||||
// A command's parameters are checked the same way.
|
||||
let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#);
|
||||
assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok());
|
||||
assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err());
|
||||
let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#);
|
||||
assert!(Manifest::parse(fine.as_bytes()).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission};
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -456,6 +456,11 @@ pub struct Manifest {
|
||||
/// lists them. Left out or empty, it is given paths and compound paths alone.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
|
||||
pub inputs: Vec<String>,
|
||||
/// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at
|
||||
/// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or
|
||||
/// empty, every kind it reads stays read-only.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")]
|
||||
pub writes: Vec<String>,
|
||||
/// The parts of the document a run is given in `_context.document`, by
|
||||
/// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command
|
||||
/// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty,
|
||||
@@ -519,6 +524,7 @@ impl Manifest {
|
||||
api: 1,
|
||||
permissions: None,
|
||||
inputs: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
context: Vec::new(),
|
||||
params: Vec::new(),
|
||||
extensions: Vec::new(),
|
||||
@@ -591,6 +597,7 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
|
||||
}
|
||||
self.validate_inputs()?;
|
||||
self.validate_writes()?;
|
||||
self.validate_context()?;
|
||||
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
|
||||
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
|
||||
@@ -691,6 +698,37 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at
|
||||
/// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`.
|
||||
fn validate_writes(&self) -> Result<()> {
|
||||
if self.writes.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.kind != Kind::Filter {
|
||||
return Err(Error::Manifest("only a filter declares `writes`".into()));
|
||||
}
|
||||
for (i, name) in self.writes.iter().enumerate() {
|
||||
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
|
||||
if InputKind::parse(name).is_none() {
|
||||
return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance")));
|
||||
}
|
||||
if self.writes.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(format!("`writes` lists `{shown}` twice")));
|
||||
}
|
||||
if !self.inputs.contains(name) {
|
||||
return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list")));
|
||||
}
|
||||
}
|
||||
if self.api < WRITES_API {
|
||||
return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later")));
|
||||
}
|
||||
let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name()));
|
||||
if !listed(Permission::DocWrite) {
|
||||
return Err(Error::Manifest("`writes` needs the permission `doc.write`".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect
|
||||
/// with commands, at `api` 3 or later lists any, with a `permissions` list that holds
|
||||
/// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]).
|
||||
@@ -764,6 +802,11 @@ impl Manifest {
|
||||
self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// The kinds among those it reads that it may change (`writes`).
|
||||
pub fn write_kinds(&self) -> Vec<InputKind> {
|
||||
self.writes.iter().filter_map(|n| InputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16
|
||||
/// lower-case letters and digits; other kinds list none.
|
||||
fn validate_extensions(&self) -> Result<()> {
|
||||
@@ -933,6 +976,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `writes` as [`input_names`] reads `inputs`.
|
||||
fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance");
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `context`: a list of names (`null`: none). Anything else is the error
|
||||
/// [`Manifest::validate_context`] gives a wrong entry.
|
||||
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
@@ -1419,6 +1472,64 @@ mod tests {
|
||||
assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice"));
|
||||
}
|
||||
|
||||
/// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with
|
||||
/// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key
|
||||
/// isn't written back. Anything else is refused naming `writes`.
|
||||
#[test]
|
||||
fn a_filter_at_api_3_lists_the_kinds_it_writes() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.write_kinds(), InputKind::ALL);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"]));
|
||||
let some = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image]));
|
||||
for none in [
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","writes":null}"#,
|
||||
] {
|
||||
let m = Manifest::parse(none.as_bytes()).unwrap();
|
||||
assert!(m.write_kinds().is_empty(), "{none}");
|
||||
assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}");
|
||||
}
|
||||
let rw = r#""permissions":["doc.read","doc.write"]"#;
|
||||
for (bad, says) in [
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#),
|
||||
"`writes` names an unknown object kind `text`",
|
||||
),
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#),
|
||||
"`writes` lists `type` twice",
|
||||
),
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#),
|
||||
"`writes` lists `image`, which `inputs` doesn't list",
|
||||
),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(),
|
||||
"`writes` needs the permission `doc.write`",
|
||||
),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(),
|
||||
"`inputs` needs the permission `doc.read`",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document
|
||||
/// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks
|
||||
/// for approval. Left out or empty, it asks for none and isn't written back. Anything else is
|
||||
|
||||
@@ -82,6 +82,10 @@ pub struct OutObject {
|
||||
/// A read-only input object (type, an image or a symbol instance) returned as it was given:
|
||||
/// it stays as it is, and new objects listed after it go above it.
|
||||
pub kept: bool,
|
||||
/// A type object, an image or a symbol instance of a kind the filter may change (`writes`)
|
||||
/// returned with changes: the fields it changes, by their names in the input, checked when
|
||||
/// they are applied ([`apply_output`]).
|
||||
pub edit: Option<serde_json::Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's
|
||||
@@ -295,7 +299,7 @@ fn affine_json(xf: Affine) -> Value {
|
||||
/// paragraphs: [style]}` with the native character and paragraph attributes, one paragraph style
|
||||
/// for each paragraph, and `truncated`: true, with no runs or paragraphs, past [`MAX_INPUT_TEXT`]
|
||||
/// or [`MAX_INPUT_RUNS`];
|
||||
/// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
|
||||
/// - an image (`"image"`): `opacity` (0 to 1), `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
|
||||
/// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`]
|
||||
/// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks
|
||||
/// through the working CMYK profile, as sRGB). A linked image's file and path are never read or
|
||||
@@ -332,6 +336,7 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left
|
||||
if let Some(q) = n.image_quad() {
|
||||
o["corners"] = json!(q.map(|p| [p.x, p.y]));
|
||||
}
|
||||
o["opacity"] = json!(n.opacity);
|
||||
o["pixelSize"] = json!([im.width, im.height]);
|
||||
o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode));
|
||||
o["linked"] = json!(im.link.is_some());
|
||||
@@ -672,6 +677,15 @@ fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// An object's name from plug-in output (`null`: no name), without control characters and at most
|
||||
/// 256 of them.
|
||||
fn decode_name(n: &Value, at: &str) -> Result<String> {
|
||||
Ok(match n {
|
||||
Value::Null => String::new(),
|
||||
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn opt<'a>(o: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a Value> {
|
||||
o.get(key).filter(|v| !v.is_null())
|
||||
}
|
||||
@@ -693,11 +707,7 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result<OutObject>
|
||||
});
|
||||
}
|
||||
if let Some(n) = o.get("name") {
|
||||
let name = match n {
|
||||
Value::Null => String::new(),
|
||||
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
};
|
||||
out.name = Some(name);
|
||||
out.name = Some(decode_name(n, at)?);
|
||||
}
|
||||
if let Some(p) = opt(o, "path") {
|
||||
out.path = Some(decode_path(p, &format!("{at}.path"), anchors)?);
|
||||
@@ -813,8 +823,18 @@ pub fn decode_output(bytes: &[u8]) -> Result<Output> {
|
||||
/// differs, before anything changes. Each object is parsed from `input` only to compare it, one at
|
||||
/// a time, and an object that can't be read from there is an error.
|
||||
pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result<Output> {
|
||||
decode_output_writing(bytes, input, read_only, &[])
|
||||
}
|
||||
|
||||
/// [`decode_output_with`] for a filter that may change the objects of kinds `writes` among them
|
||||
/// (its manifest's `writes`): such an object is still listed exactly once, and an entry for it may
|
||||
/// leave fields out, which keep their values, and give its name, its transform, and type's
|
||||
/// `text.runs` and `text.paragraphs`, an image's `opacity` or an instance's `symbolId` changed.
|
||||
/// Such an entry is [`OutObject::edit`] with the fields it changes; one that changes nothing is
|
||||
/// [`OutObject::kept`]. Any other field must be as given, and the error names the first that isn't.
|
||||
pub fn decode_output_writing(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Output> {
|
||||
let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
let objects = decode_objects(&v, input, read_only)?;
|
||||
let objects = decode_objects(&v, input, read_only, writes)?;
|
||||
let document_data = match v.get_mut("documentData").map(Value::take) {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
@@ -896,12 +916,12 @@ fn draws_nothing(c: char) -> bool {
|
||||
/// declined (the message reaches the user). A live effect's other keys don't matter.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Vec<OutObject>> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
decode_objects(&v, &[], &HashMap::new())
|
||||
decode_objects(&v, &[], &HashMap::new(), &[])
|
||||
}
|
||||
|
||||
/// The objects of output `v`, or its decline; entries for `read_only` objects as
|
||||
/// [`decode_output_with`] reads them.
|
||||
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<Vec<OutObject>> {
|
||||
/// [`decode_output_writing`] reads them, those of kinds `writes` changeable.
|
||||
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Vec<OutObject>> {
|
||||
if let Some(e) = declined(v) {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -910,6 +930,8 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
|
||||
return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
|
||||
}
|
||||
let mut anchors = 0;
|
||||
// Bytes of type text the output writes, over all its objects.
|
||||
let mut text = 0;
|
||||
let mut returned: HashSet<NodeId> = HashSet::new();
|
||||
let out = objects
|
||||
.iter()
|
||||
@@ -920,12 +942,19 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
|
||||
if !returned.insert(id) {
|
||||
return Err(out_err(&at, "is listed twice"));
|
||||
}
|
||||
let kept = OutObject { id: Some(id), kept: true, ..OutObject::default() };
|
||||
// `{"id": …}` alone keeps the object, so there is nothing to compare it with.
|
||||
if o.as_object().is_none_or(|m| m.len() != 1) {
|
||||
let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
|
||||
let Some(entry) = o.as_object().filter(|m| m.len() != 1) else { return Ok(kept) };
|
||||
let given: Value = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
|
||||
let kind = given.get("type").and_then(Value::as_str).and_then(InputKind::parse).filter(|k| writes.contains(k));
|
||||
let Some(kind) = kind else {
|
||||
check_unchanged(o, &given, &at)?;
|
||||
}
|
||||
Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() })
|
||||
return Ok(kept);
|
||||
};
|
||||
Ok(match writes::changes(entry, &given, kind, &at, &mut text)? {
|
||||
Some(edit) => OutObject { id: Some(id), edit: Some(edit), ..OutObject::default() },
|
||||
None => kept,
|
||||
})
|
||||
}
|
||||
None => decode_object(o, &format!("objects[{i}]"), &mut anchors),
|
||||
})
|
||||
@@ -951,28 +980,40 @@ fn output_id(o: &Value) -> Option<NodeId> {
|
||||
/// numbers compared by value. Otherwise the error names the first field that differs
|
||||
/// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as
|
||||
/// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the
|
||||
/// plug-in's.
|
||||
/// plug-in's. An image's `opacity`, which filters are given from plug-in API level 3, may be left
|
||||
/// out, so an entry that a filter built for level 2 writes as it was given there still matches.
|
||||
fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> {
|
||||
let changed = match (o, given) {
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
let mut keys: Vec<&String> = x.keys().collect();
|
||||
keys.sort();
|
||||
keys.into_iter().find_map(|k| match y.get(k) {
|
||||
Some(q) => first_difference(&x[k], q, k),
|
||||
None => Some(k.clone()),
|
||||
})
|
||||
keys.into_iter()
|
||||
.find_map(|k| match y.get(k) {
|
||||
Some(q) => first_difference(&x[k], q, k),
|
||||
None => Some(k.clone()),
|
||||
})
|
||||
.or_else(|| {
|
||||
let image = y.get("type").and_then(Value::as_str) == Some(InputKind::Image.name());
|
||||
let mut missing: Vec<&String> = y.keys().filter(|k| !x.contains_key(*k) && !(image && *k == "opacity")).collect();
|
||||
missing.sort();
|
||||
missing.first().map(|k| (*k).clone())
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
_ => first_difference(o, given, ""),
|
||||
};
|
||||
match changed.or_else(|| first_difference(o, given, "")) {
|
||||
match changed {
|
||||
None => Ok(()),
|
||||
Some(field) => {
|
||||
let field = crate::permissions::display_text(&field, crate::permissions::MAX_SHOWN_FIELD);
|
||||
Err(out_err(at, format!("read-only field '{field}' changed")))
|
||||
}
|
||||
Some(field) => Err(read_only_changed(at, &field)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an entry at `at` that changes read-only `field`, which is shown as
|
||||
/// [`crate::permissions::display_text`] shows a manifest string.
|
||||
fn read_only_changed(at: &str, field: &str) -> Error {
|
||||
let field = crate::permissions::display_text(field, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(at, format!("read-only field '{field}' changed"))
|
||||
}
|
||||
|
||||
/// The path of the first place `a` and `b` differ (`""`: they differ as a whole), `None` when they
|
||||
/// are the same JSON with numbers compared by value.
|
||||
fn first_difference(a: &Value, b: &Value, at: &str) -> Option<String> {
|
||||
@@ -1328,7 +1369,9 @@ impl Plan {
|
||||
/// input object, just below the first one listed after them (at the first input object's place
|
||||
/// when the output keeps none; on top of `parent` when there were no inputs). Input objects missing
|
||||
/// from the output are deleted. An object's effect records replace its own once `admit` lets them
|
||||
/// in. Returns the resulting objects in output order (to select).
|
||||
/// in. Type, images and symbol instances stay as they are, or take the changes of their
|
||||
/// [`OutObject::edit`] once each value is checked. Returns the resulting objects in output order
|
||||
/// (to select).
|
||||
pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>, parent: Option<NodeId>, admit: AdmitEffects) -> Result<Vec<NodeId>> {
|
||||
let wanted: HashSet<NodeId> = inputs.iter().copied().collect();
|
||||
let mut originals: HashMap<NodeId, Node> = HashMap::new();
|
||||
@@ -1353,12 +1396,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>,
|
||||
out_err(&at, format!("{} is not the id of an input object", id.0))
|
||||
}
|
||||
})?;
|
||||
// Type, images and symbol instances are only read: writing one would make it a path.
|
||||
if input_kind(&n).is_some() && !o.kept {
|
||||
return Err(out_err(&at, format!("{} is read-only", id.0)));
|
||||
}
|
||||
// Type, images and symbol instances change only through the fields a filter that
|
||||
// may write them returns: writing one as a path would make it a path.
|
||||
let kept = o.kept;
|
||||
if !kept {
|
||||
if input_kind(&n).is_some() && !kept {
|
||||
let Some(edit) = &o.edit else { return Err(out_err(&at, format!("{} is read-only", id.0))) };
|
||||
writes::apply(doc, &mut n, edit, &format!("{at} (id {})", id.0))?;
|
||||
} else if o.edit.is_some() {
|
||||
return Err(out_err(&at, format!("{} is not type, an image or a symbol instance", id.0)));
|
||||
} else if !kept {
|
||||
write(doc, &mut n, o, &at, admit)?;
|
||||
}
|
||||
if !run.is_empty() {
|
||||
@@ -1415,5 +1461,7 @@ pub fn output_geometry(objects: Vec<OutObject>) -> PathData {
|
||||
PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect())
|
||||
}
|
||||
|
||||
mod writes;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1066,7 +1066,8 @@ fn a_changed_field_is_named_escaped_and_short() {
|
||||
}
|
||||
|
||||
/// A filter given read-only objects returns each one as `{"id": …}` or exactly as given (numbers by
|
||||
/// value), and they stay as they are, new objects listed after one going just above it. Any change,
|
||||
/// value; an image may leave out its `opacity`), and they stay as they are, new objects listed
|
||||
/// after one going just above it. Any change,
|
||||
/// an object left out or listed twice, and a new object of such a kind are refused before anything
|
||||
/// changes.
|
||||
#[test]
|
||||
@@ -1087,6 +1088,14 @@ fn read_only_kind_field_and_omission_refuse() {
|
||||
let mut echo = input.clone();
|
||||
echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]);
|
||||
assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok());
|
||||
// An image without `opacity`, as plug-in API level 2 gave it, is the image as given.
|
||||
let mut echo = input.clone();
|
||||
for i in [4, 5] {
|
||||
assert_eq!(echo["objects"][i]["type"], json!("image"));
|
||||
echo["objects"][i].as_object_mut().unwrap().remove("opacity");
|
||||
}
|
||||
let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap();
|
||||
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5);
|
||||
// So is an id written as a float; a fractional one names no object.
|
||||
let id = input["objects"][3]["id"].as_u64().unwrap();
|
||||
let mut echo = input.clone();
|
||||
@@ -1151,6 +1160,486 @@ fn read_only_kind_field_and_omission_refuse() {
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
/// [`mixed`] with a second symbol, "Moon", and its targets and input for a filter that reads and may
|
||||
/// change every kind.
|
||||
fn writable() -> (Document, Vec<NodeId>, Vec<u8>, ReadOnlySpans, [NodeId; 5]) {
|
||||
let (mut d, _, layer, extra) = mixed();
|
||||
let art = Arc::new(Node::path(d.alloc_id(), square(5.0), Appearance::default()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Moon".into(), art, dynamic: false });
|
||||
let targets = filter_targets_with(&d, &[layer], &InputKind::ALL);
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &InputKind::ALL, usize::MAX).unwrap();
|
||||
(d, targets, bytes, read_only, extra)
|
||||
}
|
||||
|
||||
/// Decodes `out` for [`writable`]'s input with `writes` and applies it to `d`.
|
||||
fn write_out(
|
||||
d: &mut Document,
|
||||
targets: &[NodeId],
|
||||
bytes: &[u8],
|
||||
read_only: &ReadOnlySpans,
|
||||
writes: &[InputKind],
|
||||
out: &Value,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let out = decode_output_writing(out.to_string().as_bytes(), bytes, read_only, writes)?;
|
||||
apply_output(d, targets, out.objects, None, &keep)
|
||||
}
|
||||
|
||||
/// A filter that may write type, images and symbol instances changes type's runs and character
|
||||
/// attributes, an image's transform and opacity, and the symbol and transform of an instance,
|
||||
/// with entries that give only the fields they change. What it writes reads back the same. An
|
||||
/// exact echo, `{"id": …}` alone and fields given as they were (numbers by value) change nothing.
|
||||
#[test]
|
||||
fn writable_kinds_take_type_runs_image_placement_and_instance_symbols() {
|
||||
use vectorcraft_doc::{CharStyle, ParaStyle};
|
||||
let (mut d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
|
||||
let before = d.clone();
|
||||
let all = &InputKind::ALL;
|
||||
let echo = decode_output_writing(&bytes, &bytes, &read_only, all).unwrap();
|
||||
assert!(echo.objects.iter().all(|o| o.edit.is_none()));
|
||||
apply_output(&mut d, &targets, echo.objects, None, &keep).unwrap();
|
||||
assert_eq!(d, before, "an exact echo changes nothing");
|
||||
let ro = |id: NodeId| json!({"id": id.0});
|
||||
let paths: Vec<Value> = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect();
|
||||
let with = |entries: Vec<Value>| {
|
||||
let objects = [paths.clone(), entries].concat();
|
||||
json!({ "objects": objects })
|
||||
};
|
||||
let same = with(vec![
|
||||
json!({"id": text.0, "transform": [1, 0, 0, 1, 5, 50], "name": "T"}),
|
||||
json!({"id": embedded.0, "opacity": 1}),
|
||||
ro(linked),
|
||||
json!({"id": star.0, "symbolId": "Star"}),
|
||||
ro(ghost),
|
||||
]);
|
||||
let out = decode_output_writing(same.to_string().as_bytes(), &bytes, &read_only, all).unwrap();
|
||||
assert!(out.objects.iter().all(|o| o.edit.is_none()));
|
||||
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5, "fields given as they were change nothing");
|
||||
// The changes, each entry giving only what it changes.
|
||||
let big = CharStyle { size: 24.0, ..CharStyle::default() };
|
||||
let runs = json!([{"text": "Bye\n", "style": CharStyle::default()}, {"text": "now", "style": big}]);
|
||||
let out = with(vec![
|
||||
json!({"id": text.0, "name": "Renamed", "text": {"runs": runs}}),
|
||||
json!({"id": embedded.0, "transform": [1, 0, 0, 1, 10, 20], "opacity": 0.5}),
|
||||
ro(linked),
|
||||
json!({"id": star.0, "symbolId": "Moon", "transform": [1, 0, 0, 1, 50, 0]}),
|
||||
ro(ghost),
|
||||
]);
|
||||
let made = write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
|
||||
assert_eq!(made.len(), targets.len());
|
||||
let node = |id: NodeId| d.node(id).unwrap().clone();
|
||||
let NodeKind::Text(t) = &node(text).kind else { panic!("type") };
|
||||
assert_eq!((t.plain_text().as_str(), t.runs[1].style.size), ("Bye\nnow", 24.0));
|
||||
assert_eq!(t.para_at(1).space_before, 6.0, "paragraphs keep their styles");
|
||||
assert_eq!(t.para_at(0), &ParaStyle::default());
|
||||
assert_eq!(node(text).name.as_deref(), Some("Renamed"));
|
||||
let NodeKind::Image(im) = &node(embedded).kind else { panic!("image") };
|
||||
assert_eq!((im.xf, node(embedded).opacity), (Affine::new([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), 0.5));
|
||||
assert_eq!(node(star).kind, NodeKind::SymbolInstance { symbol: "Moon".into(), xf: Affine::translate((50.0, 0.0)) });
|
||||
for id in [linked, ghost] {
|
||||
assert_eq!(d.node(id), before.node(id), "objects returned by id stay as they were");
|
||||
}
|
||||
// Read again, the changed objects give what was written.
|
||||
let read = |id: NodeId| encode_read_only(&d, d.node(id).unwrap()).unwrap();
|
||||
assert_eq!(read(text)["text"]["runs"], runs);
|
||||
assert_eq!((&read(embedded)["transform"], &read(embedded)["opacity"]), (&json!([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), &json!(0.5)));
|
||||
assert_eq!((&read(star)["symbolId"], &read(star)["transform"]), (&json!("Moon"), &json!([1.0, 0.0, 0.0, 1.0, 50.0, 0.0])));
|
||||
assert!(read(star).get("missing").is_none());
|
||||
// An instance of a symbol the document lacks can point to one it has.
|
||||
let mut d = before.clone();
|
||||
let out = with(vec![ro(text), ro(embedded), ro(linked), ro(star), json!({"id": ghost.0, "symbolId": "Star"})]);
|
||||
write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
|
||||
assert!(matches!(&d.node(ghost).unwrap().kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Star"));
|
||||
}
|
||||
|
||||
/// An entry that changes a field its kind can't change, a kind the manifest doesn't list in
|
||||
/// `writes`, or gives a value out of range is refused naming the object and the field, before
|
||||
/// anything changes.
|
||||
#[test]
|
||||
fn bad_writes_are_refused_naming_the_object_and_the_field() {
|
||||
use vectorcraft_doc::CharStyle;
|
||||
let (d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
|
||||
let style = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
let styled = |f: &dyn Fn(&mut Value)| {
|
||||
let mut s = style.clone();
|
||||
f(&mut s);
|
||||
json!([{"text": "Hi\nthere", "style": s}])
|
||||
};
|
||||
let (t, e, l, s) = (text.0, embedded.0, linked.0, star.0);
|
||||
let (ti, ei, si) = (at(text), at(embedded), at(star));
|
||||
let cases: Vec<(NodeId, Value, &[InputKind], String)> = vec![
|
||||
(text, json!({"text": {"kind": "area"}}), &InputKind::ALL, format!("objects[{ti}] (id {t}): read-only field 'text.kind' changed")),
|
||||
(text, json!({"text": {"x": 1}}), &InputKind::ALL, format!("(id {t}): read-only field 'text.x' changed")),
|
||||
(text, json!({"bounds": [0, 0, 1, 1]}), &InputKind::ALL, format!("(id {t}): read-only field 'bounds[0]' changed")),
|
||||
(text, json!({"opacity": 0.5}), &InputKind::ALL, format!("(id {t}): read-only field 'opacity' changed")),
|
||||
(text, json!({"text": {"runs": []}}), &InputKind::ALL, "text.runs: type needs at least one run".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style: unknown key 'fontSzie'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.size: `size` must be from 0.1 to 1296".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(" "))}}),
|
||||
&InputKind::ALL,
|
||||
"font_family: must be 1-256 printable characters".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(format!(" {}", "a".repeat(256))))}}),
|
||||
&InputKind::ALL,
|
||||
"font_family: must be 1-256 printable characters".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["fill"] = json!({"type": "solid", "color": s["fill"]["color"], "tintt": 0.5}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.fill: unknown key 'tintt'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["stroke"] = json!({"type": "none", "pattern": "Dots"}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.stroke: unknown key 'pattern'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": [{"text": "A\nB\nC", "style": style}], "paragraphs": input["objects"][at(text)]["text"]["paragraphs"]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs: expected 3 paragraph styles, one per paragraph".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()),
|
||||
(text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")),
|
||||
(text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()),
|
||||
(text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()),
|
||||
(text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()),
|
||||
(text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{"hyphenation": {"wordLongerThen": 3}}, {}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[0].hyphenation: unknown key 'wordLongerThen'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{"justification": {"wordSpacng": [80, 100, 133]}}, {}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[0].justification: unknown key 'wordSpacng'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{}, {"tabs": [{"position": 36}, {"position": 72, "aling": "center"}]}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[1].tabs[1]: unknown key 'aling'".into(),
|
||||
),
|
||||
(text, json!({"text": {"paragraphs": [{"list": {"levl": 2}}, {}]}}), &InputKind::ALL, "text.paragraphs[0].list: unknown key 'levl'".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["stroke_dash"] = json!({"pattern": [2, 2], "ofset": 1}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.stroke_dash: unknown key 'ofset'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}),
|
||||
&InputKind::ALL,
|
||||
"holds the character of an inline graphic".into(),
|
||||
),
|
||||
(text, json!({"text": {"paragraphs": [{}]}}), &InputKind::ALL, "text.paragraphs: expected 2 paragraph styles, one per paragraph".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 0, 0, 0]}), &InputKind::ALL, format!("objects[{ti}] (id {t}).transform: flattens the object")),
|
||||
(text, json!({"transform": [1, 0, 0, 1, 1e9, 0]}), &InputKind::ALL, "transform: a number is out of range".into()),
|
||||
(text, json!({"transform": [1, 0, null, 0, 1, 10, 20]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 1, 10]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 1]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(embedded, json!({"pixelSize": [3, 1]}), &InputKind::ALL, format!("(id {e}): read-only field 'pixelSize[0]' changed")),
|
||||
(embedded, json!({"opacity": 2}), &InputKind::ALL, format!("objects[{ei}] (id {e}).opacity: must be a number from 0 to 1")),
|
||||
(embedded, json!({"opacity": "half"}), &InputKind::ALL, "opacity: must be a number from 0 to 1".into()),
|
||||
(linked, json!({"linked": false}), &InputKind::ALL, format!("(id {l}): read-only field 'linked' changed")),
|
||||
(embedded, json!({"opacity": 0.5}), &[InputKind::Type, InputKind::SymbolInstance], format!("(id {e}): read-only field 'opacity' changed")),
|
||||
(
|
||||
star,
|
||||
json!({"symbolId": "Nowhere"}),
|
||||
&InputKind::ALL,
|
||||
format!("objects[{si}] (id {s}).symbolId: 'Nowhere' is not a symbol in this document"),
|
||||
),
|
||||
(star, json!({"symbolId": 7}), &InputKind::ALL, "symbolId: must be the name of a symbol".into()),
|
||||
(star, json!({"overrides": {"a": 1}}), &InputKind::ALL, format!("(id {s}): read-only field 'overrides.a' changed")),
|
||||
(ghost, json!({"missing": false}), &InputKind::ALL, "read-only field 'missing' changed".into()),
|
||||
(star, json!({"symbolId": "Moon"}), &[InputKind::Type], format!("(id {s}): read-only field 'symbolId' changed")),
|
||||
];
|
||||
for (id, entry, writes, says) in cases {
|
||||
let mut out = input.clone();
|
||||
let mut e = entry.clone();
|
||||
e["id"] = json!(id.0);
|
||||
out["objects"][at(id)] = e;
|
||||
let mut doc = d.clone();
|
||||
let err = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
|
||||
assert!(err.contains(&says), "{entry}: {says}: {err}");
|
||||
assert_eq!(doc, d, "{entry}: nothing changed");
|
||||
}
|
||||
// Leaving a writable object out is still refused: it isn't deleted.
|
||||
let mut out = input.clone();
|
||||
out["objects"].as_array_mut().unwrap().remove(at(star));
|
||||
let e = write_out(&mut d.clone(), &targets, &bytes, &read_only, &InputKind::ALL, &out).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("objects (id {s}): a read-only object was left out")), "{e}");
|
||||
}
|
||||
|
||||
/// The text a filter writes to one type object is held to [`MAX_INPUT_TEXT`] bytes and
|
||||
/// [`MAX_INPUT_RUNS`] runs and paragraphs, as the text it is given; type given as `truncated`
|
||||
/// keeps its text, though it can still move.
|
||||
#[test]
|
||||
fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
let (mut d, _, layer, [text, ..]) = mixed();
|
||||
let long = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), &"x".repeat(MAX_INPUT_TEXT + 1), CharStyle::default()))),
|
||||
);
|
||||
let long = d.insert(Some(layer), usize::MAX, long).unwrap();
|
||||
let targets = filter_targets_with(&d, &[layer], &[InputKind::Type]);
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
|
||||
assert_eq!(input["objects"][at(long)]["truncated"], json!(true));
|
||||
let style = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
let run = |s: String| json!({"text": s, "style": style});
|
||||
let writes = &[InputKind::Type];
|
||||
for (id, text_v, says) in [
|
||||
(text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")),
|
||||
(text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
|
||||
(text, json!({"runs": [run("\n".repeat(MAX_INPUT_RUNS))]}), format!("{} paragraphs (limit {MAX_INPUT_RUNS})", MAX_INPUT_RUNS + 1)),
|
||||
(text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
|
||||
(long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()),
|
||||
] {
|
||||
let mut out = input.clone();
|
||||
out["objects"][at(id)] = json!({"id": id.0, "text": text_v});
|
||||
let mut doc = d.clone();
|
||||
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
|
||||
assert!(e.contains(&says), "{says}: {e}");
|
||||
assert_eq!(doc, d);
|
||||
}
|
||||
// At the limit the text is written; truncated type still moves.
|
||||
let mut out = input.clone();
|
||||
out["objects"][at(text)] = json!({"id": text.0, "text": {"runs": [run("x".repeat(MAX_INPUT_TEXT))]}});
|
||||
out["objects"][at(long)] = json!({"id": long.0, "transform": [1, 0, 0, 1, 3, 4]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, writes, &out).unwrap();
|
||||
assert!(matches!(&d.node(text).unwrap().kind, NodeKind::Text(t) if t.plain_text().len() == MAX_INPUT_TEXT));
|
||||
assert!(
|
||||
matches!(&d.node(long).unwrap().kind, NodeKind::Text(t) if t.xf == Affine::translate((3.0, 4.0)) && t.plain_text().len() == MAX_INPUT_TEXT + 1)
|
||||
);
|
||||
}
|
||||
|
||||
/// An inline graphic in type stays as it was, in its place among the inline graphics: the runs
|
||||
/// around it can change, and adding, removing or changing one is refused.
|
||||
#[test]
|
||||
fn inline_graphics_in_written_type_stay_as_they_were() {
|
||||
use vectorcraft_doc::{CharStyle, InlineArt, TextObject, TextRun};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A", CharStyle::default());
|
||||
t.runs = vec![
|
||||
TextRun::new("A", CharStyle::default()),
|
||||
TextRun::inline(InlineArt::new("Star"), CharStyle::default()),
|
||||
TextRun::new("B", CharStyle::default()),
|
||||
];
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let runs = input["objects"][0]["text"]["runs"].clone();
|
||||
let writes = &[InputKind::Type];
|
||||
let with = |runs: Value| json!({"objects": [{"id": id.0, "text": {"runs": runs}}]});
|
||||
let mut changed = runs.clone();
|
||||
changed[0]["text"] = json!("Before ");
|
||||
changed[2]["text"] = json!(" after");
|
||||
let mut doc = d.clone();
|
||||
write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(changed)).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.plain_text(), "Before \u{FFFC} after");
|
||||
assert_eq!(t.runs[1].inline.as_ref().map(|a| a.symbol.as_str()), Some("Star"));
|
||||
let mut moved = runs.clone();
|
||||
moved[1]["inline"]["symbol"] = json!("Moon");
|
||||
let without = json!([runs[0], runs[2]]);
|
||||
let doubled = json!([runs[0], runs[1], runs[1], runs[2]]);
|
||||
for bad in [moved, without, doubled] {
|
||||
let mut doc = d.clone();
|
||||
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(bad.clone())).unwrap_err().to_string();
|
||||
assert!(e.contains("inline graphics can't be added, removed, reordered or changed"), "{bad}: {e}");
|
||||
assert_eq!(doc, d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs
|
||||
/// stays the same, and otherwise the styles follow the paragraphs' text: a paragraph whose text
|
||||
/// stays keeps its style, also when changes are made at two places, a paragraph added at the start
|
||||
/// takes the style of the next one and one added later the style of the one before it, and joining
|
||||
/// two paragraphs keeps the first one's style.
|
||||
#[test]
|
||||
fn written_runs_without_paragraphs_keep_each_paragraph_s_style() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB\nC", CharStyle::default());
|
||||
let styled = |justify| ParaStyle { justify, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![styled(Justify::Left), styled(Justify::Center), styled(Justify::Right)]);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let justified = |text: &str| {
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
|
||||
let mut doc = d.clone();
|
||||
write_out(&mut doc, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.plain_text(), text);
|
||||
(0..t.paragraph_count()).map(|i| t.para_at(i).justify).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(justified("X\nA\nB\nC"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("A\nBé\nC"), [Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]);
|
||||
assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
// Two separate changes: B and C keep their styles.
|
||||
assert_eq!(justified("X\nA\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
assert_eq!(justified("A\nX\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
// A changed paragraph takes the style of the one it replaces; the one added after it, that style.
|
||||
assert_eq!(justified("A\nB2\nB3\nC"), [Justify::Left, Justify::Center, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("A2\nC"), [Justify::Left, Justify::Right]);
|
||||
}
|
||||
|
||||
/// A paragraph that a change adds next to a numbered one takes its style without the number, and
|
||||
/// the numbered paragraph keeps it.
|
||||
#[test]
|
||||
fn written_runs_give_an_added_paragraph_no_list_number() {
|
||||
use vectorcraft_doc::text::ParaList;
|
||||
use vectorcraft_doc::{CharStyle, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
let numbered = ParaStyle { list: Some(ParaList { start: Some(5), ..ParaList::default() }), ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![ParaStyle::default(), numbered]);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": "X\nA\nB\nY", "style": CharStyle::default()}]}}]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
|
||||
let starts: Vec<_> = (0..t.paragraph_count()).map(|i| t.para_at(i).list.map(|l| l.start)).collect();
|
||||
assert_eq!(starts, [None, None, Some(Some(5)), Some(None)]);
|
||||
}
|
||||
|
||||
/// Past 262,144 pairs of old and new paragraphs to compare, the paragraphs are paired in order.
|
||||
#[test]
|
||||
fn written_runs_pair_paragraphs_in_order_past_the_compare_limit() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let paras: Vec<String> = (0..600).map(|i| format!("p{i}")).collect();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), ¶s.join("\n"), CharStyle::default());
|
||||
let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles((0..600).map(styled).collect());
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
// 600 old paragraphs times 602 new ones: none starts or ends both texts.
|
||||
let text = format!("X\n{}\nY", paras.join("\n"));
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.paragraph_count(), 602);
|
||||
let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect();
|
||||
let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
/// Every number in the character and paragraph styles a filter writes is checked against the range
|
||||
/// the style commands keep it to, in a style of the filter's own and in one the type already has,
|
||||
/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the
|
||||
/// object and the field, and the document stays as it was. A set of the document's, given by
|
||||
/// name, takes the document's characters.
|
||||
#[test]
|
||||
fn written_style_numbers_are_checked_even_in_a_style_the_type_has() {
|
||||
use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() });
|
||||
let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() };
|
||||
let bad_chars: [(&str, CharStyle, &str); 5] = [
|
||||
("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"),
|
||||
("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"),
|
||||
("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"),
|
||||
("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"),
|
||||
("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"),
|
||||
];
|
||||
let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() };
|
||||
let bad_paras: [(&str, ParaStyle, &str); 4] = [
|
||||
("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"),
|
||||
("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"),
|
||||
(
|
||||
"hyphenation",
|
||||
ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() },
|
||||
"paragraphs[0].hyphenation.after_first",
|
||||
),
|
||||
("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"),
|
||||
];
|
||||
// `own`: the type already has the bad style, and the filter changes only its other run or
|
||||
// paragraph; otherwise the bad style is the filter's own.
|
||||
let run = |id: NodeId, own: bool, bad: &CharStyle| {
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
if own {
|
||||
t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())];
|
||||
}
|
||||
let mut doc = d.clone();
|
||||
let n = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let id = doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
(doc, id)
|
||||
};
|
||||
let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| {
|
||||
let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let mut entry = entry;
|
||||
entry["id"] = json!(id.0);
|
||||
let mut changed = doc.clone();
|
||||
let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}");
|
||||
assert_eq!(&changed, doc, "{what}: nothing changed");
|
||||
};
|
||||
let fresh = d.clone().alloc_id();
|
||||
for (what, bad, says) in &bad_chars {
|
||||
let (doc, id) = run(fresh, false, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, what);
|
||||
let (doc, id) = run(fresh, true, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() };
|
||||
for (what, bad, says) in &bad_paras {
|
||||
let (doc, id) = run(fresh, false, &CharStyle::default());
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what);
|
||||
let mut doc = doc;
|
||||
if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) {
|
||||
t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]);
|
||||
}
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
// A set the document has, by name, takes the document's characters.
|
||||
let (mut doc, id) = run(fresh, false, &CharStyle::default());
|
||||
let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() });
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]});
|
||||
write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、']));
|
||||
}
|
||||
|
||||
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
|
||||
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
//! What a filter whose manifest lists `writes` may change about the type, images and symbol
|
||||
//! instances it was given: each one's name and transform; type's runs, with their character
|
||||
//! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows.
|
||||
//! Every other field stays read-only, and every value is checked before anything changes.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR};
|
||||
use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::{
|
||||
MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err,
|
||||
read_only_changed,
|
||||
};
|
||||
use crate::{Error, InputKind, Result};
|
||||
|
||||
/// The longest font family name a filter may set, in characters.
|
||||
const MAX_FAMILY: usize = 256;
|
||||
/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object.
|
||||
const MIN_DETERMINANT: f64 = 1e-12;
|
||||
/// The most pairs of an old and a new paragraph, past those both texts start and end with, that a
|
||||
/// change of the paragraph count compares by their text ([`moved_para_styles`]).
|
||||
const MAX_MATCHED_PAIRS: usize = 1 << 18;
|
||||
|
||||
/// The fields of an object of `kind` a filter that lists the kind in `writes` may change.
|
||||
fn writable(kind: InputKind) -> &'static [&'static str] {
|
||||
match kind {
|
||||
InputKind::Type => &["name", "transform", "text"],
|
||||
InputKind::Image => &["name", "transform", "opacity"],
|
||||
InputKind::SymbolInstance => &["name", "transform", "symbolId"],
|
||||
}
|
||||
}
|
||||
|
||||
/// The changes entry `o` of a filter's output makes to object `given` of `kind` (as the input gave
|
||||
/// it), `None` when it changes nothing. Fields it leaves out keep their values; a field it gives
|
||||
/// that isn't [`writable`] must be as given. Changed type text counts toward `text`, the bytes of
|
||||
/// text written over the whole output. The changes are keyed `name`, `transform`, `opacity`,
|
||||
/// `symbolId`, `runs` and `paragraphs`; their values are checked when they are applied ([`apply`]).
|
||||
pub(super) fn changes(o: &Map<String, Value>, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result<Option<Map<String, Value>>> {
|
||||
let mut keys: Vec<&String> = o.keys().filter(|k| *k != "id").collect();
|
||||
keys.sort();
|
||||
let mut out = Map::new();
|
||||
for k in keys {
|
||||
let v = &o[k];
|
||||
let was = given.get(k);
|
||||
if !writable(kind).contains(&k.as_str()) {
|
||||
if let Some(field) = was.map_or_else(|| Some(k.clone()), |w| first_difference(v, w, k)) {
|
||||
return Err(read_only_changed(at, &field));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match (k.as_str(), was) {
|
||||
("text", Some(was)) => text_changes(k, v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?,
|
||||
("name", None) if v.is_null() => {}
|
||||
(_, Some(was)) if first_difference(v, was, "").is_none() => {}
|
||||
_ => {
|
||||
out.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((!out.is_empty()).then_some(out))
|
||||
}
|
||||
|
||||
/// The `runs` and `paragraphs` of type text `v`, the output's field `key`, that differ from `was`
|
||||
/// (the text the input gave), into `out`; its other fields must be as given, and type given as
|
||||
/// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed
|
||||
/// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to
|
||||
/// [`MAX_INPUT_TEXT_TOTAL`], and to [`MAX_INPUT_RUNS`] paragraphs. With changed runs, `paragraphs`
|
||||
/// given as they were go into `out` too, to be checked against the new paragraphs.
|
||||
fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map<String, Value>) -> Result<()> {
|
||||
let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?;
|
||||
let mut keys: Vec<&String> = t.keys().collect();
|
||||
keys.sort();
|
||||
for k in keys {
|
||||
let field = format!("{key}.{k}");
|
||||
let given = was.get(k);
|
||||
let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some());
|
||||
if !matches!(k.as_str(), "runs" | "paragraphs") {
|
||||
if differs {
|
||||
let shown = given.and_then(|g| first_difference(&t[k], g, &field)).unwrap_or_else(|| field.clone());
|
||||
return Err(read_only_changed(at, &shown));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !differs {
|
||||
continue;
|
||||
}
|
||||
if truncated {
|
||||
return Err(out_err(&format!("{at}.{field}"), "the text of type given as `truncated` can't be changed"));
|
||||
}
|
||||
let list = t[k].as_array().filter(|l| l.len() <= MAX_INPUT_RUNS);
|
||||
let list = list.ok_or_else(|| out_err(&format!("{at}.{field}"), format!("must be a list of at most {MAX_INPUT_RUNS} entries")))?;
|
||||
if k == "runs" {
|
||||
if list.is_empty() {
|
||||
return Err(out_err(&format!("{at}.{field}"), "type needs at least one run"));
|
||||
}
|
||||
let bytes = list.iter().fold(0usize, |n, r| n.saturating_add(r.get("text").and_then(Value::as_str).map_or(0, str::len)));
|
||||
if bytes > MAX_INPUT_TEXT {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})")));
|
||||
}
|
||||
// Each paragraph gets a paragraph style; the text holds at most as many paragraphs as runs.
|
||||
let breaks = |r: &Value| r.get("text").and_then(Value::as_str).map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
|
||||
let paragraphs = list.iter().fold(1usize, |n, r| n.saturating_add(breaks(r)));
|
||||
if paragraphs > MAX_INPUT_RUNS {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("{paragraphs} paragraphs (limit {MAX_INPUT_RUNS})")));
|
||||
}
|
||||
*total = total.saturating_add(bytes);
|
||||
if *total > MAX_INPUT_TEXT_TOTAL {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output")));
|
||||
}
|
||||
}
|
||||
out.insert(k.clone(), t[k].clone());
|
||||
}
|
||||
// Paragraph styles given as they were still need one per paragraph of the new runs.
|
||||
if out.contains_key("runs")
|
||||
&& !out.contains_key("paragraphs")
|
||||
&& let Some(p) = t.get("paragraphs")
|
||||
{
|
||||
out.insert("paragraphs".into(), p.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every attribute name `T` reads, including those its JSON leaves out at their defaults: the field
|
||||
/// names serde's derive hands `deserialize_struct`.
|
||||
fn attr_names<T: DeserializeOwned>() -> &'static [&'static str] {
|
||||
use serde::de::{Error as _, Visitor, value::Error};
|
||||
|
||||
struct Names<'a>(&'a mut &'static [&'static str]);
|
||||
impl<'de> serde::Deserializer<'de> for Names<'_> {
|
||||
type Error = Error;
|
||||
fn deserialize_any<V: Visitor<'de>>(self, _: V) -> std::result::Result<V::Value, Error> {
|
||||
Err(Error::custom("not a struct"))
|
||||
}
|
||||
fn deserialize_struct<V: Visitor<'de>>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result<V::Value, Error> {
|
||||
*self.0 = fields;
|
||||
Err(Error::custom("field names only"))
|
||||
}
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit
|
||||
unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
let mut fields: &'static [&'static str] = &[];
|
||||
// Always an error: the probe only records the names.
|
||||
let _ = T::deserialize(Names(&mut fields));
|
||||
fields
|
||||
}
|
||||
|
||||
/// `v`, the field `key` of the entry at `parent`, as a `T` whose attributes are all ones `T` reads:
|
||||
/// a value that isn't an object is an error at `parent`, and an unknown key, as an ill-typed value,
|
||||
/// an error at `parent.key`.
|
||||
fn strict<T: DeserializeOwned>(v: &Value, parent: &str, key: &str) -> Result<T> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(parent, format!("`{key}` must be an object")))?;
|
||||
let at = format!("{parent}.{key}");
|
||||
let names = attr_names::<T>();
|
||||
if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("unknown key '{k}'")));
|
||||
}
|
||||
serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e))
|
||||
}
|
||||
|
||||
/// The field `key` of `v`, the style at `at`, holds only attributes `T` reads: an object, or each
|
||||
/// object of a list. An unknown key is an error at `at.key` (or `at.key[i]`); other values are left
|
||||
/// to the style's own checks.
|
||||
fn known_keys<T: DeserializeOwned>(v: &Value, at: &str, key: &str) -> Result<()> {
|
||||
let names = attr_names::<T>();
|
||||
let check = |o: &Map<String, Value>, at: &str| match o.keys().find(|k| !names.contains(&k.as_str())) {
|
||||
Some(k) => {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
Err(out_err(at, format!("unknown key '{k}'")))
|
||||
}
|
||||
None => Ok(()),
|
||||
};
|
||||
match v.get(key) {
|
||||
Some(Value::Object(o)) => check(o, &format!("{at}.{key}")),
|
||||
Some(Value::Array(list)) => list.iter().enumerate().try_for_each(|(i, e)| match e {
|
||||
Value::Object(o) => check(o, &format!("{at}.{key}[{i}]")),
|
||||
_ => Ok(()),
|
||||
}),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't
|
||||
/// flatten the object.
|
||||
fn decode_transform(v: &Value, at: &str) -> Result<Affine> {
|
||||
let c: Option<Vec<f64>> = v.as_array().and_then(|a| a.iter().map(Value::as_f64).collect());
|
||||
let c: [f64; 6] = c.and_then(|c| c.try_into().ok()).ok_or_else(|| out_err(at, "must be a list of 6 numbers"))?;
|
||||
if !c.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) {
|
||||
return Err(out_err(at, format!("a number is out of range (limit ±{MAX_COORD})")));
|
||||
}
|
||||
let xf = Affine::new(c);
|
||||
if xf.determinant().abs() < MIN_DETERMINANT {
|
||||
return Err(out_err(at, "flattens the object to a line or a point"));
|
||||
}
|
||||
Ok(xf)
|
||||
}
|
||||
|
||||
/// The transform object `n` is given with: type's and an instance's own, an image's (for a
|
||||
/// distorted image, the placement nearest its corners at its middle).
|
||||
fn given_transform(n: &Node) -> Option<Affine> {
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.xf),
|
||||
NodeKind::Image(im) => Some(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)),
|
||||
NodeKind::SymbolInstance { xf, .. } => Some(*xf),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `changes` ([`changes`]) to `n`, an input object of `doc`; `at` names it in errors. Each
|
||||
/// value is checked first, and an error leaves `n` to be dropped.
|
||||
pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map<String, Value>, at: &str) -> Result<()> {
|
||||
if let Some(v) = changes.get("transform") {
|
||||
let at = format!("{at}.transform");
|
||||
let new = decode_transform(v, &at)?;
|
||||
let old = given_transform(n).filter(|xf| xf.determinant().abs() >= MIN_DETERMINANT);
|
||||
let old = old.ok_or_else(|| out_err(&at, "an object flattened to a line or a point can't be placed again"))?;
|
||||
// Everything the object carries moves with it: a distorted image's corners, its gradients.
|
||||
n.transform(new * old.inverse(), false);
|
||||
let distorted = n.is_distorted_image();
|
||||
match &mut n.kind {
|
||||
NodeKind::Text(t) => t.xf = new,
|
||||
NodeKind::SymbolInstance { xf, .. } => *xf = new,
|
||||
NodeKind::Image(im) if !distorted => im.xf = new,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(v) = changes.get("opacity") {
|
||||
let op = v.as_f64().filter(|o| (0.0..=1.0).contains(o));
|
||||
n.opacity = op.ok_or_else(|| out_err(&format!("{at}.opacity"), "must be a number from 0 to 1"))? as f32;
|
||||
}
|
||||
if let Some(v) = changes.get("symbolId") {
|
||||
let at = format!("{at}.symbolId");
|
||||
let name = v.as_str().ok_or_else(|| out_err(&at, "must be the name of a symbol"))?;
|
||||
if !doc.symbols.iter().any(|s| s.name == name) {
|
||||
let shown = crate::permissions::display_text(name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("'{shown}' is not a symbol in this document")));
|
||||
}
|
||||
let other = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol != name);
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut n.kind {
|
||||
*symbol = name.to_string();
|
||||
}
|
||||
// An edited part's path names an object of the old symbol's art, as Replace Symbol finds.
|
||||
if other && !n.extras().symbol_overrides.is_empty() {
|
||||
n.extras_mut().symbol_overrides.clear();
|
||||
}
|
||||
}
|
||||
if changes.contains_key("runs") || changes.contains_key("paragraphs") {
|
||||
let story = doc.story_of(n.id).len();
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(read_only_changed(at, "text")) };
|
||||
set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?;
|
||||
}
|
||||
if let Some(v) = changes.get("name") {
|
||||
n.name = Some(decode_name(v, at)?).filter(|s| !s.trim().is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gives type `t` the runs `runs` and paragraph styles `paragraphs` a filter returned (`threaded`:
|
||||
/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an
|
||||
/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they
|
||||
/// were, in the same order, and the characters of threaded type or type with ruby stay as they
|
||||
/// were. Every number of every run's style is in the range the character style commands keep it
|
||||
/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font
|
||||
/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph
|
||||
/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays
|
||||
/// the same, and otherwise the styles follow the paragraphs' text ([`moved_para_styles`]).
|
||||
fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> {
|
||||
if let Some(runs) = runs {
|
||||
let at = format!("{at}.text.runs");
|
||||
let list = runs.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
// The type's own styles, as JSON text, to look each run's style up once.
|
||||
let own: HashSet<String> = t.runs.iter().filter_map(|r| serde_json::to_string(&r.style).ok()).collect();
|
||||
let mut new = Vec::with_capacity(list.len());
|
||||
for (i, v) in list.iter().enumerate() {
|
||||
let at = format!("{at}[{i}]");
|
||||
let o = v.as_object().ok_or_else(|| out_err(&at, "a run must be {\"text\", \"style\", \"inline\"?}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "text" | "style" | "inline")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("unknown key '{k}'")));
|
||||
}
|
||||
let key = "text";
|
||||
let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?;
|
||||
let style_v = o.get("style").unwrap_or(&Value::Null);
|
||||
let mut style: CharStyle = strict(style_v, &at, "style")?;
|
||||
known_keys::<vectorcraft_doc::Dash>(style_v, &format!("{at}.style"), "stroke_dash")?;
|
||||
let inline = match o.get("inline") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?),
|
||||
};
|
||||
if inline.is_none() {
|
||||
if text.contains(INLINE_CHAR) {
|
||||
return Err(out_err(&at, "`text` holds the character of an inline graphic"));
|
||||
}
|
||||
// Every number goes to the layout, so it is checked even in a style the type has.
|
||||
style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?;
|
||||
for key in ["fill", "stroke"] {
|
||||
if let Some(p) = style_v.get(key) {
|
||||
check_paint_keys(p, &format!("{at}.style.{key}"))?;
|
||||
}
|
||||
}
|
||||
if !serde_json::to_string(&style).is_ok_and(|s| own.contains(&s)) {
|
||||
check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?;
|
||||
}
|
||||
}
|
||||
new.push(TextRun { text: text.to_string(), style, inline });
|
||||
}
|
||||
// Inline graphics are compared as saved (their measured bounds aren't), and keep those.
|
||||
let saved = |r: &&TextRun| serde_json::to_value(r).ok();
|
||||
let old_inline: Vec<&TextRun> = t.runs.iter().filter(|r| r.inline.is_some()).collect();
|
||||
let new_inline: Vec<&TextRun> = new.iter().filter(|r| r.inline.is_some()).collect();
|
||||
if old_inline.len() != new_inline.len() || old_inline.iter().zip(&new_inline).any(|(a, b)| saved(a) != saved(b)) {
|
||||
return Err(out_err(&at, "inline graphics can't be added, removed, reordered or changed"));
|
||||
}
|
||||
let mut kept = old_inline.into_iter().cloned().collect::<Vec<_>>().into_iter();
|
||||
for r in new.iter_mut().filter(|r| r.inline.is_some()) {
|
||||
if let Some(old) = kept.next() {
|
||||
*r = old;
|
||||
}
|
||||
}
|
||||
let plain: String = new.iter().map(|r| r.text.as_str()).collect();
|
||||
let old = t.plain_text();
|
||||
let mut moved = None;
|
||||
if plain != old {
|
||||
if threaded {
|
||||
return Err(out_err(&at, "the characters of threaded type can't be changed"));
|
||||
}
|
||||
if !t.ruby.is_empty() {
|
||||
return Err(out_err(&at, "the characters of type with ruby can't be changed"));
|
||||
}
|
||||
let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count();
|
||||
if paragraphs.is_none() && breaks(&plain) != breaks(&old) {
|
||||
// Paragraphs added or joined: the styles follow the paragraphs' text. With as many
|
||||
// paragraphs as before, each keeps its style.
|
||||
moved = Some(moved_para_styles(&t.paragraph_styles(), &old, &plain));
|
||||
}
|
||||
}
|
||||
t.runs = new;
|
||||
if let Some(styles) = moved {
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
}
|
||||
match paragraphs {
|
||||
Some(v) => {
|
||||
let text = format!("{at}.text");
|
||||
let list = v.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let count = t.paragraph_count();
|
||||
if list.len() != count {
|
||||
return Err(out_err(&format!("{text}.paragraphs"), format!("expected {count} paragraph styles, one per paragraph")));
|
||||
}
|
||||
let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &text, &format!("paragraphs[{i}]"))).collect::<Result<_>>()?;
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
None => t.normalize_paras(),
|
||||
}
|
||||
// The layout is measured again before the type is drawn.
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The paragraph styles of text `new` that replaced `old`, whose paragraphs had `styles` (one per
|
||||
/// paragraph). The paragraphs, split at `\n`, are matched as a longest common subsequence of their
|
||||
/// texts after the paragraphs both start and end with are set aside; when the paragraphs left in
|
||||
/// the old text times those left in the new pass [`MAX_MATCHED_PAIRS`], they are paired in order
|
||||
/// instead. A
|
||||
/// matched paragraph keeps its style. Between two matched paragraphs, the changed ones take the
|
||||
/// styles of the old paragraphs there in order, and the last of those past their count; paragraphs
|
||||
/// added where there were none take the style of the paragraph before them, or of the next one at
|
||||
/// the start. A style copied to a paragraph that was not there loses its list number
|
||||
/// ([`vectorcraft_doc::text::ParaList::start`]).
|
||||
fn moved_para_styles(styles: &[ParaStyle], old: &str, new: &str) -> Vec<ParaStyle> {
|
||||
let a: Vec<&str> = old.split('\n').collect();
|
||||
let b: Vec<&str> = new.split('\n').collect();
|
||||
let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
||||
let (a_rest, b_rest) = (a.get(pre..).unwrap_or_default(), b.get(pre..).unwrap_or_default());
|
||||
let suf = a_rest.iter().rev().zip(b_rest.iter().rev()).take_while(|(x, y)| x == y).count();
|
||||
// `matched[j]`: the old paragraph that new paragraph `j` is, if any.
|
||||
let mut matched: Vec<Option<usize>> = vec![None; b.len()];
|
||||
for (j, m) in matched.iter_mut().enumerate().take(pre) {
|
||||
*m = Some(j);
|
||||
}
|
||||
for k in 0..suf {
|
||||
if let Some(m) = matched.get_mut(b.len() - 1 - k) {
|
||||
*m = Some(a.len() - 1 - k);
|
||||
}
|
||||
}
|
||||
let (am, bm) = (a_rest.get(..a_rest.len() - suf).unwrap_or_default(), b_rest.get(..b_rest.len() - suf).unwrap_or_default());
|
||||
if !am.is_empty() && !bm.is_empty() && am.len().saturating_mul(bm.len()) <= MAX_MATCHED_PAIRS {
|
||||
let mut ids = std::collections::HashMap::new();
|
||||
let mut id = |s: &str| {
|
||||
let next = ids.len();
|
||||
*ids.entry(s.to_string()).or_insert(next)
|
||||
};
|
||||
let ai: Vec<usize> = am.iter().map(|s| id(s)).collect();
|
||||
let bi: Vec<usize> = bm.iter().map(|s| id(s)).collect();
|
||||
// `len[i * w + j]`: the length of the longest common subsequence of `ai[i..]` and `bi[j..]`.
|
||||
let w = bi.len() + 1;
|
||||
let mut len = vec![0u32; (ai.len() + 1) * w];
|
||||
for i in (0..ai.len()).rev() {
|
||||
for j in (0..bi.len()).rev() {
|
||||
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
|
||||
let v = if ai.get(i) == bi.get(j) { at(i + 1, j + 1) + 1 } else { at(i + 1, j).max(at(i, j + 1)) };
|
||||
if let Some(c) = len.get_mut(i * w + j) {
|
||||
*c = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < ai.len() && j < bi.len() {
|
||||
if ai.get(i) == bi.get(j) {
|
||||
if let Some(m) = matched.get_mut(pre + j) {
|
||||
*m = Some(pre + i);
|
||||
}
|
||||
(i, j) = (i + 1, j + 1);
|
||||
} else if at(i + 1, j) >= at(i, j + 1) {
|
||||
i += 1;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let style = |i: usize, numbered: bool| {
|
||||
let mut s = styles.get(i).or(styles.last()).cloned().unwrap_or_default();
|
||||
if !numbered && let Some(l) = s.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let (mut next_old, mut j) = (0, 0);
|
||||
while j < b.len() {
|
||||
if let Some(&Some(i)) = matched.get(j) {
|
||||
out.push(style(i, true));
|
||||
(next_old, j) = (i + 1, j + 1);
|
||||
continue;
|
||||
}
|
||||
// New paragraphs `j..end` stand where old paragraphs `next_old..old_end` were.
|
||||
let end = (j..b.len()).find(|&k| matched.get(k).is_some_and(Option::is_some)).unwrap_or(b.len());
|
||||
let old_end = matched.get(end).copied().flatten().unwrap_or(a.len());
|
||||
for g in 0..end - j {
|
||||
out.push(if next_old < old_end {
|
||||
style((next_old + g).min(old_end - 1), next_old + g < old_end)
|
||||
} else {
|
||||
style(next_old.checked_sub(1).unwrap_or(old_end), false)
|
||||
});
|
||||
}
|
||||
j = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An attribute of the style at `at` out of its range, naming the attribute.
|
||||
fn range_err(at: &str, e: &AttrRangeError) -> Error {
|
||||
out_err(&format!("{at}.{}", e.key), &e.message)
|
||||
}
|
||||
|
||||
/// Paragraph style `v` from a filter's output, the entry `key` of the text at `parent`: each
|
||||
/// attribute one a paragraph reads, each number in the range the paragraph style commands keep it
|
||||
/// to ([`ParaStyle::check_ranges`], the Justification options as given), and a custom Kinsoku set
|
||||
/// one of `doc`'s, by name, whose characters it takes.
|
||||
fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result<ParaStyle> {
|
||||
let mut st: ParaStyle = strict(v, parent, key)?;
|
||||
let at = format!("{parent}.{key}");
|
||||
known_keys::<vectorcraft_doc::HyphenationOptions>(v, &at, "hyphenation")?;
|
||||
known_keys::<JustificationOptions>(v, &at, "justification")?;
|
||||
known_keys::<vectorcraft_doc::TabStop>(v, &at, "tabs")?;
|
||||
known_keys::<vectorcraft_doc::text::ParaList>(v, &at, "list")?;
|
||||
let justification = match v.get("justification") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(j) => Some(serde_json::from_value::<JustificationOptions>(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?),
|
||||
};
|
||||
st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(&at, &e))?;
|
||||
if let Some(set) = &st.kinsoku_set {
|
||||
let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| {
|
||||
let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'"))
|
||||
})?;
|
||||
st.kinsoku_set = Some(std::sync::Arc::new(found.clone()));
|
||||
}
|
||||
Ok(st)
|
||||
}
|
||||
|
||||
/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before):
|
||||
/// its font family is 1 to [`MAX_FAMILY`] printable characters, counted as given, and its fill and
|
||||
/// stroke are admitted as an object's paints are. Its numbers and its paints' keys are checked for
|
||||
/// every run ([`set_text`]).
|
||||
fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> {
|
||||
let family = s.font_family.trim();
|
||||
if family.is_empty() || s.font_family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) {
|
||||
return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters")));
|
||||
}
|
||||
let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| {
|
||||
let at = format!("{at}.{key}");
|
||||
let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?;
|
||||
admit_paint(doc, decode_paint(&v, &at)?, was, &at)
|
||||
};
|
||||
s.fill = paint(&s.fill, was.map(|w| &w.fill), "fill")?;
|
||||
s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that paint `v` of a style, at `at`, has no key besides `type` and those its `type`
|
||||
/// reads; a key of another paint, or an unknown one, is an error naming it.
|
||||
fn check_paint_keys(v: &Value, at: &str) -> Result<()> {
|
||||
let Some(o) = v.as_object() else { return Ok(()) };
|
||||
let known: &[&str] = match o.get("type").and_then(Value::as_str) {
|
||||
Some("solid") => &["color", "swatch", "tint"],
|
||||
Some("gradient") => attr_names::<vectorcraft_color::GradientPaint>(),
|
||||
Some("pattern") => &["pattern", "xf"],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| *k != "type" && !known.contains(&k.as_str())) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(at, format!("unknown key '{k}'")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,7 +15,8 @@ use crate::{Error, Kind, Result};
|
||||
|
||||
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
|
||||
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
|
||||
/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]).
|
||||
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]) and a manifest's
|
||||
/// `context` ([`CONTEXT_API`]).
|
||||
pub const API_LEVEL: u32 = 3;
|
||||
|
||||
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
|
||||
@@ -25,6 +26,9 @@ pub const PROGRESS_API: u32 = 2;
|
||||
/// The API level that adds a filter's `inputs` ([`crate::InputKind`]).
|
||||
pub const INPUTS_API: u32 = 2;
|
||||
|
||||
/// The API level that adds a filter's `writes`: the kinds among its `inputs` it may change.
|
||||
pub const WRITES_API: u32 = 3;
|
||||
|
||||
/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key
|
||||
/// is ignored.
|
||||
pub const MENU_API: u32 = 2;
|
||||
|
||||
@@ -338,18 +338,19 @@ impl Operand {
|
||||
/// object: `[new] File|Folder(…)`, `new File|Folder`, `File.openDialog(…)`, `File.saveDialog(…)`,
|
||||
/// `Folder.selectDialog(…)`, `Folder.<place>` ([`catalog::FOLDER_PLACES`]) or a variable holding
|
||||
/// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a
|
||||
/// File or Folder object.
|
||||
/// File or Folder object, `Some(true)` when it counts as a Folder object whatever the path names.
|
||||
///
|
||||
/// Only `new Folder(…)`, `new Folder` and `Folder.<place>` are Folder objects whatever the path
|
||||
/// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)`
|
||||
/// gives a File or Folder object for what the user picks, `Folder.current` is the one place a
|
||||
/// script can assign, and a variable another variable was assigned to may hold a File object.
|
||||
fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand {
|
||||
/// Only `new Folder(…)`, `new Folder`, `Folder.<place>` and such a variable are Folder objects
|
||||
/// whatever the path names. `Folder(…)` gives a File object when the path names a file,
|
||||
/// `Folder.selectDialog(…)` gives a File or Folder object for what the user picks, and
|
||||
/// `Folder.current` is the one place a script can assign. A variable another variable is assigned
|
||||
/// may hold a File object, so a grouped value passes `Some(false)` for any variable.
|
||||
fn file_step(self, t: &Sig, file: bool, alias: Option<bool>) -> Operand {
|
||||
match self {
|
||||
Operand::Start if t.word("new") => Operand::New,
|
||||
Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER },
|
||||
Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER },
|
||||
Operand::Start if alias => Operand::Done(Held::File { folder: false }),
|
||||
Operand::Start if alias.is_some() => Operand::Done(Held::File { folder: alias == Some(true) }),
|
||||
Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder },
|
||||
Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false },
|
||||
Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder },
|
||||
@@ -1378,7 +1379,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) {
|
||||
let after = self.depth();
|
||||
let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text);
|
||||
let alias = self.alias(t);
|
||||
let alias = self.alias(t).then_some(false);
|
||||
let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return };
|
||||
if after < g.level {
|
||||
// The `)` of the innermost pair: the operand, when complete, is the pair's value and the
|
||||
@@ -1436,7 +1437,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
fn paren_step(&mut self, t: &Sig<'s>, before: usize) {
|
||||
let after = self.depth();
|
||||
let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text);
|
||||
let alias = self.alias(t);
|
||||
// A variable in grouping parentheses is the object it holds now, as it is outside them
|
||||
// ([`Analyzer::held_file`]).
|
||||
let alias = self.alias(t).then(|| self.folder(t.text));
|
||||
if let Some(p) = self.parens.last_mut() {
|
||||
if before == p.level {
|
||||
p.operand = match std::mem::replace(&mut p.operand, Operand::Other) {
|
||||
|
||||
@@ -619,6 +619,25 @@ fn file_only_calls_on_a_folder_do_nothing() {
|
||||
assert_eq!(lines("file.dialog"), [8]);
|
||||
}
|
||||
|
||||
/// A variable holding a Folder object is the same object in grouping parentheses, so `(d).write(s)`
|
||||
/// and `(d).length = 0` do nothing, as `d.write(s)` and `d.length = 0` do. A variable that may hold
|
||||
/// a File object still counts in them.
|
||||
#[test]
|
||||
fn a_folder_in_parentheses_is_still_a_folder() {
|
||||
let r = report(concat!(
|
||||
"var d = new Folder(p);\n",
|
||||
"(d).write(s); ((d)).copy(q); (d).open('r'); (d).length = 0;\n",
|
||||
"var f = new File(p);\n",
|
||||
"(f).write(s);\n",
|
||||
"var g = Folder(p); (g).open('r');\n",
|
||||
));
|
||||
let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default();
|
||||
let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect();
|
||||
assert_eq!(outside, [("filesWritten", &[4][..])]);
|
||||
assert_eq!(lines("file.write"), [4]);
|
||||
assert_eq!(lines("file.read"), [5]);
|
||||
}
|
||||
|
||||
/// A File object assigned to a function's own variable, its parameter or a `catch` block's
|
||||
/// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter
|
||||
/// starts without what the outer variable of the same name was assigned.
|
||||
|
||||
@@ -90,6 +90,9 @@ struct Press {
|
||||
at: Point,
|
||||
/// Whether Shift was held when the click's circle was last looked for.
|
||||
shift: bool,
|
||||
/// The tool's `radius` when the button went down: Shift uses it for the whole press, whatever
|
||||
/// `tool.setOption` writes meanwhile.
|
||||
shift_radius: f64,
|
||||
/// How far the pointer was from the press last time, and the radius the drag set (none until
|
||||
/// the pointer moves far enough).
|
||||
reach: f64,
|
||||
@@ -338,8 +341,8 @@ impl TangentCircleTool {
|
||||
// A change without an undo step since the press: a changed first segment is forgotten (the
|
||||
// press then draws nothing), and the circle follows the segments it may touch as they are now.
|
||||
self.forget_if_changed(cx);
|
||||
let radius = self.radius;
|
||||
let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return };
|
||||
let radius = press.shift_radius;
|
||||
// A pressed segment that is gone leaves nothing to touch.
|
||||
let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] };
|
||||
let moved = second != press.second;
|
||||
@@ -410,7 +413,7 @@ impl Tool for TangentCircleTool {
|
||||
self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX));
|
||||
self.looked = true;
|
||||
self.hover = None;
|
||||
self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None });
|
||||
self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, shift_radius: self.radius, reach: 0.0, radius: None });
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Drag => {
|
||||
@@ -707,6 +710,24 @@ mod tests {
|
||||
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_press_keeps_the_radius_it_started_with() {
|
||||
let d = doc();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TangentCircleTool::default();
|
||||
t.set_option("radius", &json!(20));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0));
|
||||
// A radius written during the press does not reach the circle, however Shift changes.
|
||||
t.set_option("radius", &json!(5));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 200.0, 139.0));
|
||||
t.pointer(&cx, &shifted(PointerKind::Drag, 200.0, 139.0));
|
||||
let released = up(&mut t, &cx, &shifted(PointerKind::Up, 200.0, 139.0));
|
||||
assert!(close(drawn(&released), (180.0, 100.0, 40.0, 40.0)), "{released:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_options_set_its_cross_radii_and_color() {
|
||||
let d = doc();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The
|
||||
//! paths around the area stay as they are, and nothing needs to be selected.
|
||||
|
||||
use vectorcraft_geom::kurbo::ParamCurveDeriv;
|
||||
use vectorcraft_geom::path::segment_bounds;
|
||||
use vectorcraft_geom::{ParamCurve, PathSeg};
|
||||
|
||||
@@ -171,13 +172,39 @@ fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks
|
||||
Some(shape)
|
||||
}
|
||||
|
||||
/// How far (pt) the middle of a piece of an outline may lie from a mask's outline and still count
|
||||
/// as on the mask's edge, which [`clip_to`] keeps. It covers rounding only, so a piece just outside
|
||||
/// the mask is still left out.
|
||||
const ON_MASK: f64 = 1e-6;
|
||||
|
||||
/// How far (pt) to each side of a piece [`shows_through`] looks for the mask's filled area: past
|
||||
/// [`ON_MASK`], and within a filled strip of the mask as narrow as this.
|
||||
const MASK_SIDE: f64 = 1e-4;
|
||||
|
||||
/// Does the piece of an outline whose middle is `p`, running in direction `dir` there, show
|
||||
/// through `mask` filled with `rule`? A piece off the mask's outline shows when the filled area
|
||||
/// holds `p`. A piece on the outline ([`ON_MASK`]) shows when the filled area lies on one side of
|
||||
/// it ([`MASK_SIDE`]), so every side of a square clipped by the same square shows, and an outline
|
||||
/// of the mask that bounds no filled area (two copies of one outline under even-odd) hides it.
|
||||
fn shows_through(mask: &PathData, rule: FillRule, p: Point, dir: vectorcraft_geom::Vec2) -> bool {
|
||||
if !mask.nearest(p).is_some_and(|(.., d)| d <= ON_MASK) {
|
||||
return path_contains(mask, rule, p);
|
||||
}
|
||||
let len = dir.hypot();
|
||||
if !(len > 0.0 && len.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let side = dir.turn_90() * (MASK_SIDE / len);
|
||||
path_contains(mask, rule, p + side) || path_contains(mask, rule, p - side)
|
||||
}
|
||||
|
||||
/// `shape` cut to `mask` (filled with `rule`). With `filled` (the path's fill draws), its closed
|
||||
/// subpaths are cut to their overlap with the mask, whose edge then bounds the fill. Its other
|
||||
/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask,
|
||||
/// so a hidden part of an outline does not close an area. A subpath with more segments or
|
||||
/// crossings than [`po::addons::pathtools::crossings_on`] takes is left out. None when nothing of
|
||||
/// it is inside.
|
||||
fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option<po::Shape> {
|
||||
/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask or
|
||||
/// on its edge ([`shows_through`]), so a hidden part of an outline does not close an area. A
|
||||
/// subpath with more segments or crossings than [`po::addons::pathtools::crossings_on`] takes is
|
||||
/// left out. None when nothing of it is inside.
|
||||
pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option<po::Shape> {
|
||||
let (b, mb) = (shape.path.bounds()?, mask.bounds()?);
|
||||
if !meet(&b, &mb) {
|
||||
return None;
|
||||
@@ -195,7 +222,17 @@ fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> O
|
||||
let (cut, at) = po::addons::pathtools::insert_at(sp, &places);
|
||||
subs.extend(cut.cut_at(&at).into_iter().filter(|piece| {
|
||||
let n = piece.segment_count();
|
||||
n > 0 && path_contains(mask, rule, piece.segment(n / 2).eval(0.5))
|
||||
n > 0 && {
|
||||
let seg = piece.segment(n / 2);
|
||||
// Where the tangent vanishes (a cusp at the middle), the curve runs along its second
|
||||
// derivative there, and a straight segment with that degenerate form along its chord.
|
||||
let d1 = seg.deriv();
|
||||
let dir = [d1.eval(0.5).to_vec2(), d1.deriv().eval(0.5).to_vec2(), seg.p3 - seg.p0]
|
||||
.into_iter()
|
||||
.find(|v| v.hypot2() > 0.0)
|
||||
.unwrap_or_default();
|
||||
shows_through(mask, rule, seg.eval(0.5), dir)
|
||||
}
|
||||
}));
|
||||
}
|
||||
if subs.is_empty() {
|
||||
|
||||
@@ -3796,6 +3796,32 @@ fn fill_area_press_does_not_search_a_hover_position_it_passed() {
|
||||
assert_eq!(super::fill_area::hover_searches_started() - started, 1, "only the search that was running");
|
||||
}
|
||||
|
||||
/// An outline without a fill, cut to a clipping mask, keeps the pieces on the mask's edge: a square
|
||||
/// clipped by the same square keeps all four sides. A square just outside the mask, and a square on
|
||||
/// an outline of the mask that bounds no filled area (two copies of the square under even-odd),
|
||||
/// keep nothing.
|
||||
#[test]
|
||||
fn fill_area_clip_keeps_outline_pieces_on_the_mask_edge() {
|
||||
let unit = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
let clip =
|
||||
|shape: PathData, mask: &PathData, rule: FillRule| super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule);
|
||||
let kept = clip(shapes::rectangle(unit), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge");
|
||||
assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>(), 4, "{:?}", kept.path);
|
||||
let outside = shapes::rectangle(Rect::new(-0.005, -0.005, 100.005, 100.005));
|
||||
assert!(clip(outside, &shapes::rectangle(unit), FillRule::NonZero).is_none());
|
||||
let mut twice = shapes::rectangle(unit);
|
||||
let mut back = shapes::rectangle(unit).subpaths;
|
||||
back[0].anchors.reverse();
|
||||
twice.subpaths.extend(back);
|
||||
assert!(clip(shapes::rectangle(unit), &twice, FillRule::EvenOdd).is_none());
|
||||
// A top side drawn as a cubic whose tangent vanishes at its middle shows as well.
|
||||
let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner };
|
||||
let (o, x, xy, y) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0));
|
||||
let cusp = SubPath::new(vec![a(o, o, x), a(x, o, x), a(xy, xy, xy), a(y, y, y)], true);
|
||||
let kept = clip(PathData::single(cusp), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge");
|
||||
assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>(), 4, "{:?}", kept.path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_builds_the_three_tools() {
|
||||
for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] {
|
||||
|
||||
@@ -224,6 +224,12 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered
|
||||
if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p }
|
||||
}
|
||||
|
||||
/// Whether a circle preview of radius `r` is drawn dashed. The canvas draws a dashed outline dash by
|
||||
/// dash along its whole length, so a circle longer than [`DASHED_PX`] on screen is drawn solid.
|
||||
pub(crate) fn preview_dashed(cx: &ToolContext, r: f64) -> bool {
|
||||
std::f64::consts::TAU * r <= cx.tol(DASHED_PX)
|
||||
}
|
||||
|
||||
/// Are the points two or more different points through which no circle is drawn: three on one
|
||||
/// line, or a circle that would reach past the canvas?
|
||||
fn too_large(points: &[Point], centered: bool, standard_anchors: bool) -> bool {
|
||||
@@ -573,10 +579,7 @@ impl Tool for CircleTool {
|
||||
let on_outline = if self.centered { points.get(1..).unwrap_or(&[]) } else { &points[..] };
|
||||
shapes::circle_with_anchors_at(c, r, on_outline).to_bezpath()
|
||||
};
|
||||
// The canvas draws a dashed outline dash by dash along its whole length: a circle longer
|
||||
// than DASHED_PX on screen is drawn solid instead.
|
||||
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
|
||||
o.push(Overlay::Path { path, color, width: 1.0, dashed });
|
||||
o.push(Overlay::Path { path, color, width: 1.0, dashed: preview_dashed(cx, r) });
|
||||
let opts = self.options;
|
||||
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
|
||||
if opts.radii {
|
||||
|
||||
@@ -999,7 +999,7 @@ impl Tool for ShapeTool {
|
||||
let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() };
|
||||
o.extend(self.guides.iter().cloned());
|
||||
// The points Shift-clicks placed, and after two of them the circle through them and the
|
||||
// pointer, dashed.
|
||||
// pointer, dashed (solid when it is too long on screen, as the Circle tool draws it).
|
||||
for p in &self.through {
|
||||
o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 });
|
||||
}
|
||||
@@ -1007,7 +1007,7 @@ impl Tool for ShapeTool {
|
||||
&& let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h)
|
||||
{
|
||||
let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath();
|
||||
o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true });
|
||||
o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: crate::circle::preview_dashed(cx, r) });
|
||||
}
|
||||
if let Some((p, text)) = &self.measure {
|
||||
o.push(Overlay::Measure { p: *p, text: text.clone() });
|
||||
|
||||
@@ -667,6 +667,37 @@ fn the_circle_preview_passes_through_the_snapped_pointer() {
|
||||
assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}");
|
||||
}
|
||||
|
||||
/// A circle through the Shift-clicked points more than 50,000 screen points around is previewed
|
||||
/// solid, as the Circle tool previews it: points nearly on one line give a radius of about
|
||||
/// 1,250,000 pt.
|
||||
#[test]
|
||||
fn a_huge_circle_through_shift_clicked_points_is_previewed_solid() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
for (x, y) in [(0.0, 0.0), (1000.0, 0.0)] {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift));
|
||||
}
|
||||
let paths = |t: &ShapeTool| {
|
||||
t.overlays(&cx)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Overlay::Path { dashed, .. } => Some(dashed),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 0.1));
|
||||
assert_eq!(paths(&t), vec![false]);
|
||||
// At 100% a circle 100 pt across is dashed.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 300.0));
|
||||
assert_eq!(paths(&t), vec![true]);
|
||||
}
|
||||
|
||||
/// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click
|
||||
/// starts a new circle.
|
||||
#[test]
|
||||
|
||||
@@ -86,6 +86,9 @@ struct Drag {
|
||||
/// when the Alt state at the release changes what it transforms.
|
||||
pointer: Point,
|
||||
shift: bool,
|
||||
/// The pointer's own movement since the press, before snapping: a snapped press can turn a
|
||||
/// level drag diagonal, so Scale's Shift-drag uses this to pick an axis (#6324).
|
||||
moved: Vec2,
|
||||
last: Affine,
|
||||
/// The document revision at the press: a press whose document or selection changes before it
|
||||
/// becomes a drag is dropped, so its reference point is never applied to other objects.
|
||||
@@ -100,6 +103,16 @@ impl Drag {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer drag [`TransformTool::solve`] turns into a transform.
|
||||
struct SolveDrag {
|
||||
start: Point,
|
||||
p: Point,
|
||||
/// The pointer's own movement since the press, before snapping (#6324).
|
||||
moved: Vec2,
|
||||
shift: bool,
|
||||
bounds: Rect,
|
||||
}
|
||||
|
||||
/// The first point of a Reflect axis set by a click, waiting for the second point, with the
|
||||
/// selection and the document revision it was set for.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -222,7 +235,7 @@ impl TransformTool {
|
||||
/// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the
|
||||
/// line the pointer draws on the page.
|
||||
pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) {
|
||||
let (m, a, b) = self.solve(angle, o, start, p, shift, bounds);
|
||||
let (m, a, b) = self.solve(angle, o, SolveDrag { start, p, moved: p - start, shift, bounds });
|
||||
(m, self.label(a, b))
|
||||
}
|
||||
|
||||
@@ -253,7 +266,8 @@ impl TransformTool {
|
||||
/// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height
|
||||
/// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as
|
||||
/// `object.shear` takes it (Shear).
|
||||
fn solve(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, f64, f64) {
|
||||
fn solve(&self, angle: f64, o: Point, d: SolveDrag) -> (Affine, f64, f64) {
|
||||
let SolveDrag { start, p, moved, shift, bounds } = d;
|
||||
let frame = OrientedBox { angle, rect: Rect::ZERO };
|
||||
let local = |v: Vec2| frame.to_doc().inverse() * v.to_point();
|
||||
match self.kind {
|
||||
@@ -276,7 +290,18 @@ impl TransformTool {
|
||||
let d1 = local(p - o).to_vec2();
|
||||
let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 };
|
||||
let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y));
|
||||
if shift {
|
||||
// Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal
|
||||
// one uniformly (#6324). The pointer's own movement decides, in the box's axes; a
|
||||
// snapped press can otherwise turn a level drag diagonal. A drag that starts level
|
||||
// with the reference point on that axis has nothing to scale it by, so it stays uniform.
|
||||
let moved_local = local(moved).to_vec2();
|
||||
let axis_angle = moved_local.y.abs().atan2(moved_local.x.abs()).to_degrees();
|
||||
let along = moved_local.hypot() > 1e-9;
|
||||
if shift && along && axis_angle <= 22.5 && d0.x.abs() > 1e-6 {
|
||||
sy = 1.0;
|
||||
} else if shift && along && axis_angle >= 67.5 && d0.y.abs() > 1e-6 {
|
||||
sx = 1.0;
|
||||
} else if shift {
|
||||
let l2 = d0.hypot2();
|
||||
let k = if l2 > 1e-12 { d1.dot(d0) / l2 } else { 1.0 };
|
||||
sx = k;
|
||||
@@ -380,6 +405,7 @@ impl Tool for TransformTool {
|
||||
anchors,
|
||||
pointer: p,
|
||||
shift: false,
|
||||
moved: Vec2::ZERO,
|
||||
last: Affine::IDENTITY,
|
||||
revision: cx.revision,
|
||||
});
|
||||
@@ -406,10 +432,15 @@ impl Tool for TransformTool {
|
||||
Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) });
|
||||
out.push(Action::Begin(self.kind.label().into()));
|
||||
}
|
||||
let moved = p - d.start;
|
||||
let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p));
|
||||
self.hover = guides;
|
||||
let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds);
|
||||
(d.last, d.pointer, d.shift) = (m, p, ev.mods.shift);
|
||||
let (m, a, b) = self.solve(
|
||||
d.angle_for(ev.mods.alt, ev.backquote),
|
||||
d.origin,
|
||||
SolveDrag { start: d.pick, p, moved, shift: ev.mods.shift, bounds: d.bounds },
|
||||
);
|
||||
(d.last, d.pointer, d.shift, d.moved) = (m, p, ev.mods.shift, moved);
|
||||
self.drag = Some(d);
|
||||
self.measure = Some((p, self.label(a, b)));
|
||||
self.readout = Some(self.readout_of(m, a, b, d.bounds));
|
||||
@@ -423,7 +454,12 @@ impl Tool for TransformTool {
|
||||
// or moves only pattern tiles, and with anchors selected, whether it acts
|
||||
// along the box or the page.
|
||||
let m = if d.anchors {
|
||||
self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0
|
||||
self.solve(
|
||||
d.angle_for(ev.mods.alt, ev.backquote),
|
||||
d.origin,
|
||||
SolveDrag { start: d.pick, p: d.pointer, moved: d.moved, shift: d.shift, bounds: d.bounds },
|
||||
)
|
||||
.0
|
||||
} else {
|
||||
d.last
|
||||
};
|
||||
@@ -445,7 +481,11 @@ impl Tool for TransformTool {
|
||||
}
|
||||
self.drop_axis();
|
||||
let copy = ev.mods.alt;
|
||||
let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds);
|
||||
let (m, _, _) = self.solve(
|
||||
d.angle_for(copy, ev.backquote),
|
||||
first,
|
||||
SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds },
|
||||
);
|
||||
vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit]
|
||||
} else {
|
||||
// A click sets the reference point; with Alt, it opens the dialog too. With the
|
||||
@@ -741,6 +781,54 @@ mod tests {
|
||||
assert!((c[0] - c[3]).abs() < 1e-9 && c[0] > 1.0);
|
||||
}
|
||||
|
||||
/// A Shift-drag along one axis scales along that axis alone, and a diagonal one scales
|
||||
/// uniformly (#6324): the drag's own direction decides, within 22.5° of an axis.
|
||||
#[test]
|
||||
fn scale_shift_follows_the_drag_direction() {
|
||||
let t = TransformTool::new(TransformKind::Scale);
|
||||
let o = Point::new(100.0, 100.0);
|
||||
let scales = |p: Point| {
|
||||
let c = t.matrix_for(o, Point::new(150.0, 140.0), p, true, Rect::ZERO).0.as_coeffs();
|
||||
(c[0], c[3])
|
||||
};
|
||||
// Sideways, a little off the level: width only.
|
||||
let (sx, sy) = scales(Point::new(200.0, 145.0));
|
||||
assert!((sx - 2.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9, "{sx} {sy}");
|
||||
// Up or down: height only.
|
||||
let (sx, sy) = scales(Point::new(148.0, 180.0));
|
||||
assert!((sx - 1.0).abs() < 1e-9 && (sy - 2.0).abs() < 1e-9, "{sx} {sy}");
|
||||
// Diagonal: both, by the same factor.
|
||||
let (sx, sy) = scales(Point::new(200.0, 180.0));
|
||||
assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}");
|
||||
// A drag that starts straight above (beside) the reference point has no width (height) to
|
||||
// scale, so a sideways (up or down) Shift-drag from there scales uniformly, as before.
|
||||
let from = |start: Point, p: Point| {
|
||||
let c = t.matrix_for(o, start, p, true, Rect::ZERO).0.as_coeffs();
|
||||
(c[0], c[3])
|
||||
};
|
||||
let (sx, sy) = from(Point::new(100.0, 150.0), Point::new(150.0, 160.0));
|
||||
assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}");
|
||||
let (sx, sy) = from(Point::new(150.0, 100.0), Point::new(160.0, 150.0));
|
||||
assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}");
|
||||
}
|
||||
|
||||
/// The axis of a Shift-drag comes from the pointer's own movement: a press near a corner
|
||||
/// snaps to it, and a level drag from there still scales the width alone.
|
||||
#[test]
|
||||
fn scale_shift_axis_follows_the_pointer_not_the_snapped_press() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = TransformTool::new(TransformKind::Scale);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 198.0, 203.0).with_mods(shift));
|
||||
let drag = t.pointer(&cx, &ev(PointerKind::Drag, 205.0, 203.0).with_mods(shift));
|
||||
let c = matrix(drag.last().expect("a preview")).as_coeffs();
|
||||
assert!((c[0] - 1.1).abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9, "the width alone: {c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_click_opens_dialog_and_alt_release_copies() {
|
||||
let (d, id) = doc_with_rect();
|
||||
|
||||
@@ -120,6 +120,7 @@ impl VectorcraftApp {
|
||||
last_ms: 0.0,
|
||||
moved: false,
|
||||
from_worker: false,
|
||||
worker_parts: false,
|
||||
reused: None,
|
||||
waits_for_still: cfg!(target_arch = "wasm32"),
|
||||
still: None,
|
||||
@@ -150,6 +151,7 @@ impl VectorcraftApp {
|
||||
carry_target: None,
|
||||
last_drag: None,
|
||||
escaped_press: false,
|
||||
host_caps_lock: None,
|
||||
committed_preview: false,
|
||||
panes: Default::default(),
|
||||
windows: crate::doc_windows::Windows::new(known),
|
||||
@@ -542,6 +544,9 @@ impl VectorcraftApp {
|
||||
if let Some(wait) = crate::panels::actions::tick_playback(self, now) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
|
||||
}
|
||||
// A `prefs.reset` run in this frame outside `Self::run` (a script's, say): the pass that follows draws the
|
||||
// reset rows.
|
||||
prefs_dialog::apply_prefs_resets(self);
|
||||
}
|
||||
|
||||
/// The canvas panel's body: the document tabs, then the canvas (a pane for each document while
|
||||
|
||||
@@ -77,7 +77,10 @@ impl VectorcraftApp {
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
self.beacon.command(id);
|
||||
let touch_workspace = self.session.prefs.touch_workspace;
|
||||
// A `prefs.reset` that ran straight on the session applies before this command can switch workspaces.
|
||||
crate::prefs_dialog::apply_prefs_resets(self);
|
||||
let result = self.run_now(id, params);
|
||||
crate::prefs_dialog::apply_prefs_resets(self);
|
||||
if id == "prefs.import" && result.is_ok() {
|
||||
crate::prefs_dialog::imported(self, touch_workspace);
|
||||
}
|
||||
|
||||
@@ -406,7 +406,33 @@ impl VectorcraftApp {
|
||||
shape_widgets: self.ui.view.shape_widgets,
|
||||
screen: self.screen_frame(),
|
||||
artboard: self.view().map_or(0, |v| v.artboard),
|
||||
..ViewInfo::default()
|
||||
precise: self.precise_cursors(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the drawing tools show precise cursors: General › Use Precise Cursors is on, or Caps Lock is
|
||||
/// (`Session::caps_lock`, which the canvas keeps at the host's state and `view.capsLock` sets). The canvas's pointer
|
||||
/// and the tools' brush tips both follow it.
|
||||
pub(crate) fn precise_cursors(&self) -> bool {
|
||||
self.session.prefs.use_precise_cursors || self.session.caps_lock
|
||||
}
|
||||
|
||||
/// Takes the host's Caps Lock state `on` when it changes: the session follows it until the next change, and a
|
||||
/// `view.capsLock` call between changes stays in place.
|
||||
pub(crate) fn follow_caps_lock(&mut self, on: bool) {
|
||||
if self.canvas.host_caps_lock == Some(on) {
|
||||
return;
|
||||
}
|
||||
let first_reading = self.canvas.host_caps_lock.is_none();
|
||||
self.canvas.host_caps_lock = Some(on);
|
||||
// A `view.capsLock` call that ran before the first reading stays in place; that reading is only the baseline.
|
||||
if first_reading && self.session.caps_lock {
|
||||
return;
|
||||
}
|
||||
if self.session.caps_lock != on
|
||||
&& let Err(err) = self.run("view.capsLock", serde_json::json!({ "on": on }))
|
||||
{
|
||||
log::error!("Could not update the Caps Lock state: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ pub struct CanvasCache {
|
||||
/// The frame shown was rendered on the worker: an interaction's frames stay there
|
||||
/// ([`canvas::show`]).
|
||||
pub from_worker: bool,
|
||||
/// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn
|
||||
/// again on this thread would not have matched the frame around it: until the worker's next
|
||||
/// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]).
|
||||
pub worker_parts: bool,
|
||||
/// The frame shown holds pixels the worker copied from its last frame, and when it was shown
|
||||
/// (seconds, egui's input time): it renders whole once it has been shown for
|
||||
/// [`canvas::STILL_SECS`] with the view unmoved.
|
||||
@@ -107,6 +111,9 @@ pub struct CanvasCache {
|
||||
/// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up,
|
||||
/// which gives back a selection tool Cmd lent.
|
||||
pub escaped_press: bool,
|
||||
/// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the
|
||||
/// next reading; `None` before the first pass.
|
||||
pub host_caps_lock: Option<bool>,
|
||||
/// A press on the canvas committed a panel field's running preview before the tool took the press, as the field's
|
||||
/// commit came first in production: the field's own commit later in the pass has nothing left to run.
|
||||
pub committed_preview: bool,
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
use craft::behavior::{CanvasView, PressPhase};
|
||||
use craft::keymap::Mods;
|
||||
use craft::ui::canvas::{
|
||||
Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass,
|
||||
Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget,
|
||||
canvas_space, tool_pass,
|
||||
};
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::runtime::env::Env;
|
||||
@@ -108,6 +109,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) {
|
||||
app.ui.home = None;
|
||||
}
|
||||
// The Home screen and the empty window show no marks: a closed document's text nodes are not kept.
|
||||
if app.session.active().is_none() {
|
||||
marks::release_text_marks(app);
|
||||
}
|
||||
let full = ui.available_rect_before_wrap();
|
||||
if crate::menus::home_showing(app) {
|
||||
// No type editor shows to lose the keys: the marked text stays as typed.
|
||||
@@ -133,6 +138,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
struct Body {
|
||||
reply: Option<ToolHostResponse>,
|
||||
context_at: Option<egui::Pos2>,
|
||||
/// The pasteboard's `context_at` answers the Menu key or Shift+F10, not a secondary click.
|
||||
context_key: bool,
|
||||
/// A view a compass or scroll bar edit made this pass.
|
||||
edited: Option<CanvasView>,
|
||||
}
|
||||
@@ -194,6 +201,11 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
};
|
||||
let pasteboard = app.session.documents().get(win.0).map(|st| artboards::pasteboard_color(app, st, app.outline_view()));
|
||||
let layers = move || bounds;
|
||||
let host_caps_lock = craft::ui::runtime::lock_keys::caps_lock(ui.ctx());
|
||||
app.follow_caps_lock(host_caps_lock);
|
||||
// The canvas reverses the state it is given while the host's Caps Lock is on: given this, it shows the precise
|
||||
// cursors the tools are told about.
|
||||
let precise = app.precise_cursors() != host_caps_lock;
|
||||
let prefs = &app.session.prefs;
|
||||
let mut canvas = Canvas::new("Document")
|
||||
.id(canvas_id(win))
|
||||
@@ -205,7 +217,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
.body_nudges(ARROWS)
|
||||
.rulers(x, y)
|
||||
.with_rulers(strips)
|
||||
.precise_cursors(prefs.use_precise_cursors);
|
||||
.precise_cursors(precise);
|
||||
if let Some(pasteboard) = pasteboard {
|
||||
canvas = canvas.pasteboard(pasteboard);
|
||||
}
|
||||
@@ -230,8 +242,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
rulers::apply(app, ui, out);
|
||||
}
|
||||
let pressed = matches!(output.press.phase, PressPhase::Down { .. });
|
||||
let Body { reply, context_at, edited } = body;
|
||||
let request = reply.as_ref().and_then(|r| r.context.as_ref()).map(|c| c.at).or(context_at);
|
||||
let Body { reply, context_at, context_key, edited } = body;
|
||||
let request = reply
|
||||
.as_ref()
|
||||
.and_then(|r| r.context.as_ref())
|
||||
.map(|c| context_menu::Request { at: c.at, key: c.source == ContextSource::Key })
|
||||
.or(context_at.map(|at| context_menu::Request { at, key: context_key }));
|
||||
let jumped = edited.is_some();
|
||||
// Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own.
|
||||
let view_now =
|
||||
@@ -265,7 +281,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body {
|
||||
let live = kind == BodyKind::Live;
|
||||
let presenting = app.ui.screen_mode == 3;
|
||||
let mut out = Body { context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), ..Body::default() };
|
||||
let background = space.background();
|
||||
let mut out = Body {
|
||||
context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)),
|
||||
context_key: background.context.is_none() && background.context_key,
|
||||
..Body::default()
|
||||
};
|
||||
grids(app, ui, space, win);
|
||||
if live {
|
||||
find_shown_tool(app, ui.ctx(), space);
|
||||
|
||||
@@ -4,25 +4,39 @@ use craft::ui::contract::{Bind, ShowContainer as _, Trigger};
|
||||
use craft::ui::menu::Menu;
|
||||
use egui::Pos2;
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::marks;
|
||||
use super::outline::{hit_with, selection_hit_at};
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// The canvas context menu (right-click, Menu key, Shift+F10). A `request` (screen points: the pointer, or
|
||||
/// the view centre for a key) selects the object under it unless it already is, then the menu lists what
|
||||
/// applies to the selection ([`crate::menus::context_items`]) at that point until it closes. The locked
|
||||
/// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked`
|
||||
/// for its Unlock submenu. With the Intertwine tool, a right-click where three or more objects of the group
|
||||
/// overlap keeps the selection and puts what it arranges in `ui.context_intertwine`
|
||||
/// ([`vectorcraft_tools::intertwine::menu_target`]). With the Artboard tool, an artboard takes the place of
|
||||
/// the object ([`crate::panels::artboards::right_click`]).
|
||||
/// A request for the canvas menu at `at` (screen points): a secondary click at the pointer, or the Menu key or
|
||||
/// Shift+F10 (`key`), which the canvas reports at the view centre.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Request {
|
||||
pub(crate) at: Pos2,
|
||||
pub(crate) key: bool,
|
||||
}
|
||||
|
||||
/// The canvas context menu (right-click, Menu key, Shift+F10). A right-click selects the object under the
|
||||
/// pointer unless it already is, then the menu lists what applies to the selection
|
||||
/// ([`crate::menus::context_items`]) at that point until it closes. The locked objects under the pointer
|
||||
/// ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` for its Unlock submenu. With
|
||||
/// the Intertwine tool, a right-click where three or more objects of the group overlap keeps the selection and
|
||||
/// puts what it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). With the
|
||||
/// Artboard tool, an artboard takes the place of the object ([`crate::panels::artboards::right_click`]). A key
|
||||
/// request keeps the selection and opens the menu at it ([`prepare_key`]).
|
||||
///
|
||||
/// Called on every pass after the canvas shows, with its response as `opener`: the menu is shown from the
|
||||
/// point stored in `ui.context_menu_at`, so a later pass without a request keeps it open.
|
||||
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option<Pos2>) {
|
||||
if let Some(at) = request {
|
||||
prepare(app, space, at);
|
||||
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option<Request>) {
|
||||
if let Some(request) = request {
|
||||
let at = if request.key {
|
||||
prepare_key(app, space)
|
||||
} else {
|
||||
prepare(app, space, request.at);
|
||||
request.at
|
||||
};
|
||||
app.ui.context_menu_at = Some(at);
|
||||
}
|
||||
let Some(at) = app.ui.context_menu_at else { return };
|
||||
@@ -69,3 +83,33 @@ fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) {
|
||||
let _ = app.run("select.set", json!({ "ids": [top.0] }));
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-shot work of a key request: the menu is for the selection as it is (the selected artboards with the
|
||||
/// Artboard tool), at the centre of the part of it in view, or at the view centre when none of it is in view.
|
||||
/// Nothing under a point is looked up: no locked objects, word or Intertwine target. Returns the menu's point.
|
||||
fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 {
|
||||
app.ui.context_locked = None;
|
||||
app.ui.context_intertwine = None;
|
||||
app.ui.context_spelling = None;
|
||||
let on_artboards = app.session.tool_id() == "artboard";
|
||||
let bounds = if on_artboards {
|
||||
app.session.active().and_then(|st| {
|
||||
let picked = crate::panels::artboards::picked(app, st.doc.artboards.len());
|
||||
picked.iter().filter_map(|&i| st.doc.artboards.get(i).map(|a| a.rect)).reduce(|a, b| a.union(b))
|
||||
})
|
||||
} else {
|
||||
app.selection_bounds()
|
||||
};
|
||||
let view = &space.view;
|
||||
let at = bounds
|
||||
.map(|b| {
|
||||
egui::Rect::from_points(&[b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)].map(|p| view.to_screen(p)))
|
||||
})
|
||||
.map(|r| r.intersect(view.rect))
|
||||
.filter(|r| !r.is_negative())
|
||||
.map_or(view.rect.center(), |r| r.center());
|
||||
if on_artboards {
|
||||
crate::panels::artboards::measure_menu(app, view.to_doc(at));
|
||||
}
|
||||
at
|
||||
}
|
||||
@@ -160,6 +160,13 @@ pub(crate) struct Marks {
|
||||
artboard_marks: Vec<BezPath>,
|
||||
}
|
||||
|
||||
/// Drops the hidden-character and spelling memos and the text nodes they hold.
|
||||
pub(crate) fn release_text_marks(app: &mut VectorcraftApp) {
|
||||
app.canvas.hidden_chars.marks.clear();
|
||||
app.canvas.spelling = SpellingMarks::default();
|
||||
app.canvas.text_nodes = TextNodes::default();
|
||||
}
|
||||
|
||||
/// The marks of one canvas pass over `view`. The memos of [`crate::CanvasCache`] are kept while their
|
||||
/// gate is on and dropped, with the text nodes they hold, when it is off.
|
||||
pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
|
||||
@@ -183,9 +190,7 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
|
||||
let fades = artboards::fades_outside_artboards(app);
|
||||
let shows_artboards = artboards::shows_artboards(app);
|
||||
let Some(st) = app.session.active() else {
|
||||
app.canvas.hidden_chars.marks.clear();
|
||||
app.canvas.spelling = SpellingMarks::default();
|
||||
app.canvas.text_nodes = TextNodes::default();
|
||||
release_text_marks(app);
|
||||
return m;
|
||||
};
|
||||
let key = (st.uid, st.revision);
|
||||
|
||||
@@ -122,6 +122,32 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() {
|
||||
assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept");
|
||||
}
|
||||
|
||||
/// Closing the last document drops the memos' text nodes on the canvas's next frame, whether it
|
||||
/// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window.
|
||||
#[test]
|
||||
fn a_canvas_frame_without_a_document_releases_the_text_nodes() {
|
||||
let ctx = crate::testing::ui_context();
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() };
|
||||
crate::testing::part_frame(app, &ctx, raw, crate::canvas::show);
|
||||
};
|
||||
for home in [true, false] {
|
||||
let mut app = app();
|
||||
app.session.execute("prefs.set", &json!({"key": "showHomeScreen", "value": home})).unwrap();
|
||||
text(&mut app, 20, 60, "one\ttwo qzxv\nthree");
|
||||
app.ui.view.hidden_chars = true;
|
||||
app.ui.view.auto_spell_check = true;
|
||||
frame(&mut app);
|
||||
assert!(app.canvas.text_nodes.list.is_some() && !app.canvas.hidden_chars.marks.is_empty(), "home {home}: the canvas keeps the memos");
|
||||
app.session.execute("file.close", &json!({})).unwrap();
|
||||
assert_eq!(crate::menus::home_showing(&app), home);
|
||||
frame(&mut app);
|
||||
assert!(app.canvas.text_nodes.list.is_none(), "home {home}: no list of the closed document's text objects is kept");
|
||||
assert!(app.canvas.hidden_chars.marks.is_empty(), "home {home}: no hidden-character marks of the closed document are kept");
|
||||
assert!(app.canvas.spelling.lines.is_empty(), "home {home}: no spelling marks of the closed document are kept");
|
||||
}
|
||||
}
|
||||
|
||||
/// `paths` small rectangles and three point type objects with hidden characters and words no
|
||||
/// dictionary knows: the first on the first layer, the second in a group on that layer and the
|
||||
/// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type
|
||||
|
||||
@@ -8,9 +8,9 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 {
|
||||
Color32::from_rgb(rgb[0], rgb[1], rgb[2])
|
||||
}
|
||||
|
||||
/// Outline of a node for highlighting (paths, compound children, area type frames, other
|
||||
/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip
|
||||
/// group's clipping path only, as [`walk_drawn`] visits it).
|
||||
/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds,
|
||||
/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures
|
||||
/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it).
|
||||
pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
walk_drawn(n, &mut |c| match &c.kind {
|
||||
@@ -27,13 +27,19 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath {
|
||||
bp.line_to(t.xf * b);
|
||||
}
|
||||
}
|
||||
} else if let Some(b) = c.geometric_bounds_with(symbols) {
|
||||
} else if let Some(q) = c.drawn_corners(symbols) {
|
||||
corners(&mut bp, q);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(_) => {
|
||||
if let Some(b) = c.geometric_bounds_with(symbols) {
|
||||
bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath());
|
||||
}
|
||||
}
|
||||
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => {
|
||||
if let Some(b) = c.geometric_bounds_with(symbols) {
|
||||
bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath());
|
||||
// A symbol instance shows its art's box, turned, skewed or in perspective with it.
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
if let Some(q) = c.drawn_corners(symbols) {
|
||||
corners(&mut bp, q);
|
||||
}
|
||||
}
|
||||
// A placed document shows its box, turned with it.
|
||||
@@ -56,6 +62,14 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath {
|
||||
bp
|
||||
}
|
||||
|
||||
/// Adds the closed outline through the four corners `q` to `bp`.
|
||||
fn corners(bp: &mut BezPath, q: [Point; 4]) {
|
||||
let [a, b, c, d] = q;
|
||||
bp.move_to(a);
|
||||
[b, c, d].into_iter().for_each(|p| bp.line_to(p));
|
||||
bp.close_path();
|
||||
}
|
||||
|
||||
/// The most points ([`overlay_points`]) the selection's outlines and anchors, and the hover
|
||||
/// highlight, are drawn for: an Image Trace of a photo selects hundreds of thousands of paths at
|
||||
/// once, and selecting all of an opened PDF can select as many type objects, images and gradient
|
||||
|
||||
@@ -48,13 +48,19 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo
|
||||
|
||||
/// The pixels of the `w`×`h` frame through `view` to render again for `doc`, when only the document
|
||||
/// changed, or placed documents' bitmaps were made, since the frame shown (its key `key` but for
|
||||
/// the revision and [`CacheKey::placed`], and its render options `opts`), which this thread
|
||||
/// rendered, and no frame is on its way from the worker: those it changed in, and those the
|
||||
/// objects showing those bitmaps' files cover (`Some(None)`: none), grown to whole eighths of the
|
||||
/// frame, as long as they are at most half of it. None: render the whole frame. Frames the worker
|
||||
/// renders stay whole: its renderer keeps the rasters of the art's effects, this thread's doesn't.
|
||||
/// What changed is measured by this thread's renderer, which drew the frame shown: it keeps what
|
||||
/// it measures (a 3D effect's art) to draw the part again.
|
||||
/// the revision and [`CacheKey::placed`], and its render options `opts`), and no frame of another
|
||||
/// document, or of this revision or a later one, is on its way from the worker: those it changed
|
||||
/// in, and those the objects showing those bitmaps' files cover (`Some(None)`: none), grown to
|
||||
/// whole eighths of the frame, as long as they are at most half of it. None: render the whole
|
||||
/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve)
|
||||
/// shows in the frame it is made in, when the part's share of the frame's last whole render time
|
||||
/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their
|
||||
/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame
|
||||
/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn
|
||||
/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]):
|
||||
/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What
|
||||
/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to
|
||||
/// draw the part again.
|
||||
pub(super) fn changed_pixels(
|
||||
app: &mut VectorcraftApp,
|
||||
key: &CacheKey,
|
||||
@@ -71,19 +77,25 @@ pub(super) fn changed_pixels(
|
||||
}
|
||||
let shown_key = app.canvas.key.as_ref()?;
|
||||
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() };
|
||||
if !same_view || app.canvas.texture.is_none() || app.canvas.from_worker || app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) {
|
||||
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some());
|
||||
// A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]).
|
||||
let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision);
|
||||
if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way {
|
||||
return None;
|
||||
}
|
||||
// The placed documents' files whose bitmaps were made since the frame shown.
|
||||
let entry = app.session.documents().iter().find(|d| d.uid as usize == key.doc).and_then(|d| app.canvas.placed_keys.get(&d.uid));
|
||||
let placed = placed_changes(entry, shown_key.placed, key.placed, doc, vectorcraft_render::placed_document::made_between)?;
|
||||
// Over a frame the worker rendered, the part's share of the whole frame's time is at most 8 ms.
|
||||
let budget = if app.canvas.from_worker { 8.0 / app.canvas.last_ms } else { 0.5 };
|
||||
match app.canvas.renderer.changed(shown, doc, opts).and(placed) {
|
||||
vectorcraft_render::Changed::Nothing => Some(None),
|
||||
vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) {
|
||||
None => Some(None),
|
||||
Some([x0, y0, x1, y1]) => {
|
||||
let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h));
|
||||
(u64::from(x1 - x0) * u64::from(y1 - y0) * 2 <= u64::from(w) * u64::from(h)).then_some(Some([x0, y0, x1, y1]))
|
||||
let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h));
|
||||
(share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1]))
|
||||
}
|
||||
},
|
||||
vectorcraft_render::Changed::Everything => None,
|
||||
@@ -122,6 +134,9 @@ pub(crate) struct WorkerFrame {
|
||||
pub(crate) moved: usize,
|
||||
/// The frame holds pixels copied from the last frame.
|
||||
pub(crate) reused: bool,
|
||||
/// The frame drew art in a way that depends on its size
|
||||
/// ([`vectorcraft_render::FrameStats::view_sized`]).
|
||||
pub(crate) view_sized: bool,
|
||||
}
|
||||
|
||||
/// Nothing but the position of the view differs between the frame `kept` and the job `job`, in
|
||||
@@ -239,6 +254,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option
|
||||
let moved = r.stats.moved;
|
||||
(img, moved)
|
||||
});
|
||||
// A copied frame's parts draw nothing that depends on the frame's size ([`composed_frame`]).
|
||||
let view_sized = !reused && r.stats.view_sized > 0;
|
||||
let keeps =
|
||||
job.may_keep && moved == 0 && r.stats.view_sized == 0 && img.pixels.len() <= MAX_KEPT_BYTES && (img.width, img.height) == (job.w, job.h);
|
||||
*kept =
|
||||
@@ -246,7 +263,7 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option
|
||||
// The kept frame stays sRGB, so the next frame's copied pixels are converted only once.
|
||||
let width = img.width;
|
||||
crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over());
|
||||
WorkerFrame { img, moved, reused }
|
||||
WorkerFrame { img, moved, reused, view_sized }
|
||||
}
|
||||
|
||||
/// Upload the art's raster directly into the canvas texture without reallocating or copying pixels;
|
||||
@@ -580,6 +597,7 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate:
|
||||
app.canvas.reused = done.reused.then(|| frame::clock(ctx));
|
||||
app.canvas.moved = done.moved > 0;
|
||||
app.canvas.from_worker = true;
|
||||
app.canvas.worker_parts = done.view_sized;
|
||||
}
|
||||
|
||||
/// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas.
|
||||
@@ -667,7 +685,13 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f
|
||||
/// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s
|
||||
/// key: only the document changed since the frame shown, in that part of it
|
||||
/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's.
|
||||
fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) {
|
||||
///
|
||||
/// Over a frame the worker rendered, a part that drew raster effects from rasters made before
|
||||
/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]),
|
||||
/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]),
|
||||
/// would not match the frame around it: it is not drawn, false is returned, and the edits after it
|
||||
/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]).
|
||||
fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool {
|
||||
let Frame { key, doc, effects, view, opts, pixel, .. } = frame;
|
||||
let t0 = monotonic_ms();
|
||||
if region.is_none() {
|
||||
@@ -679,6 +703,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
|
||||
let renderer = &mut app.canvas.renderer;
|
||||
let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view;
|
||||
let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts));
|
||||
if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) {
|
||||
app.canvas.worker_parts = true;
|
||||
return false;
|
||||
}
|
||||
let width = part.width;
|
||||
crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over());
|
||||
let color = color_image(&part);
|
||||
@@ -689,6 +717,7 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
|
||||
app.canvas.key = Some((*key).clone());
|
||||
app.canvas.shown = Some(((*doc).clone(), opts.clone()));
|
||||
app.perf.render_ms = monotonic_ms() - t0;
|
||||
true
|
||||
}
|
||||
|
||||
/// With `waits_for_still` set (the web build) and the last render slow, an edit while the view
|
||||
@@ -736,7 +765,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
|
||||
// Frames that would be slow on this thread (the last one took over 8 ms) go
|
||||
// to the worker. An interaction's frames stay on the worker once it drew the frame shown:
|
||||
// its renderer keeps the rasters of the art's effects that make those frames fast, and this
|
||||
// thread's renderer has none, so a frame fast on the worker would be slow here.
|
||||
// thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a
|
||||
// part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]).
|
||||
let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc);
|
||||
let settling = app.canvas.moved && !key.interacting;
|
||||
let staying = key.interacting && app.canvas.from_worker;
|
||||
@@ -751,11 +781,14 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
|
||||
let may_copy = app.canvas.key.as_ref() != Some(key);
|
||||
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
|
||||
let mut landed = None;
|
||||
match (&mut app.canvas.worker, heavy, changed) {
|
||||
// Only the document changed since the frame shown, in a part of it: that part is
|
||||
// rendered again, here, into the texture. `last_ms` stays the whole frame's.
|
||||
(_, _, Some(region)) => draw_changed(app, &Frame { key, doc, effects, size: (w, h), view, opts, pixel }, region),
|
||||
(Some(worker), true, None) => {
|
||||
// Only the document changed since the frame shown, in a part of it: that part is rendered
|
||||
// again, here, into the texture. `last_ms` stays the whole frame's.
|
||||
let part = Frame { key, doc, effects, size: (w, h), view, opts, pixel };
|
||||
let drawn = changed.is_some_and(|region| draw_changed(app, &part, region));
|
||||
let Frame { opts, .. } = part;
|
||||
match (&mut app.canvas.worker, heavy, drawn) {
|
||||
(_, _, true) => {}
|
||||
(Some(worker), true, false) => {
|
||||
// The worker draws the frame: what this thread's renderer made to measure the edit
|
||||
// isn't drawn here.
|
||||
app.canvas.renderer.let_go_of_measured();
|
||||
|
||||
@@ -53,6 +53,94 @@ fn a_symbol_instance_is_outlined_around_its_art() {
|
||||
assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0));
|
||||
}
|
||||
|
||||
/// The points of `bp`'s move and line elements, in order.
|
||||
fn outline_points(bp: &vectorcraft_geom::BezPath) -> Vec<Point> {
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
bp.elements()
|
||||
.iter()
|
||||
.filter_map(|el| match el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `got` are the points `want`, each within 1e-9, a last point of `got` that repeats its
|
||||
/// first left out.
|
||||
fn same_points(got: &[Point], want: &[Point]) -> bool {
|
||||
let near = |a: &Point, b: &Point| a.distance(*b) < 1e-9;
|
||||
let got = match got {
|
||||
[first, rest @ .., last] if !rest.is_empty() && near(first, last) => &got[..got.len() - 1],
|
||||
_ => got,
|
||||
};
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(a, b))
|
||||
}
|
||||
|
||||
/// Puts `n` in perspective, drawn through `h`.
|
||||
fn in_perspective(n: &mut Node, h: vectorcraft_geom::Homography) {
|
||||
let at = vectorcraft_doc::PerspectiveAttachment { projection: Some(h.to_array()), ..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0) };
|
||||
n.extras_mut().perspective = Some(Box::new(at));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() {
|
||||
// The 20 × 20 square symbol of the test above, its instance at (20, 30).
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Star"><path d="M0 0H20V20H0Z" fill="#e0a000"/></symbol></defs><use href="#Star" x="20" y="30"/></svg>"##;
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "star.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let mut inst = None;
|
||||
st.doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
inst = Some(n.clone());
|
||||
}
|
||||
});
|
||||
let inst = inst.unwrap();
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let square = [(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y));
|
||||
let placed = |a: Affine| {
|
||||
let mut n = inst.clone();
|
||||
let NodeKind::SymbolInstance { xf, .. } = &mut n.kind else { panic!("an instance") };
|
||||
*xf = a * *xf;
|
||||
let xf = *xf;
|
||||
(n, square.map(|p| xf * p))
|
||||
};
|
||||
for (case, a) in [
|
||||
("unturned", Affine::IDENTITY),
|
||||
("turned 30 degrees", Affine::rotate_about(30f64.to_radians(), Point::new(30.0, 40.0))),
|
||||
("skewed", Affine::skew(0.5, 0.0)),
|
||||
] {
|
||||
let (n, frame) = placed(a);
|
||||
let got = outline_points(&node_outline(&n, &symbols));
|
||||
assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}");
|
||||
}
|
||||
// In perspective, the frame's corners go through the projection.
|
||||
let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.004, 0.0, 1.0]]);
|
||||
let mut n = inst.clone();
|
||||
in_perspective(&mut n, h);
|
||||
let (_, flat) = placed(Affine::IDENTITY);
|
||||
let drawn = flat.map(|p| h.apply(p).unwrap());
|
||||
let got = outline_points(&node_outline(&n, &symbols));
|
||||
assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_in_perspective_is_outlined_by_its_projected_box() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "Hello world", "size": 24})).unwrap();
|
||||
let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap());
|
||||
let st = s.active().unwrap();
|
||||
let mut n = st.doc.node(id).unwrap().clone();
|
||||
let NodeKind::Text(t) = &n.kind else { panic!("type") };
|
||||
let b = t.bounds().unwrap();
|
||||
let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]);
|
||||
in_perspective(&mut n, h);
|
||||
let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap());
|
||||
let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes()));
|
||||
assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}");
|
||||
}
|
||||
|
||||
/// One headless canvas frame on an 800 × 600 window.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() };
|
||||
@@ -1613,6 +1701,89 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the
|
||||
/// frame of the move: once the press's frame arrives from the worker, every move shows the
|
||||
/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters
|
||||
/// from before their objects moved, when a part drawn here would have differed from it, or when
|
||||
/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker,
|
||||
/// and the moves after the worker's frame are drawn here again. A frame of an older revision on
|
||||
/// its way does not hold a move back.
|
||||
#[test]
|
||||
fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
for i in 0..60 {
|
||||
let (x, y) = (f64::from(i % 10) * 40.0, f64::from(i / 10) * 50.0);
|
||||
app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 30, "height": 30})).unwrap();
|
||||
}
|
||||
app.session.execute("select.none", &json!({})).unwrap();
|
||||
app.ui.view.smart_guides = false;
|
||||
app.canvas.worker_started = true; // the first frame renders on this thread
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (worker, mut side) = WorkerSide::start();
|
||||
app.canvas.worker = Some(worker);
|
||||
app.canvas.last_ms = 50.0;
|
||||
app.select_tool("pen");
|
||||
let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision);
|
||||
let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision);
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
frame(&mut app, &ctx, vec![button(at, true)]);
|
||||
assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker");
|
||||
assert!(side.render());
|
||||
let mut drag = |app: &mut VectorcraftApp| {
|
||||
at += vec2(9.0, 5.0);
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
};
|
||||
for step in 0..6 {
|
||||
drag(&mut app);
|
||||
assert_eq!(shown(&app), revision(&app), "move {step}: the curve is drawn in its own frame");
|
||||
assert!(side.jobs.try_recv().is_err(), "move {step}: nothing is queued on the worker");
|
||||
}
|
||||
for case in ["moved", "differs", "slow"] {
|
||||
match case {
|
||||
"moved" => app.canvas.moved = true,
|
||||
"differs" => app.canvas.worker_parts = true,
|
||||
_ => app.canvas.last_ms = 10_000.0,
|
||||
}
|
||||
drag(&mut app);
|
||||
assert!(shown(&app) < revision(&app), "{case}: the move is not drawn here");
|
||||
assert!(side.render(), "{case}: the move renders on the worker");
|
||||
drag(&mut app);
|
||||
assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here");
|
||||
assert!(!app.canvas.worker_parts, "{case}");
|
||||
}
|
||||
// A worker's frame that drew art in a way that depends on its size: the move after it renders
|
||||
// on the worker too.
|
||||
app.canvas.worker_parts = true;
|
||||
drag(&mut app);
|
||||
let job = side.jobs.try_iter().last().expect("the move is on the worker");
|
||||
let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job);
|
||||
side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap();
|
||||
drag(&mut app);
|
||||
assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size");
|
||||
assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker");
|
||||
drag(&mut app);
|
||||
assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here");
|
||||
// A frame on its way of an older revision: the next move is drawn here, and that frame is not
|
||||
// shown when it arrives.
|
||||
app.canvas.worker_parts = true;
|
||||
drag(&mut app);
|
||||
assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way");
|
||||
app.canvas.worker_parts = false;
|
||||
for late in [false, true] {
|
||||
if late {
|
||||
assert!(side.render());
|
||||
}
|
||||
drag(&mut app);
|
||||
assert_eq!(shown(&app), revision(&app), "drawn here, the frame on its way arrived: {late}");
|
||||
}
|
||||
frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
app.canvas.worker = None;
|
||||
}
|
||||
|
||||
/// The frame after an interaction renders without `interacting` also when the interaction
|
||||
/// leaves the document as it was (#1257): here a drag back to where it started.
|
||||
#[test]
|
||||
@@ -1777,7 +1948,9 @@ fn cached_frames_keep_their_scale() {
|
||||
// Deliver the actual replacement and verify that it replaces the cached key.
|
||||
let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let expected = job.key.clone();
|
||||
completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false }).unwrap();
|
||||
completed
|
||||
.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false, view_sized: false })
|
||||
.unwrap();
|
||||
frame(&mut app, size, new_ppp);
|
||||
assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived");
|
||||
}
|
||||
@@ -1917,7 +2090,9 @@ fn a_pan_fills_the_area() {
|
||||
// The fill arrives; the next frame draws it, and asks for no other fill.
|
||||
let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts);
|
||||
let (doc, opts) = (fill_job.doc, fill_job.opts);
|
||||
fill_completed.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false }).unwrap();
|
||||
fill_completed
|
||||
.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false })
|
||||
.unwrap();
|
||||
let (meshes, pixels) = frame(&mut app);
|
||||
assert!(fill_jobs.try_recv().is_err(), "the fill covers the canvas");
|
||||
assert_eq!(app.canvas.key.as_ref(), Some(&old), "the last frame is still shown");
|
||||
@@ -1962,11 +2137,15 @@ fn a_pan_fills_the_area() {
|
||||
app.view_mut().unwrap().center = Point::new(250.0, 150.0);
|
||||
// That fill finishes after the worker's frame: it is taken and not kept.
|
||||
let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts);
|
||||
fill_completed.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false }).unwrap();
|
||||
fill_completed
|
||||
.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false })
|
||||
.unwrap();
|
||||
// The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept.
|
||||
let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let expected = job.key.clone();
|
||||
completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false }).unwrap();
|
||||
completed
|
||||
.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false, view_sized: false })
|
||||
.unwrap();
|
||||
let (meshes, _) = frame(&mut app);
|
||||
assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame is shown");
|
||||
assert!(app.canvas.fill.is_none() && meshes.iter().all(|m| m.texture_id != fill_tex), "the fill is dropped");
|
||||
@@ -5043,6 +5222,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
ms: 2.5,
|
||||
moved: 0,
|
||||
reused: false,
|
||||
view_sized: false,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -5066,6 +5246,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
ms: 2.5,
|
||||
moved: 0,
|
||||
reused: false,
|
||||
view_sized: false,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -5088,6 +5269,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
ms: 2.5,
|
||||
moved: 0,
|
||||
reused: false,
|
||||
view_sized: false,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -5110,6 +5292,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
ms: 2.5,
|
||||
moved: 0,
|
||||
reused: false,
|
||||
view_sized: false,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -5170,7 +5353,16 @@ fn the_contour_bar_sets_corners_and_bakes() {
|
||||
/// A frame the render worker finished for `job`: white pixels of the job's size.
|
||||
fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done {
|
||||
let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] };
|
||||
crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), opts: job.opts.clone(), img, ms: 40.0, moved: 0, reused: false }
|
||||
crate::render_worker::Done {
|
||||
key: job.key.clone(),
|
||||
doc: job.doc.clone(),
|
||||
opts: job.opts.clone(),
|
||||
img,
|
||||
ms: 40.0,
|
||||
moved: 0,
|
||||
reused: false,
|
||||
view_sized: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A job for the render worker to pan over a document of `doc`: a view at 100% moved by `(dx, dy)`
|
||||
@@ -5636,7 +5828,8 @@ fn a_pan_after_the_settling_frame() {
|
||||
let job = jobs.try_recv().unwrap_or_else(|_| panic!("{name}: the canvas asks for a frame"));
|
||||
let f = render_job(&mut r, &mut kept, &job);
|
||||
assert_eq!(f.reused, copies, "{name}");
|
||||
let done = crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img: f.img, ms: 40.0, moved: f.moved, reused: f.reused };
|
||||
let (key, doc, opts, img) = (job.key, job.doc, job.opts, f.img);
|
||||
let done = crate::render_worker::Done { key, doc, opts, img, ms: 40.0, moved: f.moved, reused: f.reused, view_sized: f.view_sized };
|
||||
done_tx.send(done).unwrap();
|
||||
};
|
||||
frame(&mut app, 1.0);
|
||||
|
||||
@@ -67,3 +67,88 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() {
|
||||
assert_ne!(alt, plain, "Alt shows the Eyedropper's cursor");
|
||||
assert_eq!(shown(&mut app, egui::Modifiers::NONE), plain, "and letting go brings the bucket back");
|
||||
}
|
||||
|
||||
/// The Blob Brush's or the Eraser's tip outline at the pointer, as the canvas draws it this pass.
|
||||
fn shows_tip(app: &mut VectorcraftApp) -> bool {
|
||||
let view = app.view_info();
|
||||
app.session.overlays(view).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. }))
|
||||
}
|
||||
|
||||
/// Use Precise Cursors or Caps Lock, or both, gives the Blob Brush and the Eraser only the crosshair: the tool draws no
|
||||
/// tip outline around it. With both off, each shows its own pointer and the tip outline.
|
||||
#[test]
|
||||
fn precise_cursors_hide_the_brush_tip_outline() {
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair));
|
||||
for tool in ["blobBrush", "eraser"] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool(tool);
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0));
|
||||
for (preference, caps_lock) in [(false, false), (true, false), (false, true), (true, true), (false, false)] {
|
||||
app.run("prefs.set", serde_json::json!({"key": "usePreciseCursors", "value": preference})).unwrap();
|
||||
WindowHost::of(&ctx).set_caps_lock(Some(caps_lock));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]);
|
||||
let precise = preference || caps_lock;
|
||||
let case = format!("{tool}, Use Precise Cursors {preference}, Caps Lock {caps_lock}");
|
||||
assert_eq!(app.session.caps_lock, caps_lock, "{case}: the session takes the host's Caps Lock state");
|
||||
assert_eq!(app.view_info().precise, precise, "{case}");
|
||||
assert_eq!(shows_tip(&mut app), !precise, "{case}");
|
||||
assert_eq!(craft::ui::runtime::cursor::current(&ctx) == crosshair, precise, "{case}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `view.capsLock` sets the Caps Lock state the tools and the canvas's pointer follow until the host's state changes.
|
||||
#[test]
|
||||
fn the_caps_lock_command_gives_the_brushes_the_crosshair() {
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair));
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("blobBrush");
|
||||
let ctx = crate::testing::ui_context();
|
||||
WindowHost::of(&ctx).set_caps_lock(Some(false));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(shows_tip(&mut app));
|
||||
app.run("view.capsLock", serde_json::json!({"on": true})).unwrap();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]);
|
||||
assert!(app.session.caps_lock, "the host's unchanged state leaves the command's in place");
|
||||
assert!(!shows_tip(&mut app));
|
||||
assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair);
|
||||
app.run("view.capsLock", serde_json::json!({"on": false})).unwrap();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(shows_tip(&mut app));
|
||||
assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair);
|
||||
// With the host's Caps Lock on, the command turns it off for the tools and the canvas's pointer alike.
|
||||
WindowHost::of(&ctx).set_caps_lock(Some(true));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]);
|
||||
assert!(!shows_tip(&mut app));
|
||||
assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair);
|
||||
app.run("view.capsLock", serde_json::json!({"on": false})).unwrap();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(!app.session.caps_lock);
|
||||
assert!(shows_tip(&mut app));
|
||||
assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair);
|
||||
}
|
||||
|
||||
/// A `view.capsLock` call that runs before the first canvas pass stays in place when the host's Caps Lock is off.
|
||||
#[test]
|
||||
fn the_caps_lock_command_before_the_first_frame_stays_in_place() {
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("blobBrush");
|
||||
app.run("view.capsLock", serde_json::json!({"on": true})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
WindowHost::of(&ctx).set_caps_lock(Some(false));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.session.caps_lock, "the first host reading is only the baseline");
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.session.caps_lock);
|
||||
}
|
||||
@@ -609,9 +609,8 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
if typed && paragraph {
|
||||
ranked(ui, rank::TYPE, |ui| {
|
||||
crate::panels::paragraph::control_bar(app, ui);
|
||||
});
|
||||
// The Paragraph group ranks its link and its Align buttons as two members, so the buttons leave first.
|
||||
crate::panels::paragraph::control_bar(app, ui);
|
||||
}
|
||||
let vertical = group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some();
|
||||
if vertical {
|
||||
|
||||
@@ -34,6 +34,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let angles: Vec<Entry<usize>> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect();
|
||||
let rotation = app.view().map_or(0.0, |v| v.rotation);
|
||||
let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX);
|
||||
// An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0
|
||||
// turns the -0 of a small negative angle into 0.
|
||||
let angle = format!("{}°", rotation.round() + 0.0);
|
||||
let shows: Vec<Entry<StatusBarShow>> =
|
||||
StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect();
|
||||
let unit = app.session.general_unit();
|
||||
@@ -68,13 +71,18 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let zoom = Field::new(tl!("Zoom"))
|
||||
.side(SideLabel::new().kind(LabelKind::Hidden))
|
||||
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui));
|
||||
// PLAN: assumed CanvasView::zoom and crate::state::zoom_display_percent(zoom, print) through the scheme (cv.S4).
|
||||
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
|
||||
if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) {
|
||||
zoom_to = Some(crate::state::zoom_display_percent(view.zoom, print));
|
||||
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print));
|
||||
}
|
||||
Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| {
|
||||
// Entries are keyed by index: an angle is not a hashable value.
|
||||
rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles).look(SelectLook::Filled).show(ui).value().copied();
|
||||
rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles)
|
||||
.placeholder(angle.clone())
|
||||
.look(SelectLook::Filled)
|
||||
.show(ui)
|
||||
.value()
|
||||
.copied();
|
||||
});
|
||||
Divider::vertical().show(ui);
|
||||
for (icon, to, tip, enabled) in
|
||||
|
||||
@@ -716,6 +716,33 @@ fn the_status_bar_show_choice_is_checked_and_saved() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The status bar's Rotation box shows the view's angle: a preset angle shows its row's label, an angle between the
|
||||
/// presets shows rounded to a whole degree, and a pick from the list still turns the view.
|
||||
#[test]
|
||||
fn the_status_bar_rotation_box_shows_the_view_angle() {
|
||||
let mut bar = status_readout_app();
|
||||
let rotation = |bar: &mut Shown, angle: f64| {
|
||||
bar.app().run("view.rotate", json!({ "angle": angle })).unwrap();
|
||||
let rotation = bar.settle().find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box"));
|
||||
let value = bar.tree().value_of(rotation.node).map(str::to_owned);
|
||||
(rotation, value)
|
||||
};
|
||||
for (angle, shown) in [(17.0, "17°"), (37.4, "37°"), (-0.3, "0°"), (-122.6, "-123°")] {
|
||||
let (_, value) = rotation(&mut bar, angle);
|
||||
assert_eq!(value.as_deref(), Some(shown), "the box at {angle}°");
|
||||
assert!(bar.texts().iter().any(|t| t.text == shown), "the box draws {shown}");
|
||||
}
|
||||
let (_, value) = rotation(&mut bar, 45.0);
|
||||
assert_eq!(value.as_deref(), Some("45°"));
|
||||
// From an angle between the presets, the list still turns the view to the row picked.
|
||||
let (opener, _) = rotation(&mut bar, 17.0);
|
||||
bar.click_on(&opener).settle();
|
||||
bar.click("-45°").settle();
|
||||
assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0));
|
||||
let rotation = bar.find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box"));
|
||||
assert_eq!(bar.tree().value_of(rotation.node), Some("-45°"));
|
||||
}
|
||||
|
||||
/// While background work runs the status bar shows it where the message was, with the count of the jobs after the
|
||||
/// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress.
|
||||
#[test]
|
||||
@@ -806,6 +833,28 @@ fn set_zoom_100_matches_actual_size_with_display_print_size() {
|
||||
assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// At UI Scaling 150% the zoom field shows the zoom `view.setZoom` set, and a zoom typed into it is the zoom the view
|
||||
/// gets, as at 100%: 200% gives the view the zoom `view.setZoom` gives for 200%.
|
||||
#[test]
|
||||
fn the_zoom_field_sets_the_typed_zoom_at_any_ui_scaling() {
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap();
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.session.prefs.ui_scaling = 1.5;
|
||||
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(460.0, 260.0));
|
||||
app.run("view.setZoom", json!({"zoom": 200})).unwrap();
|
||||
let wanted = app.view().unwrap().zoom;
|
||||
app.run("view.setZoom", json!({"zoom": 100})).unwrap();
|
||||
let mut bar = crate::tests::panel_harness::Panel::new(app, super::status_bar);
|
||||
assert!((bar.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling");
|
||||
let shown = |bar: &crate::tests::panel_harness::Panel| bar.value("Zoom").unwrap_or_default();
|
||||
assert!(shown(&bar).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&bar));
|
||||
bar.type_into("Zoom", "200");
|
||||
let zoom = bar.app().view().unwrap().zoom;
|
||||
assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}");
|
||||
assert!(shown(&bar).starts_with("200"), "the field shows the typed zoom: {}", shown(&bar));
|
||||
}
|
||||
|
||||
/// Read the painted coordinates while checking that drawing never changes the source
|
||||
/// position, document, selection or either branch of its edit history.
|
||||
fn assert_status_coordinates(bar: &mut Shown, expected: Option<&str>) {
|
||||
@@ -2551,6 +2600,26 @@ fn the_type_groups_leave_the_control_bar_before_opacity_and_style() {
|
||||
assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group");
|
||||
}
|
||||
|
||||
/// With type selected, the Paragraph group's Align left, Align center and Align right buttons leave the Control bar
|
||||
/// before its Paragraph: link: some width shows the link without them, and no width shows them without the link.
|
||||
#[test]
|
||||
fn the_paragraph_link_stays_on_the_control_bar_after_its_align_buttons_leave() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
|
||||
let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({ "ids": [text] })).unwrap();
|
||||
let mut bar = control_shown(app);
|
||||
let names = ["Paragraph:", "Align left", "Align center", "Align right"];
|
||||
let seen = control_bar_widths(&mut bar, &names);
|
||||
assert!(seen.iter().any(|s| s.iter().all(|shown| *shown)), "a wide bar shows {names:?}");
|
||||
for s in &seen {
|
||||
assert!(s[1..].iter().all(|shown| *shown == s[1]), "the three Align buttons show or go together: {s:?}");
|
||||
assert!(!s[1] || s[0], "the Align buttons show only with the Paragraph: link: {s:?}");
|
||||
}
|
||||
assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Paragraph: link without the Align buttons");
|
||||
}
|
||||
|
||||
/// With area type selected, its vertical alignment buttons leave the Control bar before Opacity and the Style group,
|
||||
/// and after the Align buttons that follow them, with the Character and Paragraph groups shown and with both off.
|
||||
#[test]
|
||||
|
||||
@@ -39,10 +39,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new(
|
||||
|
||||
/// Where the glyphs that start at the box's upper left have their tip, in the icon's 24-unit box.
|
||||
const TIP: Vec2 = Vec2::new(2.0, 2.0);
|
||||
/// The tip of the glyphs that point down-left (a pipette, a brush, a bucket, a knife).
|
||||
const LOWER_LEFT: Vec2 = Vec2::new(2.0, 22.0);
|
||||
/// The pipette's sampling tip, at the box's lower left.
|
||||
const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0);
|
||||
/// The middle of the Anchor Point caret's square.
|
||||
const CARET: Vec2 = Vec2::new(12.0, 6.0);
|
||||
/// The blade's point of the knife, at the box's upper right.
|
||||
const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0);
|
||||
/// The bottom of the drop below the paint bucket.
|
||||
const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0);
|
||||
/// The bottom of the drop beside the Live Paint diamond.
|
||||
const DIAMOND_DROP: Vec2 = Vec2::new(20.0, 18.0);
|
||||
/// The middle of the brush's bristle edge, at its lower left.
|
||||
const BRISTLE_TIP: Vec2 = Vec2::new(6.0, 17.5);
|
||||
|
||||
fn system(icon: CursorIcon) -> cb::Cursor {
|
||||
cb::Cursor::System(icon)
|
||||
@@ -111,7 +119,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor {
|
||||
Cursor::HandGrab => system(CursorIcon::Grabbing),
|
||||
Cursor::ZoomIn => PaintedCursor::zoom(false).into(),
|
||||
Cursor::ZoomOut => PaintedCursor::zoom(true).into(),
|
||||
Cursor::Eyedropper => tool("pipette", LOWER_LEFT, None),
|
||||
Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None),
|
||||
Cursor::NotAllowed => system(CursorIcon::NotAllowed),
|
||||
Cursor::Busy => system(CursorIcon::Progress),
|
||||
Cursor::AddStop => badged(CursorBadge::Add),
|
||||
@@ -136,10 +144,10 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor {
|
||||
Cursor::PencilContinue => marked(Crosshair, "cursor-mark-line-rising"),
|
||||
// Only the centre: the tool draws the tip's outline round it, at the zoom.
|
||||
Cursor::BlobBrush | Cursor::Eraser => PaintedCursor::circle(1.25).into(),
|
||||
Cursor::Knife => tool("dc-knife", LOWER_LEFT, None),
|
||||
Cursor::LivePaintBucket => tool("paint-bucket", LOWER_LEFT, None),
|
||||
Cursor::LivePaintBucketFace => tool("dc-live-bucket", LOWER_LEFT, None),
|
||||
Cursor::LivePaintBucketEdge => tool("paintbrush", LOWER_LEFT, None),
|
||||
Cursor::Knife => tool("dc-knife", BLADE_POINT, None),
|
||||
Cursor::LivePaintBucket => tool("paint-bucket", BUCKET_DROP, None),
|
||||
Cursor::LivePaintBucketFace => tool("dc-live-bucket", DIAMOND_DROP, None),
|
||||
Cursor::LivePaintBucketEdge => tool("paintbrush", BRISTLE_TIP, None),
|
||||
Cursor::LivePaintSelectFace => marked(Arrow, "cursor-mark-square"),
|
||||
Cursor::LivePaintSelectEdge => marked(Arrow, "cursor-mark-edge"),
|
||||
Cursor::LivePaintSelectOutside => marked(Arrow, "x"),
|
||||
|
||||
@@ -10,6 +10,41 @@ fn every_tool_cursors_hotspot_lies_inside_its_icon_box() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A click lands where the glyph points: in every painted tool cursor's image, the icon's own
|
||||
/// mark color (not only its halo) covers the hotspot pixel or one next to it.
|
||||
#[test]
|
||||
fn every_tool_cursors_hotspot_is_on_its_glyph() {
|
||||
use craft::ui::primitives::{painted_image, register_app_icons};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::rgba_color;
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
register_app_icons(&CURSOR_ICONS);
|
||||
let mut missed = Vec::new();
|
||||
crate::testing::ui_context()
|
||||
.run_ui(Default::default(), |ui| {
|
||||
let env = Env::of(ui);
|
||||
let ink = rgba_color(env.tokens.tokens().color.overlay.stroke);
|
||||
let near_ink = |px: &[u8]| px[3] == 255 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8);
|
||||
for c in GLYPHS {
|
||||
let cb::Cursor::Painted(painted @ PaintedCursor::Tool { .. }) = tool_cursor(c) else { continue };
|
||||
let Some(image) = painted_image(&env, &painted, 2.0) else {
|
||||
missed.push(format!("{c:?}: no image"));
|
||||
continue;
|
||||
};
|
||||
let ([w, h], [hx, hy]) = (image.size.map(usize::from), image.hotspot.map(usize::from));
|
||||
let on_glyph = (hy.saturating_sub(1)..=(hy + 1).min(h - 1))
|
||||
.flat_map(|y| (hx.saturating_sub(1)..=(hx + 1).min(w - 1)).map(move |x| (y * w + x) * 4))
|
||||
.any(|i| near_ink(&image.rgba[i..i + 4]));
|
||||
if !on_glyph {
|
||||
missed.push(format!("{c:?}"));
|
||||
}
|
||||
}
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
assert!(missed.is_empty(), "hotspots off their glyphs: {missed:?}");
|
||||
}
|
||||
|
||||
/// A `cursor-` icon name a cursor uses must be in the set the host registers.
|
||||
#[test]
|
||||
fn every_cursor_icon_the_app_names_is_in_its_set() {
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::behavior::dock::{Action, DockEdge};
|
||||
use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target};
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
|
||||
use craft::ui::dialog::DialogResult;
|
||||
@@ -345,6 +345,133 @@ fn set_shown(app: &mut VectorcraftApp, name: &str, show: Option<bool>) -> Result
|
||||
Ok(show)
|
||||
}
|
||||
|
||||
// ---------- docking and floating ----------
|
||||
|
||||
/// The window edge and column index from that edge where `panel` docks; none while it floats or is hidden.
|
||||
fn docked_at(ui: &UiState, panel: &str) -> Option<(DockEdge, usize)> {
|
||||
panel_docking::column_of(panel_docking::layout_of(ui), panel).and_then(|(slot, _)| slot)
|
||||
}
|
||||
|
||||
/// The window edge toolbar panel `panel` docks at: while docked, its edge; while it floats or is
|
||||
/// hidden, the edge of the docked panel the dock records it left; else the left edge.
|
||||
fn last_edge(ui: &UiState, panel: &str) -> DockEdge {
|
||||
let ws = &ui.dock_workspace;
|
||||
let left = ws.floated().iter().chain(ws.hidden()).find(|(p, _)| p == panel).and_then(|(_, at)| at.anchor.as_deref());
|
||||
docked_at(ui, panel).or_else(|| left.and_then(|anchor| docked_at(ui, anchor))).map_or(DockEdge::Start, |(edge, _)| edge)
|
||||
}
|
||||
|
||||
/// The `side` param's name of `edge`.
|
||||
fn side_name(edge: DockEdge) -> &'static str {
|
||||
if edge == DockEdge::End { "right" } else { "left" }
|
||||
}
|
||||
|
||||
/// Where toolbar `bar` is: `{toolbar, floating, side, order, pos}`, as `window.toolbar.dock` and
|
||||
/// `window.toolbar.float` return it.
|
||||
fn placement(app: &VectorcraftApp, bar: &str) -> Result<Value, String> {
|
||||
let b = find(&app.ui, bar).ok_or_else(|| format!("no toolbar named `{bar}`"))?;
|
||||
let panel = panel_id(b.id);
|
||||
let docked = docked_at(&app.ui, &panel);
|
||||
let pos = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| [w.rect.min.x, w.rect.min.y]);
|
||||
Ok(json!({
|
||||
"toolbar": b.name,
|
||||
"floating": docked.is_none(),
|
||||
"side": side_name(last_edge(&app.ui, &panel)),
|
||||
"order": docked.map(|(_, n)| n),
|
||||
"pos": pos,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `window.toolbar.dock`: docks the toolbar named `name` as a column of the dock on the `side` edge
|
||||
/// (omitted: [`last_edge`]), at column `order` from the window edge (omitted: the innermost, or where it
|
||||
/// is when it docks at that edge already). Bad params are errors and change nothing.
|
||||
fn dock(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?;
|
||||
let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?;
|
||||
let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone());
|
||||
let edge = match p.get("side") {
|
||||
None | Some(Value::Null) => last_edge(&app.ui, &panel),
|
||||
// `Start` and `End`, as panels take them, too.
|
||||
Some(Value::String(s)) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => DockEdge::Start,
|
||||
Some(Value::String(s)) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => DockEdge::End,
|
||||
Some(Value::String(s)) => return Err(format!("side is left or right, not `{s}`")),
|
||||
Some(v) => return Err(format!("side is left or right, not `{v}`")),
|
||||
};
|
||||
// A panel of each other column of that edge's dock, from the window edge inwards.
|
||||
let others: Vec<String> = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), edge)
|
||||
.iter()
|
||||
.filter(|c| !c.panels().any(|q| *q == panel))
|
||||
.filter_map(|c| c.panels().next().cloned())
|
||||
.collect();
|
||||
let order = match p.get("order") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => match v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|&n| n <= others.len()) {
|
||||
Some(n) => Some(n),
|
||||
None => return Err(format!("order is a whole number from 0 to {}, not `{v}`", others.len())),
|
||||
},
|
||||
};
|
||||
let here = docked_at(&app.ui, &panel).filter(|(e, _)| *e == edge).map(|(_, n)| n);
|
||||
if here.is_none() {
|
||||
// A new innermost column of that edge's dock; a hidden toolbar shows.
|
||||
let hidden = !panel_docking::layout_of(&app.ui).contains(&panel);
|
||||
app.run("window.panel.dock", json!({ "panel": panel, "side": if edge == DockEdge::End { "End" } else { "Start" } }))?;
|
||||
shown_again(app, id, hidden);
|
||||
}
|
||||
let now = docked_at(&app.ui, &panel).map(|(_, n)| n);
|
||||
if let Some(n) = order.filter(|n| Some(*n) != now) {
|
||||
let to = match others.get(n) {
|
||||
Some(anchor) => Target::at(anchor.clone(), DockPlacement::column(false)),
|
||||
None => match others.last() {
|
||||
Some(last) => Target::at(last.clone(), DockPlacement::column(true)),
|
||||
None => return placement(app, &name),
|
||||
},
|
||||
};
|
||||
let ctx = app.ui_ctx.clone();
|
||||
panel_docking::apply(app, ctx.as_ref(), vec![Action::move_panel(panel, to)])?;
|
||||
}
|
||||
// A toolbar where it was asked to go shows too, which ends a Tab hide.
|
||||
panel_docking::show_panels(app);
|
||||
placement(app, &name)
|
||||
}
|
||||
|
||||
/// `window.toolbar.float`: floats the toolbar named `name` with its top-left corner at `x`, `y` in
|
||||
/// window points (both or neither; neither: where the dock floats a panel, and a floating toolbar
|
||||
/// stays where it is).
|
||||
fn float(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?;
|
||||
let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?;
|
||||
let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone());
|
||||
let coord = |k: &str| match p.get(k) {
|
||||
None | Some(Value::Null) => Some(None),
|
||||
Some(v) => v.as_f64().filter(|f| f.abs() <= 1e6).map(|f| Some(f as f32)),
|
||||
};
|
||||
let at = match (coord("x"), coord("y")) {
|
||||
(Some(Some(x)), Some(Some(y))) => Some(pos2(x, y)),
|
||||
(Some(None), Some(None)) => None,
|
||||
_ => return Err("x and y must both be numbers from -1000000 to 1000000".into()),
|
||||
};
|
||||
let window = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| w.rect);
|
||||
let hidden = !panel_docking::layout_of(&app.ui).contains(&panel);
|
||||
match (at, window) {
|
||||
(Some(at), _) => panel_docking::place_floating(app, &panel, at, window.map_or(0.0, |r| r.width()))?,
|
||||
(None, None) => {
|
||||
app.run("window.panel.float", json!({ "panel": panel }))?;
|
||||
}
|
||||
(None, Some(_)) => {}
|
||||
}
|
||||
shown_again(app, id, hidden);
|
||||
// A toolbar floating already shows too, which ends a Tab hide.
|
||||
panel_docking::show_panels(app);
|
||||
placement(app, &name)
|
||||
}
|
||||
|
||||
/// After a command showed toolbar `id`, which was `hidden`, the groups torn off it show again, as
|
||||
/// Show Toolbar brings them back.
|
||||
fn shown_again(app: &mut VectorcraftApp, id: u32, hidden: bool) {
|
||||
if hidden && panel_docking::layout_of(&app.ui).contains(&panel_id(id)) {
|
||||
crate::toolbar::strips_follow(app, &Owner::Toolbar(id), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens New Toolbar: a name box whose OK is held while the name is refused, the refusal shown under
|
||||
/// the row.
|
||||
fn open_new(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
@@ -464,6 +591,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?;
|
||||
delete(app, name).map(|_| Value::Null)
|
||||
})(),
|
||||
"window.toolbar.dock" => dock(app, p),
|
||||
"window.toolbar.float" => float(app, p),
|
||||
"window.toolbar.list" => {
|
||||
let layout = panel_docking::layout_of(&app.ui);
|
||||
Ok(json!(
|
||||
@@ -474,7 +603,6 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
let panel = panel_id(b.id);
|
||||
let place = panel_docking::column_of(layout, &panel);
|
||||
let docked = place.as_ref().and_then(|(at, _)| at.as_ref());
|
||||
let side = if matches!(docked, Some((DockEdge::End, _))) { "right" } else { "left" };
|
||||
let double = place.as_ref().is_some_and(|(_, column)| column.steps == Some(2));
|
||||
json!({
|
||||
"name": b.name,
|
||||
@@ -482,7 +610,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
"double": double,
|
||||
"slots": b.slots,
|
||||
"floating": docked.is_none(),
|
||||
"side": side,
|
||||
"side": side_name(last_edge(&app.ui, &panel)),
|
||||
"order": docked.map(|(_, n)| *n),
|
||||
})
|
||||
})
|
||||
@@ -723,8 +851,9 @@ mod tests {
|
||||
|
||||
/// What hides a toolbar: Window › Tools hides the Tools panel alone and a toolbar still shows, with
|
||||
/// the drawer open for it; a strip torn off a toolbar follows the toolbar and one torn off Tools
|
||||
/// follows Tools; Tab hides the toolbar and a second Tab shows it; making, copying or showing a
|
||||
/// toolbar while Tab hides the panels shows them again, with the other toolbars as they were
|
||||
/// follows Tools; Tab hides the toolbar and a second Tab shows it; making, copying, showing,
|
||||
/// docking or floating a toolbar while Tab hides the panels shows them again, with the other
|
||||
/// toolbars as they were
|
||||
/// (VectorCraft's own rule: showing one does not turn the others off).
|
||||
#[test]
|
||||
fn a_new_toolbar_shows_without_the_tools_panel_until_tab() {
|
||||
@@ -759,11 +888,15 @@ mod tests {
|
||||
assert!(!panel_docking::panels_shown(&app));
|
||||
tab(&mut app, &ctx, 2.0);
|
||||
assert!(panel_docking::panels_shown(&app) && shown(&app, "Mine"));
|
||||
// Made, copied or shown while Tab hides the panels, a toolbar ends the hide.
|
||||
// Made, copied, shown, docked or floated while Tab hides the panels, a toolbar ends the hide.
|
||||
for (k, (command, params)) in [
|
||||
("window.toolbar.new", json!({"name": "Other"})),
|
||||
("window.toolbar.duplicate", json!({"name": "Mine"})),
|
||||
("window.toolbar.custom", json!({"name": "Other", "show": true})),
|
||||
// Floating already, docked, then docked where it is already.
|
||||
("window.toolbar.float", json!({"name": "Mine"})),
|
||||
("window.toolbar.dock", json!({"name": "Mine"})),
|
||||
("window.toolbar.dock", json!({"name": "Mine"})),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -978,4 +1111,122 @@ mod tests {
|
||||
assert_eq!(many.len(), MAX);
|
||||
assert_eq!(many.iter().map(|b| b.id).collect::<BTreeSet<_>>().len(), MAX, "every toolbar has an id of its own");
|
||||
}
|
||||
|
||||
/// A hidden toolbar that `window.toolbar.dock` or `window.toolbar.float` shows brings back the
|
||||
/// group torn off it, as Show Toolbar does.
|
||||
#[test]
|
||||
fn docking_or_floating_a_hidden_toolbar_brings_back_its_torn_off_group() {
|
||||
let mut app = app();
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap();
|
||||
app.run("toolbar.addTool", json!({"tool": "curvature", "toolbar": "Mine", "slot": 0, "place": "group"})).unwrap();
|
||||
app.run("window.floatTools", json!({"tool": "pen", "toolbar": "Mine"})).unwrap();
|
||||
let id = find(&app.ui, "Mine").unwrap().id;
|
||||
let strip = strip_id(&Owner::Toolbar(id), "pen");
|
||||
let on = |app: &VectorcraftApp| panel_docking::layout_of(&app.ui).contains(&strip);
|
||||
assert!(on(&app));
|
||||
for (command, params) in [
|
||||
("window.toolbar.dock", json!({"name": "Mine"})),
|
||||
("window.toolbar.float", json!({"name": "Mine"})),
|
||||
("window.toolbar.float", json!({"name": "Mine", "x": 40, "y": 50})),
|
||||
] {
|
||||
app.run("window.toolbar.custom", json!({"name": "Mine", "show": false})).unwrap();
|
||||
assert!(!on(&app), "the strip hides with its toolbar");
|
||||
app.run(command, params.clone()).unwrap();
|
||||
assert!(panel_docking::layout_of(&app.ui).contains(&panel_id(id)), "{command} {params} shows the toolbar");
|
||||
assert!(on(&app), "{command} {params} brings the strip back");
|
||||
}
|
||||
}
|
||||
|
||||
/// The dock layout, to compare.
|
||||
fn layout(app: &VectorcraftApp) -> Value {
|
||||
serde_json::to_value(panel_docking::layout_of(&app.ui)).unwrap()
|
||||
}
|
||||
|
||||
/// Where the toolbar named `name` docks: its edge and column from that edge (none: floating).
|
||||
fn dock_place(app: &VectorcraftApp, name: &str) -> Option<(DockEdge, usize)> {
|
||||
docked_at(&app.ui, &panel_id(find(&app.ui, name).unwrap().id))
|
||||
}
|
||||
|
||||
/// `window.toolbar.dock` docks a toolbar at an edge, innermost or at the column asked for, and
|
||||
/// `window.toolbar.float` floats it, at x, y when given; bad params and a toolbar already where
|
||||
/// it is asked to go change nothing, and `window.toolbar.list` reports the same places.
|
||||
#[test]
|
||||
fn toolbars_dock_and_float_by_their_commands() {
|
||||
let mut app = app();
|
||||
for name in ["A", "B", "C"] {
|
||||
app.run("window.toolbar.new", json!({ "name": name })).unwrap();
|
||||
}
|
||||
assert_eq!(dock_place(&app, "A"), None, "New Toolbar floats");
|
||||
let undo = app.session.doc().map_or(0, |d| d.history.undo.len());
|
||||
let r = app.run("window.toolbar.dock", json!({"name": "a"})).unwrap();
|
||||
assert_eq!((&r["toolbar"], &r["floating"], &r["side"], &r["pos"]), (&json!("A"), &json!(false), &json!("left"), &Value::Null));
|
||||
let (edge, a) = dock_place(&app, "A").unwrap();
|
||||
assert_eq!(edge, DockEdge::Start);
|
||||
assert_eq!(r["order"], json!(a));
|
||||
// Each one docked after it goes inside it; one asked to go at A's column goes outside it.
|
||||
app.run("window.toolbar.dock", json!({"name": "B", "side": "left"})).unwrap();
|
||||
let b = dock_place(&app, "B").unwrap().1;
|
||||
assert!(b > dock_place(&app, "A").unwrap().1, "B docks inside A");
|
||||
let at_a = dock_place(&app, "A").unwrap().1;
|
||||
app.run("window.toolbar.dock", json!({"name": "C", "side": "start", "order": at_a})).unwrap();
|
||||
let [c, a, b] = ["C", "A", "B"].map(|n| dock_place(&app, n).unwrap().1);
|
||||
assert!(c < a && a < b, "C goes outside A: {c} {a} {b}");
|
||||
// Docked again at the edge it docks at, with no column asked for, nothing changes.
|
||||
let before = layout(&app);
|
||||
app.run("window.toolbar.dock", json!({"name": "A"})).unwrap();
|
||||
app.run("window.toolbar.dock", json!({"name": "A", "side": "left", "order": a})).unwrap();
|
||||
assert_eq!(layout(&app), before);
|
||||
// Bad params are errors and change nothing.
|
||||
let columns = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), DockEdge::Start).len();
|
||||
for p in [
|
||||
json!({"name": "A", "side": "top"}),
|
||||
json!({"name": "A", "side": 1}),
|
||||
json!({"name": "A", "order": columns}),
|
||||
json!({"name": "A", "order": -1}),
|
||||
json!({"name": "A", "order": 0.5}),
|
||||
json!({"name": "A", "order": "1"}),
|
||||
json!({"name": "Nope"}),
|
||||
json!({}),
|
||||
] {
|
||||
assert!(app.run("window.toolbar.dock", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
for p in [
|
||||
json!({"name": "A", "x": 10}),
|
||||
json!({"name": "A", "x": 1e7, "y": 0}),
|
||||
json!({"name": "A", "x": "1", "y": 2}),
|
||||
json!({"name": "Nope"}),
|
||||
json!({}),
|
||||
] {
|
||||
assert!(app.run("window.toolbar.float", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(layout(&app), before);
|
||||
// The innermost column asked for: A moves inside B.
|
||||
app.run("window.toolbar.dock", json!({"name": "A", "order": columns - 1})).unwrap();
|
||||
assert!(dock_place(&app, "A").unwrap().1 > dock_place(&app, "B").unwrap().1);
|
||||
// At the right edge.
|
||||
let r = app.run("window.toolbar.dock", json!({"name": "A", "side": "RIGHT"})).unwrap();
|
||||
assert_eq!(r["side"], json!("right"));
|
||||
assert_eq!(dock_place(&app, "A").map(|(e, _)| e), Some(DockEdge::End));
|
||||
// Floated, it remembers the right edge, and docks there again.
|
||||
let r = app.run("window.toolbar.float", json!({"name": "A"})).unwrap();
|
||||
assert_eq!((&r["floating"], &r["side"], &r["order"]), (&json!(true), &json!("right"), &Value::Null));
|
||||
assert!(r["pos"].is_array());
|
||||
let listed = app.run("window.toolbar.list", json!({})).unwrap();
|
||||
let a_row = listed.as_array().unwrap().iter().find(|t| t["name"] == "A").unwrap().clone();
|
||||
assert_eq!((&a_row["floating"], &a_row["side"]), (&json!(true), &json!("right")));
|
||||
// Floating already, with no x, y: it stays where it is.
|
||||
let before = layout(&app);
|
||||
app.run("window.toolbar.float", json!({"name": "A"})).unwrap();
|
||||
assert_eq!(layout(&app), before);
|
||||
let r = app.run("window.toolbar.float", json!({"name": "A", "x": 300, "y": 200})).unwrap();
|
||||
assert_eq!(r["pos"], json!([300.0, 200.0]));
|
||||
assert_eq!(app.run("window.toolbar.dock", json!({"name": "A"})).unwrap()["side"], json!("right"));
|
||||
// A hidden toolbar shows where it is docked or floated to.
|
||||
app.run("window.toolbar.custom", json!({"name": "B", "show": false})).unwrap();
|
||||
app.run("window.toolbar.float", json!({"name": "B", "x": 50, "y": 60})).unwrap();
|
||||
assert!(panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel_id(find(&app.ui, "B").unwrap().id)).is_some());
|
||||
// Neither command records an undo step.
|
||||
assert_eq!(app.session.doc().map_or(0, |d| d.history.undo.len()), undo);
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let key = "group";
|
||||
let group = match p.get(key) {
|
||||
Some(Value::String(g)) => g.clone(),
|
||||
None | Some(Value::Null) => crate::panels::swatches::sole_selected_group(app).ok_or("missing `group`")?,
|
||||
None | Some(Value::Null) => {
|
||||
crate::panels::swatches::sole_selected_group(app).ok_or("select a color group in the Swatches panel, or pass group")?
|
||||
}
|
||||
Some(_) => return Err(format!("`{key}` must be a string")),
|
||||
};
|
||||
let st = app.session.active().ok_or("no document open")?;
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! `artboard.setProps {index, color}`.
|
||||
//!
|
||||
//! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog
|
||||
//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's
|
||||
//! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor
|
||||
//! Artwork shows the library that Limit to Library limits to. The OK for a Save for Web colour table cell shifts the cell's
|
||||
//! colour in the table instead ([`super::save_for_web::take_palette_pick`]).
|
||||
//!
|
||||
//! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`,
|
||||
@@ -104,7 +105,7 @@ pub(crate) fn open_picker(app: &VectorcraftApp) -> Option<DialogId> {
|
||||
|
||||
/// The document's swatches and the swatch libraries as the picker's Color Swatches view: solid
|
||||
/// colours only, tints as their colour.
|
||||
fn swatch_view(app: &VectorcraftApp) -> PickerSwatches {
|
||||
pub(crate) fn swatch_view(app: &VectorcraftApp) -> PickerSwatches {
|
||||
let solid = |swatches: &[vectorcraft_color::Swatch]| -> Vec<(Label, Srgba)> {
|
||||
swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect()
|
||||
};
|
||||
@@ -124,6 +125,15 @@ fn swatch_view(app: &VectorcraftApp) -> PickerSwatches {
|
||||
PickerSwatches::new(libraries, tl!("Open a document to see its swatches."))
|
||||
}
|
||||
|
||||
/// The index in [`swatch_view`]'s libraries of the library a Limit to Library key names
|
||||
/// (`"document"` or a library id); `None` when the view does not list it.
|
||||
fn library_index(app: &VectorcraftApp, limit: &str) -> Option<usize> {
|
||||
if limit == swatchlib::DOCUMENT_SWATCHES {
|
||||
return Some(0);
|
||||
}
|
||||
colour_libraries(app).iter().position(|lib| lib.id == limit).map(|i| i + 1)
|
||||
}
|
||||
|
||||
/// The working CMYK profile as the picker's CMYK converter, so its CMYK fields follow the document's
|
||||
/// inks; `None` (the picker's built-in coated CMYK) when the profile can't link to sRGB.
|
||||
fn working_cmyk() -> Option<CmykConverter> {
|
||||
@@ -204,8 +214,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
while let Some((parent, request)) = dialogs.with(|h| h.take_color_request()) {
|
||||
let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 });
|
||||
let key = request.key.clone();
|
||||
let child = ColorPickerDialog::from_request(request).eyedropper(true).add_to_swatches(false).gamut(gamut(app)).working_rgb(WorkingRgb);
|
||||
let library = super::recolor::limit_to(&dialogs, parent).and_then(|limit| library_index(app, &limit));
|
||||
let child = ColorPickerDialog::from_request(request)
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
let id = dialogs.with(|h| h.open_child(child, parent));
|
||||
// Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to.
|
||||
if let Some(i) = library
|
||||
&& let Err(e) = dialogs.with(|h| h.set_json_field(ctx, id, "library", json!(i)))
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() });
|
||||
}
|
||||
let busy = app.screen_pick.busy();
|
||||
|
||||
@@ -115,21 +115,51 @@ fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
|
||||
if let Some(k) = f.text("kind") {
|
||||
p["kind"] = json!(k);
|
||||
}
|
||||
if let Some(mut r) = f.number("radius") {
|
||||
if relative {
|
||||
let id = NodeId(json_field(f, "id").as_u64().unwrap_or(0));
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) {
|
||||
let corners: BTreeSet<usize> = serde_json::from_value(json_field(f, "corners")).unwrap_or_default();
|
||||
if let Some(k) = corners.iter().next() {
|
||||
let max = lc.corner(*k).map(|c| c.max_radius()).unwrap_or(0.0);
|
||||
r = (r / 100.0).clamp(0.0, 1.0) * max;
|
||||
}
|
||||
let Some(r) = f.number("radius") else {
|
||||
return app.run("object.setLiveShape", p).map(|_| ());
|
||||
};
|
||||
if !relative {
|
||||
p["radius"] = json!(r);
|
||||
return app.run("object.setLiveShape", p).map(|_| ());
|
||||
}
|
||||
// Relative: the percentage is of each corner's own maximum, so corners with different
|
||||
// maximums (a star's points and its inner corners) get different lengths. Corners of the
|
||||
// same length share one `object.setLiveShape`; several run as one undo step.
|
||||
let id = NodeId(json_field(f, "id").as_u64().unwrap_or(0));
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let mut lengths: Vec<(f64, Vec<usize>)> = vec![];
|
||||
if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) {
|
||||
let corners: BTreeSet<usize> = serde_json::from_value(json_field(f, "corners")).unwrap_or_default();
|
||||
for k in corners {
|
||||
let len = (r / 100.0).clamp(0.0, 1.0) * lc.corner(k).map(|c| c.max_radius()).unwrap_or(0.0);
|
||||
match lengths.iter_mut().find(|(l, _)| (*l - len).abs() < 1e-9) {
|
||||
Some((_, ks)) => ks.push(k),
|
||||
None => lengths.push((len, vec![k])),
|
||||
}
|
||||
}
|
||||
p["radius"] = json!(r);
|
||||
}
|
||||
app.run("object.setLiveShape", p).map(|_| ())
|
||||
match &lengths[..] {
|
||||
[] => {
|
||||
p["radius"] = json!(r);
|
||||
app.run("object.setLiveShape", p).map(|_| ())
|
||||
}
|
||||
[(len, _)] => {
|
||||
p["radius"] = json!(len);
|
||||
app.run("object.setLiveShape", p).map(|_| ())
|
||||
}
|
||||
_ => {
|
||||
let commands: Vec<Value> = lengths
|
||||
.iter()
|
||||
.map(|(len, ks)| {
|
||||
let mut step = p.clone();
|
||||
step["corners"] = json!(ks);
|
||||
step["radius"] = json!(len);
|
||||
json!({"command": "object.setLiveShape", "params": step})
|
||||
})
|
||||
.collect();
|
||||
app.run("command.batch", json!({"label": "Live Shape", "commands": commands})).map(|_| ())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -277,4 +307,38 @@ mod tests {
|
||||
assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. })));
|
||||
assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0));
|
||||
}
|
||||
|
||||
/// Relative rounding gives each corner the percentage of its own maximum: a star's point and
|
||||
/// the inner corner beside it differ, and OK rounds both as one undo step.
|
||||
#[test]
|
||||
fn relative_radius_is_a_percentage_of_each_corners_own_maximum() {
|
||||
let (mut app, _) = app();
|
||||
let id = app.run("shape.star", json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("object.setLiveShape", json!({"id": id, "radius": 1})).unwrap();
|
||||
let lc = |app: &VectorcraftApp| {
|
||||
let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone();
|
||||
let c = LiveCorners::of(&n).unwrap();
|
||||
(c.radii_relative(), c.radius(0), c.radius(1), c.corner(0).unwrap().max_radius(), c.corner(1).unwrap().max_radius())
|
||||
};
|
||||
let (_, _, _, max0, max1) = lc(&app);
|
||||
assert!((max0 - max1).abs() > 1.0, "the corners' maximums differ: {max0} and {max1}");
|
||||
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let n = steps(&app);
|
||||
app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap();
|
||||
set(&app, "radii", json!("relative"));
|
||||
set(&app, "radius", json!(50));
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
let (relative, f0, f1, _, _) = lc(&app);
|
||||
assert!(relative);
|
||||
assert!((f0 - 0.5).abs() < 1e-9 && (f1 - 0.5).abs() < 1e-9, "stored fractions: {f0} and {f1}");
|
||||
assert_eq!(steps(&app), n + 1, "one undo step");
|
||||
// The same values again change nothing and record no step.
|
||||
app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap();
|
||||
set(&app, "radius", json!(50));
|
||||
confirm(&mut app);
|
||||
assert_eq!(steps(&app), n + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert!(!lc(&app).0, "undo brings back absolute radii");
|
||||
}
|
||||
}
|
||||
@@ -718,7 +718,8 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
&& let Some(dialogs) = app.dialogs()
|
||||
{
|
||||
let key = request.key.clone();
|
||||
let picker = dialogs.with(|host| host.open(ColorPickerDialog::from_request(request)));
|
||||
let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app));
|
||||
let picker = dialogs.with(|host| host.open(picker));
|
||||
app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) });
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
|
||||
@@ -561,6 +561,21 @@ mod tests {
|
||||
assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value");
|
||||
}
|
||||
|
||||
/// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size
|
||||
/// with Relative, a share of the object's size, shows one.
|
||||
#[test]
|
||||
fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() {
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
let app = app();
|
||||
for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] {
|
||||
let cx = EffectCx::new(&app, effect, false);
|
||||
let rows = super::super::effect_rows::distort(&cx, &DialogFields::new());
|
||||
let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit);
|
||||
assert_eq!(unit(key), Some(None), "{effect} {key}");
|
||||
assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lists the dialogs draw hold the values the effect's parameter documentation lists, in
|
||||
/// its order; Rasterize's Color Model names the document's mode first.
|
||||
#[test]
|
||||
|
||||
@@ -36,7 +36,12 @@ fn data_label(text: &str) -> Label {
|
||||
|
||||
/// A whole-number slider row over `0..=100` percent.
|
||||
fn percent_range(key: &str, label: Label, default: f64) -> Param {
|
||||
Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent)
|
||||
count_range(key, label, default).unit(UnitKind::Percent)
|
||||
}
|
||||
|
||||
/// A whole-number slider row over `0..=100` with no unit after the number.
|
||||
fn count_range(key: &str, label: Label, default: f64) -> Param {
|
||||
Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0)
|
||||
}
|
||||
|
||||
/// The row of `key` for either unit of a Relative/Absolute pair: a share of the object's size, or a distance in the
|
||||
@@ -82,7 +87,7 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec<Param> {
|
||||
pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
|
||||
let roughen = cx.id == "distort.roughen";
|
||||
// PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it
|
||||
let second = if roughen { percent_range("detail", lbl!("Detail:"), 10.0) } else { percent_range("ridges", lbl!("Ridges per segment:"), 4.0) };
|
||||
let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) };
|
||||
let points: Vec<(String, Label)> = choices(&cx.id, "points")
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
|
||||
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user