diff --git a/Cargo.lock b/Cargo.lock
index 14d5119325..0417aba6f0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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"
diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs
index 8c510f5dbd..8f1b50dd58 100644
--- a/apps/vectorcraft/src/prefs_dir.rs
+++ b/apps/vectorcraft/src/prefs_dir.rs
@@ -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);
}
}
diff --git a/assets/icons/dc-cap-butt.svg b/assets/icons/dc-cap-butt.svg
index bf39a170a6..dee85e09a0 100644
--- a/assets/icons/dc-cap-butt.svg
+++ b/assets/icons/dc-cap-butt.svg
@@ -1 +1 @@
-
+
diff --git a/assets/icons/dc-cap-round.svg b/assets/icons/dc-cap-round.svg
index 06af9d07ea..bcf2e976c4 100644
--- a/assets/icons/dc-cap-round.svg
+++ b/assets/icons/dc-cap-round.svg
@@ -1 +1 @@
-
+
diff --git a/assets/icons/dc-cap-square.svg b/assets/icons/dc-cap-square.svg
index 4a82a10d9a..5fcb2e3c5d 100644
--- a/assets/icons/dc-cap-square.svg
+++ b/assets/icons/dc-cap-square.svg
@@ -1 +1 @@
-
+
diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs
index 909fedd04d..b5c993a865 100644
--- a/crates/doc/src/document_guides.rs
+++ b/crates/doc/src/document_guides.rs
@@ -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 {
+ 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.
diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs
index ab347529e6..d1322de74f 100644
--- a/crates/doc/src/perspective.rs
+++ b/crates/doc/src/perspective.rs
@@ -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) {
diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs
index 25a2451968..073a0f2efd 100644
--- a/crates/doc/src/text.rs
+++ b/crates/doc/src/text.rs
@@ -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,
diff --git a/crates/doc/src/text/attr_ranges.rs b/crates/doc/src/text/attr_ranges.rs
new file mode 100644
index 0000000000..bce0098ac2
--- /dev/null
+++ b/crates/doc/src/text/attr_ranges.rs
@@ -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 = 0.1..=1296.0;
+/// Leading ([`CharStyle::leading`]) other than Auto, in points.
+pub const LEADING: RangeInclusive = 0.1..=5000.0;
+/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
+pub const CHAR_SCALE: RangeInclusive = 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 = -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 = -360.0..=360.0;
+/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
+pub const CHAR_MITER_LIMIT: RangeInclusive = 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(())
+ }
+}
diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs
index b3cff3aa47..9371947565 100644
--- a/crates/doc/src/text/tests.rs
+++ b/crates/doc/src/text/tests.rs
@@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() {
assert_eq!(serde_json::from_str::(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::*;
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 7e6028b045..6732c973f4 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -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.
diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs
index 6c16893aba..135c9d964e 100644
--- a/crates/engine/src/cmd/addons/pathtools/shape.rs
+++ b/crates/engine/src/cmd/addons/pathtools/shape.rs
@@ -33,7 +33,7 @@ pub fn specs() -> Vec {
"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
),
diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs
index 5ab9da102c..426f374a5c 100644
--- a/crates/engine/src/cmd/buildcmds.rs
+++ b/crates/engine/src/cmd/buildcmds.rs
@@ -77,7 +77,7 @@ pub fn specs() -> Vec {
"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
),
diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs
index 063c25f4b2..a7827e135b 100644
--- a/crates/engine/src/cmd/colorcmds.rs
+++ b/crates/engine/src/cmd/colorcmds.rs
@@ -141,7 +141,7 @@ pub fn specs() -> Vec {
"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
diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs
index 54e7a3bbf4..42ee145c94 100644
--- a/crates/engine/src/cmd/colormgmt.rs
+++ b/crates/engine/src/cmd/colormgmt.rs
@@ -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, 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, 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, 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 {
}
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:?}");
+ }
+}
diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs
index 0c03b1ea11..5e756623f0 100644
--- a/crates/engine/src/cmd/fileio/commands.rs
+++ b/crates/engine/src/cmd/fileio/commands.rs
@@ -36,7 +36,7 @@ pub fn specs() -> Vec {
"Export Document",
[],
None,
- "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, 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-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path",
+ "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, 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-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path",
has_doc,
export::export
),
diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs
index 23b7a1c13f..b308f874ab 100644
--- a/crates/engine/src/cmd/fileio/encode.rs
+++ b/crates/engine/src/cmd/fileio/encode.rs
@@ -256,6 +256,11 @@ struct RasterOptions {
dither: Option,
dither_amount: Option,
transparency: Option,
+ /// 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,
+ /// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is.
+ transparency_dither_amount: Option,
matte: Option,
lossless: Option,
lzw: Option,
@@ -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> {
let checked = |key: &str, n: f64| {
@@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result {
{
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 {
diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs
index 0272bab874..2d6e459ece 100644
--- a/crates/engine/src/cmd/fileio/formats.rs
+++ b/crates/engine/src/cmd/fileio/formats.rs
@@ -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,
];
diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs
index 250fc98f9b..2b3613984a 100644
--- a/crates/engine/src/cmd/fileio/load.rs
+++ b/crates/engine/src/cmd/fileio/load.rs
@@ -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);
diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs
index e54aababec..d27166e5da 100644
--- a/crates/engine/src/cmd/fileio/tests_palette.rs
+++ b/crates/engine/src/cmd/fileio/tests_palette.rs
@@ -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 = 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");
diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs
index 68c681b0a5..527957f234 100644
--- a/crates/engine/src/cmd/object/transform.rs
+++ b/crates/engine/src/cmd/object/transform.rs
@@ -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)
})?
diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs
index 13f7051223..77cdfdcb7d 100644
--- a/crates/engine/src/cmd/panelcmds.rs
+++ b/crates/engine/src/cmd/panelcmds.rs
@@ -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] = [
diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs
index 2859ecf1c0..525cef316a 100644
--- a/crates/engine/src/cmd/path.rs
+++ b/crates/engine/src/cmd/path.rs
@@ -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> {
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) })
})
}
diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs
index 6f8ce2256f..b93db7b8a2 100644
--- a/crates/engine/src/cmd/plugin.rs
+++ b/crates/engine/src/cmd/plugin.rs
@@ -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 {
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| -> Result<(Document, Vec)> {
+ 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 = 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::>();
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 {
+ 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 {
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
};
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 {
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 {
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 {
"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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., 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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., 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 {
"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 {
"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 {
"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
),
diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs
index aa8a90d407..27d38e158f 100644
--- a/crates/engine/src/cmd/prefscmds.rs
+++ b/crates/engine/src/cmd/prefscmds.rs
@@ -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> {
+ 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 {
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 {
}
fn reset(s: &mut Session, p: &Value) -> Result {
- 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) }))
}
diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs
index cde1456589..1d3c8f7d7b 100644
--- a/crates/engine/src/cmd/textstyles.rs
+++ b/crates/engine/src/cmd/textstyles.rs
@@ -157,13 +157,13 @@ pub fn specs() -> Vec {
"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, kept: Option<&Map>, 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 =
+ 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 {
/// 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, Vec) {
- 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, Vec) {
"warichuGap",
"warichuScale",
"stroke_width",
+ "stroke_miter_limit",
+ "stroke_dash",
+ "small_caps",
+ "fontAxes",
"left_indent",
"right_indent",
"first_line_indent",
diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs
index e8f57aa14f..c0a92a20e3 100644
--- a/crates/engine/src/cmd/textstyles/tests.rs
+++ b/crates/engine/src/cmd/textstyles/tests.rs
@@ -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"]);
}
diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs
index ea6647b7a4..db1a641f2f 100644
--- a/crates/engine/src/cmd/variablecmds.rs
+++ b/crates/engine/src/cmd/variablecmds.rs
@@ -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 {
fn unbind(s: &mut Session, p: &Value) -> Result {
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;
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 3813cb344b..7e97c28337 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -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>,
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
tool_panic: Option,
/// How many times switching or closing documents, or replacing the active one, has started the
diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs
index 39c740cb2e..9c137c96bd 100644
--- a/crates/engine/src/script/dom.rs
+++ b/crates/engine/src/script/dom.rs
@@ -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
+///
+/// lists, and `Fit Artboard to artwork bounds` is the one
+/// 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
+/// 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![d],
};
let mut ids: Vec = Vec::with_capacity(list.len());
+ let mut seen: HashSet = 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 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)),
));
diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs
index ec4461d698..dbb24b641a 100644
--- a/crates/engine/src/script/mod.rs
+++ b/crates/engine/src/script/mod.rs
@@ -1650,24 +1650,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) {
/// `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>) {
- 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>) {
+ 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 {
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 {
+ 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());
diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs
index 6a323aadd3..6c1a0b408c 100644
--- a/crates/engine/src/session/documents.rs
+++ b/crates/engine/src/session/documents.rs
@@ -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,
diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs
index a48795b910..29cd6f1bea 100644
--- a/crates/engine/src/store.rs
+++ b/crates/engine/src/store.rs
@@ -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-/` 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 = 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 = 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 = 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 = BTreeMap::new();
let named = |written: &BTreeMap, 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 = 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| 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 {
+ 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,
/// The entries it can't use (a permission it doesn't know, an invalid id), as they were.
other: Vec,
+ /// 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,
+ grants: Vec,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ mac: Option,
+}
+
+/// 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 {
+ let entries: Vec = 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 {
+ match serde_json::from_slice::(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, 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) -> Option> {
+ let fits = |bytes: &Vec| 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 {
+ 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 {
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 {
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::>(&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::(&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::(&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::(entry.clone()) {
@@ -2106,11 +2386,19 @@ fn read_grants(dir: &Path) -> Result {
}
/// 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 {
- 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) -> BTreeMap {
+ 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()
diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs
new file mode 100644
index 0000000000..151cd4055d
--- /dev/null
+++ b/crates/engine/src/store/grant_keys.rs
@@ -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 {
+ 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 {
+ 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, 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 {
+ 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, 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 >,
+ generations: Mutex>,
+}
+
+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, 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 , 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 >> = Mutex::new(None);
+
+/// The one memory store of [`keep_grant_keys_in_memory`].
+static SHARED_MEMORY: LazyLock> = 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>> = 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>) {
+ *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 = 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> {
+ #[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));
+ 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, 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 {
+ 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 {
+ 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> {
+ use hmac::Mac;
+ let mut mac = hmac::Hmac::::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 {
+ 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 {
+ 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> {
+ 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>>,
+ /// How a connection is made ([`connect`]).
+ connect: fn() -> Result, 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, 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 {
+ self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e))
+ }
+
+ fn key_entry(&self) -> Result {
+ self.entry(Self::ACCOUNT)
+ }
+
+ /// The key the system's key store keeps, read from it.
+ fn stored(&self, entry: &keyring_core::Entry) -> Result, 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 {
+ 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, keyring_core::Error> {
+ #[cfg(target_os = "macos")]
+ {
+ let store: Arc = apple_native_keyring_store::keychain::Store::new()?;
+ Ok(store)
+ }
+ #[cfg(windows)]
+ {
+ let store: Arc = 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 = 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, 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 {
+ 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, 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 {
+ #[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> = 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, keyring_core::Error> {
+ if TRIES.fetch_add(1, Ordering::SeqCst) == 0 {
+ return Err(keyring_core::Error::NoDefaultStore);
+ }
+ let store: Arc = MOCK.clone();
+ Ok(store)
+ }
+
+ /// Connections asked for from [`restarting`].
+ static RESTARTS: AtomicUsize = AtomicUsize::new(0);
+ /// The store [`restarting`] connects to first.
+ static BEFORE: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
+ /// The store [`restarting`] connects to on every later try.
+ static AFTER: LazyLock> = 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, keyring_core::Error> {
+ let store: Arc = 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 {
+ 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(&::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");
+ }
+}
diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs
index 39f496557d..9b0147174e 100644
--- a/crates/engine/src/tests/colorcontrast.rs
+++ b/crates/engine/src/tests/colorcontrast.rs
@@ -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();
diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs
index d6e82af05b..b0b511e661 100644
--- a/crates/engine/src/tests/fill_area.rs
+++ b/crates/engine/src/tests/fill_area.rs
@@ -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 = 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 = 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.
diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs
index d922be19dd..6f7fe9c581 100644
--- a/crates/engine/src/tests/menucmds.rs
+++ b/crates/engine/src/tests/menucmds.rs
@@ -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 {
+ 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 = 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 = 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();
diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs
index 0a255fb3a3..e47eb8377a 100644
--- a/crates/engine/src/tests/plugins.rs
+++ b/crates/engine/src/tests/plugins.rs
@@ -2714,7 +2714,8 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
let approved = asking(id, r#"["doc.read"]"#, &empty);
std::fs::write(&later, &approved).unwrap();
let grants = folder.0.join("grants.json");
- let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap();
+ let entry =
+ |hash: String| crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string());
std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap();
let held = HeldLoad::new(later.clone());
let mut s = session();
@@ -2731,7 +2732,7 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
s.finish_plugin_loads();
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
assert!(vectorcraft_plugins::registry::remove(id));
- let listed: Vec = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap();
+ let listed = crate::store::grant_entries(&std::fs::read(&grants).unwrap());
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed");
assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::>(), [json!(sha256_hex(&other))], "{listed:?}");
}
@@ -2750,7 +2751,11 @@ fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() {
let approved = asking(id, r#"["doc.read"]"#, &empty);
std::fs::write(&later, &approved).unwrap();
let grants = folder.0.join("grants.json");
- std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
+ std::fs::write(
+ &grants,
+ crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()),
+ )
+ .unwrap();
// The first write removes the grant; the second, which puts it back, finds a folder where the
// file goes and fails.
let blocked = grants.clone();
@@ -2785,7 +2790,11 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() {
let approved = asking(id, r#"["doc.read"]"#, &empty);
std::fs::write(&later, &approved).unwrap();
let grants = folder.0.join("grants.json");
- std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
+ std::fs::write(
+ &grants,
+ crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()),
+ )
+ .unwrap();
// The first write removes the grant; while the second puts it back, the id is installed
// elsewhere.
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
@@ -2800,7 +2809,14 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() {
assert!(vectorcraft_plugins::registry::remove(id));
// A grants file that went away holds no grant; one still there must read as a list.
let listed: Vec = match std::fs::read(&grants) {
- Ok(b) => serde_json::from_slice(&b).unwrap(),
+ Ok(b) => match serde_json::from_slice::(&b).unwrap() {
+ Value::Array(entries) => entries,
+ Value::Object(mut file) => match file.remove("grants") {
+ Some(Value::Array(entries)) => entries,
+ other => panic!("the grants file holds no list: {other:?}"),
+ },
+ other => panic!("the grants file holds no list: {other:?}"),
+ },
Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![],
Err(e) => panic!("the grants file could not be read: {e}"),
};
@@ -3077,11 +3093,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
let other_wasm = asking(other, r#"["doc.read"]"#, &empty);
let grants = folder.0.join("grants.json");
let ids = || -> Vec {
- serde_json::from_slice::>(&std::fs::read(&grants).unwrap())
- .unwrap()
- .iter()
- .map(|e| e["id"].as_str().unwrap().to_string())
- .collect()
+ crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].as_str().unwrap().to_string()).collect()
};
let mut s = session();
s.attach_plugin_store(folder.0.clone());
@@ -3101,7 +3113,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
// A grant the store already holds for an id whose stored module lists no permissions.
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]});
- std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap();
+ std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([entry, other_entry]).to_string())).unwrap();
vectorcraft_plugins::registry::remove(id);
let mut third = session();
third.attach_plugin_store(folder.0.clone());
@@ -3111,7 +3123,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
// So does an entry this version can't read, and a grant held only by the process.
let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]});
- std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap();
+ std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, other_entry]).to_string())).unwrap();
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant {
id: id.into(),
@@ -3171,8 +3183,8 @@ fn a_grant_that_cannot_be_removed_keeps_the_stored_module() {
let file = s.stored_plugin_file(id).unwrap();
// An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which
// makes the rewritten file larger than the 1 MiB that is read.
- let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0);
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
run(&mut s, "plugin.install", replace.clone());
@@ -3219,8 +3231,8 @@ fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() {
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
let file = s.stored_plugin_file(id).unwrap();
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0);
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
crate::store::PUT_BACK_FAILS.set(true);
@@ -3252,7 +3264,7 @@ fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() {
let file = s.stored_plugin_file(id).unwrap();
let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]});
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
@@ -3285,8 +3297,8 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() {
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
let file = s.stored_plugin_file(id).unwrap();
- let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0);
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
std::fs::remove_file(&file).unwrap();
@@ -3315,13 +3327,14 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() {
let needs_approval = json!({"dataBase64": approved_data});
let grants = folder.0.join("grants.json");
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
- let recorded = serde_json::to_vec(&json!([entry])).unwrap();
+ let list = json!([entry]).to_string();
+ let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list);
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
vectorcraft_plugins::registry::remove(id);
let mut next = session();
@@ -3331,12 +3344,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() {
let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
assert!(refused.contains("doc.read"), "{refused}");
- std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
+ std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap();
next.attach_plugin_store(elsewhere.0.clone());
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
// A load that can rewrite the file forgets the grant, and the store has nothing ignored again.
- std::fs::write(&grants, &recorded).unwrap();
+ std::fs::write(&grants, recorded(&folder.0)).unwrap();
next.attach_plugin_store(folder.0.clone());
assert!(!grants.exists(), "the load removes the grant");
@@ -3346,7 +3359,7 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() {
let mut third = session();
third.attach_plugin_store(folder.0.clone());
std::fs::remove_dir(&grants).unwrap();
- std::fs::write(&grants, &recorded).unwrap();
+ std::fs::write(&grants, recorded(&folder.0)).unwrap();
assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count");
// Attaching the same store again, with no stored module to try the removal for, keeps it out.
@@ -3383,8 +3396,9 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() {
let needs_approval = json!({"dataBase64": approved_data});
let grants = folder.0.join("grants.json");
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
- let recorded = serde_json::to_vec(&json!([entry])).unwrap();
- std::fs::write(&grants, &recorded).unwrap();
+ let list = json!([entry]).to_string();
+ let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list);
+ std::fs::write(&grants, recorded(&folder.0)).unwrap();
let mut first = session();
first.attach_plugin_store(folder.0.clone());
let inside = folder.0.join("inside");
@@ -3394,7 +3408,7 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() {
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
let file = first.stored_plugin_file(id).unwrap();
@@ -3414,13 +3428,13 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() {
later.attach_plugin_store(folder.0.clone());
assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it");
- std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
+ std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap();
other.attach_plugin_store(elsewhere.0.clone());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
other.attach_plugin_store(folder.0.clone());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't");
- std::fs::write(&grants, &recorded).unwrap();
+ std::fs::write(&grants, recorded(&folder.0)).unwrap();
assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
for s in [&mut first, &mut other, &mut later] {
assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
@@ -3478,7 +3492,7 @@ fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() {
let mut other = session();
other.attach_plugin_store(alias);
std::fs::create_dir(&dir).unwrap();
- std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
+ std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(&dir, &json!([entry]).to_string())).unwrap();
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
first.ignore_stored_grant(id, first.grant_writes());
@@ -3519,11 +3533,10 @@ fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() {
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
- let recorded = serde_json::to_vec(&json!([entry])).unwrap();
let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins"));
for dir in [&old, &new] {
std::fs::create_dir(dir).unwrap();
- std::fs::write(dir.join("grants.json"), &recorded).unwrap();
+ std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(dir, &json!([entry]).to_string())).unwrap();
}
std::os::unix::fs::symlink(&old, &link).unwrap();
let mut linked = session();
@@ -3590,8 +3603,8 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() {
let file = s.stored_plugin_file(id).unwrap();
let recorded = std::fs::read(&grants).unwrap();
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0);
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let entry = crate::store::grant_entries(&recorded).remove(0);
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
let data = crate::store::plugin_data_dir(&folder.0, id);
std::fs::create_dir_all(&data).unwrap();
@@ -3649,8 +3662,8 @@ fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() {
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
let recorded = std::fs::read(&grants).unwrap();
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0);
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let entry = crate::store::grant_entries(&recorded).remove(0);
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
let data = crate::store::plugin_data_dir(&folder.0, id);
let settings = br#"{"zoom":"aGVsbG8="}"#;
@@ -3781,8 +3794,9 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() {
}
/// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module
-/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant
-/// still covers, and the grant is left as it was.
+/// that asks for no permissions doesn't stay in the store: the store gets back the earlier module,
+/// and the file is left as it was. The generation was raised before the removal and stays raised, so
+/// the file left in place grants nothing and the module asks again.
#[test]
fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() {
let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants");
@@ -3802,8 +3816,8 @@ fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() {
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
crate::store::GRANTS_DELETE_FAILS.set(false);
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
- assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was");
- assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module");
+ assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file stays as it was");
+ assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the file left in place grants nothing");
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(!grants.exists(), "a removal that can delete the file forgets the grant");
@@ -3891,7 +3905,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() {
// A malformed hash is no wildcard, even for the module on disk.
let upper = sha256_hex(&first).to_uppercase();
for hash in ["", "00", upper.as_str()] {
- std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap()).unwrap();
+ std::fs::write(
+ &grants,
+ crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()),
+ )
+ .unwrap();
assert!(!starts(), "hash {hash:?}");
}
@@ -3951,11 +3969,11 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() {
// The grants file is full: the new grant, which is longer, doesn't fit.
let cap = 1 << 20;
- let mut entries: Vec = serde_json::from_slice(&recorded).unwrap();
+ let mut entries: Vec = crate::store::grant_entries(&recorded);
entries.push(json!({"id": "", "pad": ""}));
- let room = cap - serde_json::to_vec(&entries).unwrap().len();
+ let room = cap - crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()).len();
*entries.last_mut().unwrap() = json!({"id": "", "pad": "x".repeat(room)});
- let full = serde_json::to_vec(&entries).unwrap();
+ let full = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap());
assert_eq!(full.len(), cap);
std::fs::write(&grants, &full).unwrap();
run(&mut s, "plugin.install", update.clone());
@@ -4195,7 +4213,7 @@ fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) {
/// The ids `grants.json` in `dir` holds grants for, and the hash of each.
fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap {
- let entries: Vec = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap();
+ let entries = crate::store::grant_entries(&std::fs::read(dir.join("grants.json")).unwrap());
entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect()
}
@@ -4497,8 +4515,8 @@ fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off(
assert!(!disabled.is_empty());
let file = s.stored_plugin_file(id).unwrap();
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
- let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
- let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
+ let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0);
+ let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")));
std::fs::write(&grants, &full).unwrap();
crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true);
@@ -4718,6 +4736,118 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
}
+/// A filter at `api` 3 that lists type, images and symbol instances in `writes` changes a type
+/// object's characters, an image's transform and opacity and the symbol an instance shows, as one
+/// undo step that undo takes back and redo gives again, and the changes are kept when the document
+/// is saved and opened. An echo records no undo step; a refused write, and a write by a filter that
+/// lists the kinds in `inputs` alone, leave the document and the history as they were.
+#[test]
+fn a_filter_that_writes_type_images_and_instances_is_one_undo_step() {
+ use std::sync::Arc;
+ use vectorcraft_doc::{Appearance, Node, NodeKind, Symbol};
+ use vectorcraft_geom::Affine;
+ let mut s = session();
+ let r = rect(&mut s, 10.0, "#ff0000");
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap());
+ let (mut image, mut inst) = (NodeId(0), NodeId(0));
+ s.edit("Set up", |d, _| {
+ for name in ["Sun", "Moon"] {
+ let art = Arc::new(Node::path(d.alloc_id(), triangle(), Appearance::default()));
+ d.symbols.push(Symbol { name: name.into(), art, dynamic: false });
+ }
+ let layer = d.layers[0].id;
+ let im = vectorcraft_doc::ImageObject {
+ key: "none".into(),
+ width: 4,
+ height: 2,
+ xf: Affine::translate((100.0, 20.0)),
+ link: None,
+ placement: Default::default(),
+ pixels: None,
+ };
+ let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
+ image = d.insert(Some(layer), usize::MAX, n).unwrap();
+ let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Sun".into(), xf: Affine::translate((200.0, 20.0)) });
+ inst = d.insert(Some(layer), usize::MAX, n).unwrap();
+ Ok(())
+ })
+ .unwrap();
+ let manifest = |id: &str, writes: &str| {
+ format!(
+ r#"{{"id":"{id}","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"]{writes}}}"#
+ )
+ };
+ let all = r#","writes":["type","image","symbolInstance"]"#;
+ let put = |s: &mut Session, src: &str| {
+ let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
+ run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true}))
+ };
+ let p = |id: &str| json!({"id": id, "ids": [r.0, t.0, image.0, inst.0]});
+ let style = match &node(&s, t).kind {
+ NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(),
+ _ => panic!("type"),
+ };
+ let edits = json!({"objects": [
+ {"id": r.0},
+ {"id": t.0, "text": {"runs": [{"text": "Bye now", "style": style}]}},
+ {"id": image.0, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.25},
+ {"id": inst.0, "symbolId": "Moon"},
+ ]});
+ let writer = "test.engine.writes.revise";
+ let listed = put(&mut s, &tpl::returning(&manifest(writer, all), &edits.to_string()));
+ assert_eq!((&listed["api"], &listed["writes"]), (&json!(3), &json!(["type", "image", "symbolInstance"])));
+ let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
+ assert_eq!(run(&mut s, "plugin.run", p(writer))["ids"], json!([r.0, t.0, image.0, inst.0]));
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
+ let check = |d: &vectorcraft_doc::Document| {
+ let NodeKind::Text(x) = &d.node(t).unwrap().kind else { panic!("type") };
+ assert_eq!(x.plain_text(), "Bye now");
+ let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("image") };
+ assert_eq!((im.xf, d.node(image).unwrap().opacity), (Affine::new([2.0, 0.0, 0.0, 2.0, 50.0, 60.0]), 0.25));
+ assert!(
+ matches!(&d.node(inst).unwrap().kind, NodeKind::SymbolInstance { symbol, xf } if symbol == "Moon" && *xf == Affine::translate((200.0, 20.0)))
+ );
+ };
+ let after = s.doc().unwrap().doc.clone();
+ check(&after);
+ assert!(matches!(&after.node(t).unwrap().kind, NodeKind::Text(x) if x.cached_bounds.is_some()), "the type is laid out again");
+ assert_eq!(s.doc().unwrap().selection.objects, [r, t, image, inst]);
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc().unwrap().doc.layers, before.layers);
+ run(&mut s, "edit.redo", json!({}));
+ assert_eq!(s.doc().unwrap().doc.layers, after.layers);
+ check(&vectorcraft_format::load(&vectorcraft_format::save(&after, false)).unwrap());
+ // An echo changes nothing and records no undo step.
+ let echo = "test.engine.writes.echo";
+ put(&mut s, &tpl::module(&manifest(echo, all), tpl::ECHO, "", 1));
+ let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
+ run(&mut s, "plugin.run", p(echo));
+ assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "an echo records no undo step");
+ // Refused writes leave the document and the history as they were, also when a valid change
+ // comes before the refused one.
+ let bad = "test.engine.writes.bad";
+ let retyped = json!({"id": t.0, "text": {"runs": [{"text": "Hello again", "style": style}]}});
+ for (writes, output, says) in [
+ (
+ all,
+ json!({"objects": [{"id": r.0}, retyped, {"id": image.0}, {"id": inst.0, "symbolId": "Nowhere"}]}),
+ format!("objects[3] (id {}).symbolId: 'Nowhere' is not a symbol in this document", inst.0),
+ ),
+ (
+ all,
+ json!({"objects": [{"id": r.0}, {"id": t.0}, {"id": image.0, "opacity": 1.5}, {"id": inst.0}]}),
+ format!("objects[2] (id {}).opacity: must be a number from 0 to 1", image.0),
+ ),
+ ("", edits.clone(), format!("objects[1] (id {}): read-only field 'text.kind' changed", t.0)),
+ ] {
+ put(&mut s, &tpl::returning(&manifest(bad, writes), &output.to_string()));
+ let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
+ let e = s.execute("plugin.run", &p(bad)).unwrap_err().to_string();
+ assert!(e.contains(&says), "{says}: {e}");
+ assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "{output}");
+ }
+}
+
/// The manifest of a filter at `api` 3 with id `id` that asks for the document information
/// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or
/// nothing).
@@ -4880,6 +5010,73 @@ fn the_document_context_is_capped_and_its_rows_cost_instructions() {
refused(&mut s);
}
+/// A filter that writes type, run while typing is in progress: the plug-in is given the typed
+/// text, so an echo keeps it, with Real-time Drawing on and off. An output that is refused leaves
+/// the document and the history as they were; with Real-time Drawing on the typing stays in
+/// progress, and off it is kept as its own step before the plug-in is given its input.
+#[test]
+fn a_filter_that_writes_type_is_given_the_typing_in_progress() {
+ use vectorcraft_doc::NodeKind;
+ use vectorcraft_tools::{PointerEvent, PointerKind};
+ let manifest = |id: &str| {
+ format!(
+ r#"{{"id":"{id}","name":"Retype","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"#
+ )
+ };
+ let put = |s: &mut Session, src: &str| {
+ let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
+ run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true}))
+ };
+ let plain = |s: &Session, t: NodeId| match &node(s, t).kind {
+ NodeKind::Text(x) => x.plain_text(),
+ _ => panic!("type"),
+ };
+ let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>();
+ let typing = |real_time: bool| {
+ let mut s = session();
+ s.prefs.real_time_drawing = real_time;
+ let v = ViewInfo::default();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20}))["id"].as_u64().unwrap());
+ s.select_tool("type", v).unwrap();
+ let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap();
+ for k in [PointerKind::Down, PointerKind::Up] {
+ s.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap();
+ }
+ s.tool_text("B", v).unwrap();
+ assert_eq!(plain(&s, t), if real_time { "AB" } else { "A" }, "real time {real_time}");
+ (s, t)
+ };
+ let bang = "test.engine.writes.typing.bang";
+ let bad = "test.engine.writes.typing.bad";
+ for real_time in [false, true] {
+ // The plug-in adds "!" to the text it is given: "AB" or, given only "A", "A".
+ let (mut s, t) = typing(real_time);
+ let style = match &node(&s, t).kind {
+ NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(),
+ _ => panic!("type"),
+ };
+ let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string();
+ put(&mut s, &tpl::when_given_else(&manifest(bang), tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!")));
+ run(&mut s, "plugin.run", json!({"id": bang, "ids": [t.0]}));
+ assert_eq!(plain(&s, t), "AB!", "real time {real_time}: the plug-in is given the typed text");
+ let steps = labels(&s);
+ assert_eq!(steps[steps.len() - 2..], ["Typing", "Retype"], "real time {real_time}");
+
+ let (mut s, t) = typing(real_time);
+ put(&mut s, &tpl::returning(&manifest(bad), &json!({"objects": [{"id": t.0, "transform": [0, 0, 0, 0, 0, 0]}]}).to_string()));
+ let undo = labels(&s);
+ let e = s.execute("plugin.run", &json!({"id": bad, "ids": [t.0]})).unwrap_err().to_string();
+ assert!(e.contains("transform: flattens the object to a line or a point"), "{e}");
+ assert_eq!(plain(&s, t), "AB", "real time {real_time}");
+ if real_time {
+ assert_eq!(labels(&s), undo, "the refused output leaves the history as it was");
+ assert!(s.in_interaction(), "and the typing in progress");
+ } else {
+ assert_eq!(labels(&s)[undo.len()..], ["Typing"], "only the typing is kept");
+ }
+ }
+}
+
/// A run past its memory budget fails before the plug-in starts, with the document and undo
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
@@ -5121,7 +5318,7 @@ fn a_grant_covers_only_the_module_it_was_given_to() {
// A kept grant that records no hash, or an empty one, covers no module: the stored module isn't
// installed at the next start and `plugin.inspect` asks for approval.
for entry in [json!({"id": id, "permissions": ["settings", "cache"]}), json!({"id": id, "hash": "", "permissions": ["settings", "cache"]})] {
- std::fs::write(folder.0.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
+ std::fs::write(folder.0.join("grants.json"), crate::store::signed_grants_file(&folder.0, &json!([entry]).to_string())).unwrap();
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
let mut again = session();
@@ -5152,9 +5349,9 @@ fn grants_this_version_cant_read_are_kept() {
let invalid = json!({"id": "bad id/", "hash": "00", "permissions": ["doc.read"]});
let grant = json!({"id": kept, "hash": vectorcraft_plugins::permissions::sha256_hex(&kept_wasm), "permissions": ["doc.read"]});
let grants = folder.0.join("grants.json");
- std::fs::write(&grants, serde_json::to_vec(&json!([future, grant, invalid])).unwrap()).unwrap();
+ std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, grant, invalid]).to_string())).unwrap();
std::fs::write(folder.0.join("kept.wasm"), &kept_wasm).unwrap();
- let entries = || serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap();
+ let entries = || crate::store::grant_entries(&std::fs::read(&grants).unwrap());
let mut s = session();
s.attach_plugin_store(folder.0.clone());
assert!(vectorcraft_plugins::registry::get(kept).is_some(), "the entries this version can't read don't drop the grant next to them");
@@ -5188,7 +5385,7 @@ fn grants_this_version_cant_read_are_kept() {
// and left as it is when even compact would.
let cap = 1 << 20;
let many: Vec = (0..14_000).map(|i| json!({"id": format!("x.{i}"), "hash": "00", "permissions": ["ui.panel"]})).collect();
- let compact = serde_json::to_vec(&many).unwrap();
+ let compact = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&many).unwrap());
assert!(compact.len() < cap && serde_json::to_vec_pretty(&many).unwrap().len() > cap);
std::fs::write(&grants, &compact).unwrap();
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]}));
@@ -5198,13 +5395,1082 @@ fn grants_this_version_cant_read_are_kept() {
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm)}));
assert_eq!(inspected["needsApproval"], json!(false), "the compact file is read back");
run(&mut s, "plugin.remove", json!({"id": added}));
- let full = serde_json::to_vec(&json!([{"id": "x.full", "hash": "0".repeat(cap - 100), "permissions": ["ui.panel"]}])).unwrap();
+ let full = crate::store::signed_grants_file(
+ &folder.0,
+ &json!([{"id": "x.full", "hash": "0".repeat(cap - 250), "permissions": ["ui.panel"]}]).to_string(),
+ );
+ assert!(full.len() < cap);
std::fs::write(&grants, &full).unwrap();
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]}));
assert_eq!(std::fs::read(&grants).unwrap(), full, "not written past the cap");
run(&mut s, "plugin.remove", json!({"id": added}));
}
+/// Tests: the key store `store` on this thread until the guard is dropped.
+struct ThreadKeys;
+
+impl ThreadKeys {
+ fn using(store: impl crate::store::grant_keys::GrantKeyStore + 'static) -> Self {
+ crate::store::grant_keys::THREAD_STORE.set(Some(std::sync::Arc::new(store)));
+ ThreadKeys
+ }
+}
+
+impl Drop for ThreadKeys {
+ fn drop(&mut self) {
+ crate::store::grant_keys::THREAD_STORE.set(None);
+ }
+}
+
+/// A key store that is locked or can't be reached.
+struct UnreachableKeys;
+
+impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys {
+ fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> {
+ Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into()))
+ }
+
+ fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
+ Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into()))
+ }
+
+ fn generation(&self, _: &std::path::Path) -> std::result::Result , crate::store::grant_keys::KeyStoreError> {
+ Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into()))
+ }
+
+ fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
+ Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into()))
+ }
+}
+
+/// A memory key store the test keeps a handle on. While `file_generations_fail` is set, it fails to
+/// keep the generation that the grants file in the folder is at, and keeps every other one.
+struct SharedKeys {
+ keys: std::sync::Arc,
+ file_generations_fail: std::sync::Arc,
+}
+
+impl SharedKeys {
+ fn new(keys: &std::sync::Arc) -> Self {
+ SharedKeys { keys: keys.clone(), file_generations_fail: std::sync::Arc::default() }
+ }
+}
+
+impl crate::store::grant_keys::GrantKeyStore for SharedKeys {
+ fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> {
+ crate::store::grant_keys::GrantKeyStore::key(self.keys.as_ref())
+ }
+
+ fn set_key(&self, key: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
+ crate::store::grant_keys::GrantKeyStore::set_key(self.keys.as_ref(), key)
+ }
+
+ fn generation(&self, folder: &std::path::Path) -> std::result::Result , crate::store::grant_keys::KeyStoreError> {
+ crate::store::grant_keys::GrantKeyStore::generation(self.keys.as_ref(), folder)
+ }
+
+ fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
+ if self.file_generations_fail.load(std::sync::atomic::Ordering::SeqCst)
+ && std::fs::read(folder.join("grants.json")).ok().and_then(|bytes| generation_of(&bytes)) == Some(generation)
+ {
+ return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into()));
+ }
+ crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation)
+ }
+}
+
+/// The generation the grants file `bytes` is at.
+fn generation_of(bytes: &[u8]) -> Option {
+ serde_json::from_slice::(bytes).ok()?["generation"].as_u64()
+}
+
+/// The generation `keys` keeps for the plug-in store `dir`.
+fn kept_generation(keys: &crate::store::grant_keys::MemoryGrantKeys, dir: &std::path::Path) -> Option {
+ crate::store::grant_keys::GrantKeyStore::generation(keys, &crate::store::plugin_store_key(dir)).unwrap()
+}
+
+/// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether
+/// `plugin.inspect` of `data` (its module) then asks for approval.
+fn starts_from(dir: &std::path::Path, id: &str, data: &str) -> (bool, bool) {
+ vectorcraft_plugins::registry::remove(id);
+ vectorcraft_plugins::registry::revoke(id);
+ let mut next = session();
+ next.attach_plugin_store(dir.to_path_buf());
+ let asks = run(&mut next, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"] == json!(true);
+ (vectorcraft_plugins::registry::get(id).is_some(), asks)
+}
+
+/// The grants file as VectorCraft wrote it keeps its grants; once it is changed outside VectorCraft
+/// it grants nothing, and its plug-ins ask again: a grant given more permissions, a grant added, the
+/// MAC taken out or cut short, a MAC made with another key, the file cut short, and the file copied
+/// into another plug-in folder.
+#[test]
+fn a_grants_file_changed_outside_vectorcraft_grants_nothing() {
+ use crate::store::grant_keys::{GrantKey, MemoryGrantKeys};
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let folder = crate::tests_links::Folder::new("plugin-store-signed");
+ let copy = crate::tests_links::Folder::new("plugin-store-signed-copy");
+ let id = "test.engine.permissions.signed";
+ let added = "test.engine.permissions.signedadded";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let added_wasm = asking(added, r#"["doc.read"]"#, &json!({"objects": []}));
+ let (data, added_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&added_wasm));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let added_file = folder.0.join(format!("{}.wasm", crate::store::file_stem(added)));
+ std::fs::write(&added_file, &added_wasm).unwrap();
+ let written = std::fs::read(&grants).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file as written keeps its grant");
+
+ let file: Value = serde_json::from_slice(&written).unwrap();
+ let with = |change: &dyn Fn(&mut Value)| {
+ let mut file = file.clone();
+ change(&mut file);
+ serde_json::to_vec(&file).unwrap()
+ };
+ // At the generation kept for the folder, so that only the MAC tells the file apart.
+ let generation = file["generation"].as_u64().unwrap();
+ let other_key = {
+ let keys = MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32]));
+ crate::store::grant_keys::GrantKeyStore::set_generation(&keys, &crate::store::plugin_store_key(&folder.0), generation).unwrap();
+ let _other = ThreadKeys::using(keys);
+ crate::store::signed_grants_file(&folder.0, &file["grants"].to_string())
+ };
+ let tag = file["mac"].as_str().unwrap().to_string();
+ let changed: [(&str, Vec); 6] = [
+ ("a permission added", with(&|f| f["grants"][0]["permissions"] = json!(["doc.read", "doc.write"]))),
+ (
+ "a grant added",
+ with(&|f| f["grants"].as_array_mut().unwrap().push(json!({"id": added, "hash": sha256_hex(&added_wasm), "permissions": ["doc.read"]}))),
+ ),
+ ("the MAC taken out", with(&|f| _ = f.as_object_mut().unwrap().remove("mac"))),
+ ("the MAC cut short", with(&|f| f["mac"] = json!(tag[..32]))),
+ ("a MAC made with another key", other_key),
+ ("the file cut short", written[..written.len() - 2].to_vec()),
+ ];
+ for (what, bytes) in changed {
+ std::fs::write(&grants, &bytes).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{what}");
+ assert_eq!(starts_from(&folder.0, added, &added_data), (false, true), "{what}");
+ assert_eq!(std::fs::read(&grants).unwrap(), bytes, "{what}: the file is left as it is");
+ }
+
+ std::fs::write(&grants, &written).unwrap();
+ std::fs::write(copy.0.join("copied.wasm"), &wasm).unwrap();
+ std::fs::write(copy.0.join("grants.json"), &written).unwrap();
+ crate::store::grant_keys::set_current_generation(&crate::store::plugin_store_key(©.0), generation).unwrap();
+ assert_eq!(starts_from(©.0, id, &data), (false, true), "copied into another folder");
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file left as written keeps its grant");
+ std::fs::remove_file(&added_file).unwrap();
+ run(&mut s, "plugin.remove", json!({"id": id}));
+}
+
+/// A grants file in the form an older version wrote, a plain list, grants nothing. Approving a
+/// plug-in again replaces it with a signed file that holds that grant alone; removing a plug-in takes
+/// its entry out and leaves the rest unsigned.
+#[test]
+fn an_unsigned_grants_file_is_replaced_by_the_next_approval() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let folder = crate::tests_links::Folder::new("plugin-store-unsigned");
+ let id = "test.engine.permissions.unsigned";
+ let other = "test.engine.permissions.unsignedother";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let entry = |id: &str, wasm: &[u8]| json!({"id": id, "hash": sha256_hex(wasm), "permissions": ["doc.read"]});
+ let unsigned = serde_json::to_vec(&json!([entry(id, &wasm), entry(other, &other_wasm)])).unwrap();
+ std::fs::write(&grants, &unsigned).unwrap();
+ std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "an unsigned list grants nothing");
+ assert_eq!(std::fs::read(&grants).unwrap(), unsigned, "and is left as it is");
+
+ // `other` isn't installed, so the removal reports it as not found after removing its entry.
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.execute("plugin.remove", &json!({"id": other})).is_err());
+ assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "the removal takes its entry out");
+ assert!(std::fs::read(&grants).unwrap().starts_with(b"["), "and leaves the rest unsigned");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true));
+
+ std::fs::write(&grants, &unsigned).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true}));
+ assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "only the new grant is kept");
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the approval counts at the next start");
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ assert!(!grants.exists());
+}
+
+/// With no key in the key store, a signed grants file grants nothing; the next approval makes a key
+/// and signs a file that holds that grant alone.
+#[test]
+fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() {
+ use crate::store::grant_keys::{GrantKey, GrantKeyStore, MemoryGrantKeys};
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let folder = crate::tests_links::Folder::new("plugin-store-no-key");
+ let id = "test.engine.permissions.nokey";
+ let other = "test.engine.permissions.nokeyother";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let list = json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}, {"id": other, "hash": "0".repeat(64), "permissions": ["doc.read"]}]);
+ let signed = {
+ let _old = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([3; 32])));
+ crate::store::signed_grants_file(&folder.0, &list.to_string())
+ };
+ std::fs::write(&grants, &signed).unwrap();
+ std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap();
+ let keys = std::sync::Arc::new(MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "no key, no grant");
+ assert!(keys.key().unwrap().is_none(), "reading makes no key");
+ assert_eq!(std::fs::read(&grants).unwrap(), signed, "the file is left as it is");
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true}));
+ assert!(keys.key().unwrap().is_some(), "the approval makes a key");
+ let ids: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect();
+ assert_eq!(ids, vec![json!(id)], "only the new grant is kept");
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false));
+ run(&mut s, "plugin.remove", json!({"id": id}));
+}
+
+/// When the key store can't be reached, no grants file grants anything and none is written: an
+/// approval holds for the session only, the stored module isn't replaced, and a grant the file may
+/// hold can't be removed.
+#[test]
+fn an_unreachable_key_store_keeps_approvals_in_the_session() {
+ let folder = crate::tests_links::Folder::new("plugin-store-unreachable-keys");
+ let id = "test.engine.permissions.unreachable";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let written = std::fs::read(&grants).unwrap();
+ let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
+
+ let locked = ThreadKeys::using(UnreachableKeys);
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the stored grant can't be checked");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null}));
+ run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"], "replace": true}));
+ assert_eq!(
+ vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()),
+ Some(vectorcraft_plugins::permissions::sha256_hex(&changed)),
+ "it runs in this session"
+ );
+ assert_eq!(std::fs::read(&grants).unwrap(), written, "the grants file is left as it is");
+ assert_eq!(std::fs::read(&module).unwrap(), wasm, "the store keeps the module its grant covers");
+ let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
+ assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}");
+ assert_eq!(std::fs::read(&grants).unwrap(), written);
+
+ drop(locked);
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the grant counts once the key store can be reached");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ assert!(!grants.exists());
+}
+
+/// While the key store can't be reached, removing a plug-in fails and leaves it installed when no
+/// earlier signed copy of the grants file can be kept from granting it again: with the grants file
+/// gone, and with a grants file that doesn't name the plug-in. Once the key store can be reached, the
+/// removal raises the generation, and the copy put back grants nothing.
+#[test]
+fn a_removal_the_key_store_cannot_make_last_fails() {
+ let folder = crate::tests_links::Folder::new("plugin-store-unreachable-remove");
+ let id = "test.engine.permissions.unreachableremove";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
+ let written = std::fs::read(&grants).unwrap();
+ std::fs::remove_file(&grants).unwrap();
+
+ let locked = ThreadKeys::using(UnreachableKeys);
+ let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
+ assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with the grants file gone: {refused}");
+ assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed");
+ drop(locked);
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ std::fs::write(&grants, &written).unwrap();
+ std::fs::write(&module, &wasm).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing");
+ std::fs::remove_file(&grants).unwrap();
+ std::fs::remove_file(&module).unwrap();
+
+ let other = "test.engine.permissions.unreachableremoveother";
+ let plain = vectorcraft_format::base64_encode(&asking(id, "[]", &json!({"objects": []})));
+ let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ run(&mut s, "plugin.install", json!({"dataBase64": plain}));
+ let names: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect();
+ assert_eq!(names, vec![json!(other)], "the grants file doesn't name the plug-in");
+ let locked = ThreadKeys::using(UnreachableKeys);
+ let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
+ assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with a grants file that can't be checked: {refused}");
+ assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed");
+ drop(locked);
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ run(&mut s, "plugin.remove", json!({"id": other}));
+}
+
+/// A stored plug-in that didn't load, because the grants file of an older version doesn't count, and
+/// that keeps no settings or cache, is removed with its module and its entry, and the removal
+/// reports it removed. A removal whose stored module can't be deleted fails and keeps its settings.
+/// Removing an invalid id leaves the kept generation as it is.
+#[test]
+fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let folder = crate::tests_links::Folder::new("plugin-store-unloaded-remove");
+ let id = "test.engine.permissions.unloadedremove";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id)));
+ std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}])).unwrap()).unwrap();
+ std::fs::write(&module, &wasm).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the unsigned list grants nothing");
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})));
+ assert!(!module.exists(), "the module is removed");
+ assert!(!grants.exists(), "and its entry");
+ assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "a second removal finds nothing");
+
+ // A stored module that can't be deleted (here a folder in its place), of a plug-in that keeps
+ // settings, fails the removal, and the settings stay for the next try.
+ std::fs::create_dir_all(module.join("held")).unwrap();
+ let data_dir = crate::store::plugin_data_dir(&folder.0, id);
+ std::fs::create_dir_all(&data_dir).unwrap();
+ let setting = data_dir.join("settings.json");
+ std::fs::write(&setting, b"{}").unwrap();
+ let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
+ assert!(refused.contains("can't delete"), "{refused}");
+ assert!(module.exists());
+ assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back");
+ std::fs::remove_dir_all(&module).unwrap();
+ assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal deletes them");
+ assert!(!data_dir.exists());
+
+ // An invalid id names no grant: its removal doesn't raise the generation.
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([3; 32])));
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ for invalid in ["", "not an id"] {
+ assert!(s.execute("plugin.remove", &json!({"id": invalid})).is_err(), "{invalid:?} isn't found");
+ assert_eq!(kept_generation(&keys, &folder.0), None, "{invalid:?}: the generation is left as it is");
+ }
+ assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
+ assert_eq!(kept_generation(&keys, &folder.0), Some(2), "a valid id's removal still retires signed copies");
+}
+
+/// Removing an installed plug-in whose stored module can't be deleted fails, and the plug-in stays
+/// installed with its settings and its stored grant; a second removal, once the module can be
+/// deleted, removes it.
+#[test]
+fn removing_an_installed_plugin_whose_module_cant_be_deleted_keeps_it_installed() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32])));
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let folder = crate::tests_links::Folder::new("plugin-store-installed-remove-held");
+ let id = "test.engine.permissions.installedremoveheld";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id)));
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ assert!(module.is_file(), "the module is stored");
+ assert!(s.holds_plugin_grant(id), "and its grant");
+ let stored_grant = s.stored_plugin_grant(id);
+ assert!(stored_grant.is_some(), "in the signed grants file");
+ let data_dir = crate::store::plugin_data_dir(&folder.0, id);
+ std::fs::create_dir_all(&data_dir).unwrap();
+ let setting = data_dir.join("settings.json");
+ std::fs::write(&setting, b"{}").unwrap();
+
+ // A folder in the module's place can't be deleted as a file.
+ std::fs::remove_file(&module).unwrap();
+ std::fs::create_dir_all(module.join("held")).unwrap();
+ let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
+ assert!(refused.contains("can't delete"), "{refused}");
+ assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
+ assert!(module.exists());
+ assert!(s.stored_plugin_grant(id) == stored_grant, "the stored grant is kept for the next launch");
+ assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back");
+
+ std::fs::remove_dir_all(&module).unwrap();
+ assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal removes it");
+ assert!(vectorcraft_plugins::registry::get(id).is_none() && !module.exists() && !data_dir.exists());
+ assert!(!s.holds_plugin_grant(id), "and its grant");
+}
+
+/// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same
+/// key, generation, grants and folder verifies. A key's bytes are never printed.
+#[test]
+fn a_grants_mac_verifies_only_for_its_key_grants_and_folder() {
+ use crate::store::grant_keys::{GrantKey, sign, verify};
+ let (key, other) = (GrantKey::from_bytes([1; 32]), GrantKey::from_bytes([2; 32]));
+ let folder = std::path::Path::new("/plug-ins");
+ let tag = sign(&key, folder, 4, b"[]").unwrap();
+ assert_eq!(tag.len(), 64);
+ assert!(verify(&key, folder, 4, b"[]", &tag));
+ assert!(!verify(&other, folder, 4, b"[]", &tag), "another key");
+ assert!(!verify(&key, std::path::Path::new("/other"), 4, b"[]", &tag), "another folder");
+ assert!(!verify(&key, folder, 3, b"[]", &tag), "another generation");
+ assert!(!verify(&key, folder, 4, b"[ ]", &tag), "other grants");
+ assert!(!verify(&key, folder, 4, b"[]", &tag[..62]), "a MAC cut short");
+ assert!(!verify(&key, folder, 4, b"[]", &tag.to_uppercase()), "upper case");
+ assert!(!verify(&key, folder, 4, b"[]", ""));
+ assert_eq!(format!("{key:?}"), "GrantKey(..)");
+}
+
+/// A key store where another process keeps its key between this one's read and its write, and
+/// that write does not replace it.
+struct KeptFirstElsewhere {
+ reads: std::sync::Mutex,
+}
+
+impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere {
+ fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> {
+ let mut reads = self.reads.lock().unwrap();
+ *reads += 1;
+ // signing_key and create_key each read once before the write.
+ Ok((*reads > 2).then(|| crate::store::grant_keys::GrantKey::from_bytes([7; 32])))
+ }
+
+ fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
+ Ok(())
+ }
+
+ fn generation(&self, _: &std::path::Path) -> std::result::Result , crate::store::grant_keys::KeyStoreError> {
+ Ok(None)
+ }
+
+ fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
+ Ok(())
+ }
+}
+
+#[test]
+fn a_new_grants_key_is_the_one_the_key_store_kept() {
+ use crate::store::grant_keys::{GrantKey, sign, verify};
+ let _keys = ThreadKeys::using(KeptFirstElsewhere { reads: std::sync::Mutex::new(0) });
+ let key = crate::store::grant_keys::signing_key().unwrap();
+ assert_eq!(key, GrantKey::from_bytes([7; 32]), "the key kept first signs");
+ let folder = std::path::Path::new("/plug-ins");
+ assert!(verify(&GrantKey::from_bytes([7; 32]), folder, 1, b"[]", &sign(&key, folder, 1, b"[]").unwrap()));
+}
+
+/// An earlier copy of the grants file put back over the current one grants nothing: after one
+/// plug-in's grant is revoked while another's stays, and after the last grant is revoked and the
+/// file removed.
+#[test]
+fn an_earlier_grants_file_put_back_grants_nothing() {
+ let folder = crate::tests_links::Folder::new("plugin-store-earlier-copy");
+ let id = "test.engine.permissions.earlier";
+ let other = "test.engine.permissions.earlierother";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []}));
+ let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ let both = std::fs::read(&grants).unwrap();
+ run(&mut s, "plugin.remove", json!({"id": other}));
+ let one = std::fs::read(&grants).unwrap();
+
+ std::fs::write(&grants, &both).unwrap();
+ assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "the revoked grant doesn't come back");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier copy grants nothing");
+ std::fs::write(&grants, &one).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the current file keeps its grant");
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ assert!(!grants.exists());
+ std::fs::write(&grants, &one).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the last revoked grant doesn't come back");
+
+ // A grant revoked from a file edited outside VectorCraft doesn't come back with a signed copy
+ // made before the edit either.
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let signed = std::fs::read(&grants).unwrap();
+ let mut edited: Value = serde_json::from_slice(&signed).unwrap();
+ edited["mac"] = json!("0".repeat(64));
+ std::fs::write(&grants, serde_json::to_vec(&edited).unwrap()).unwrap();
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ assert!(!grants.exists());
+ std::fs::write(&grants, &signed).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back");
+}
+
+/// A grant revoked while the grants file is gone, or while another file that grants nothing (one
+/// without a MAC, or one that doesn't hold a list) is in its place, doesn't come back with the last
+/// signed file put back: the revoke raises the generation. A revoke that a signed file without an
+/// entry for the plug-in already covers, or one while the key store holds no key, leaves the
+/// generation as it is.
+#[test]
+fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new("plugin-store-revoke-without-file");
+ let id = "test.engine.permissions.revokedgone";
+ let other = "test.engine.permissions.revokedgoneother";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.store_grant(other, None), "nothing to revoke in an empty folder");
+ assert_eq!(kept(&folder.0), None, "without a key nothing is signed, so no generation is kept");
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let signed = std::fs::read(&grants).unwrap();
+ assert_eq!(kept(&folder.0), Some(3));
+ assert!(s.store_grant(other, None));
+ assert_eq!(kept(&folder.0), Some(3), "the signed file names no grant for it, so nothing is raised");
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false));
+
+ // The file is gone when the grant is revoked.
+ std::fs::remove_file(&grants).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.store_grant(id, None));
+ assert_eq!(kept(&folder.0), Some(5));
+ std::fs::write(&grants, &signed).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked while the file was gone doesn't come back");
+
+ // A file without a MAC that names no grant for it is in place.
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let signed = std::fs::read(&grants).unwrap();
+ std::fs::write(&grants, b"[]").unwrap();
+ assert!(s.store_grant(id, None));
+ assert_eq!(std::fs::read(&grants).unwrap(), b"[]", "the unsigned file is left as it is");
+ std::fs::write(&grants, &signed).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over an unsigned file doesn't come back");
+
+ // A file that doesn't hold a list is in place: it is left as it is, and the revoke holds once it
+ // raises the generation.
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let signed = std::fs::read(&grants).unwrap();
+ std::fs::write(&grants, br#""not a list""#).unwrap();
+ assert!(s.store_grant(id, None));
+ assert_eq!(std::fs::read(&grants).unwrap(), br#""not a list""#, "the file is left as it is");
+ std::fs::write(&grants, &signed).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back");
+}
+
+/// Every signed write of the grants file raises the generation by two and is at the generation after
+/// that, which the key store then keeps, and the file stays signed; removing the last grant raises
+/// the generation too.
+#[test]
+fn a_signed_grants_write_raises_the_generation_and_stays_signed() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new("plugin-store-generation");
+ let id = "test.engine.permissions.generation";
+ let other = "test.engine.permissions.generationother";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3)));
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false));
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(6), Some(6)));
+ run(&mut s, "plugin.remove", json!({"id": other}));
+ assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(9), Some(9)));
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ assert!(!grants.exists());
+ assert_eq!(kept(&folder.0), Some(11), "removing the file raises the generation");
+}
+
+/// Each plug-in folder has a generation of its own.
+#[test]
+fn two_plugin_folders_keep_their_own_generations() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let first = crate::tests_links::Folder::new("plugin-store-generation-a");
+ let second = crate::tests_links::Folder::new("plugin-store-generation-b");
+ let ids = ["test.engine.permissions.foldera", "test.engine.permissions.folderaother", "test.engine.permissions.folderb"];
+ let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect();
+ let mut a = session();
+ a.attach_plugin_store(first.0.clone());
+ run(&mut a, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]}));
+ run(&mut a, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]}));
+ let mut b = session();
+ b.attach_plugin_store(second.0.clone());
+ run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]}));
+ assert_eq!((kept(&first.0), kept(&second.0)), (Some(6), Some(3)));
+ assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false));
+ assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false));
+ let (mut a, mut b) = (session(), session());
+ a.attach_plugin_store(first.0.clone());
+ b.attach_plugin_store(second.0.clone());
+ run(&mut a, "plugin.remove", json!({"id": ids[0]}));
+ run(&mut a, "plugin.remove", json!({"id": ids[1]}));
+ run(&mut b, "plugin.remove", json!({"id": ids[2]}));
+}
+
+/// A key store that holds a key and no generation for the folder, as one does the first time this
+/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 3.
+#[test]
+fn a_key_without_a_generation_reads_generation_zero() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32])));
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let folder = crate::tests_links::Folder::new("plugin-store-generation-zero");
+ let id = "test.engine.permissions.generationzero";
+ let other = "test.engine.permissions.generationzeroother";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ assert_eq!(crate::store::grant_keys::current_generation(&crate::store::plugin_store_key(&folder.0)), Ok(0));
+ let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string());
+ assert_eq!(generation_of(&file), Some(0));
+ std::fs::write(&grants, &file).unwrap();
+ std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at generation 0 keeps its grant");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
+ run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(3));
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false));
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.remove", json!({"id": other}));
+ run(&mut s, "plugin.remove", json!({"id": id}));
+}
+
+/// A grant revoked while the file signed at generation 0 is gone doesn't come back with that file
+/// put back: with a key kept, the revoke raises the generation from 0.
+#[test]
+fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([6; 32])));
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let folder = crate::tests_links::Folder::new("plugin-store-generation-zero-revoke");
+ let id = "test.engine.permissions.generationzerorevoke";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string());
+ assert_eq!(generation_of(&file), Some(0));
+ std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.store_grant(id, None));
+ assert_eq!(kept_generation(&keys, &folder.0), Some(2));
+ std::fs::write(&grants, &file).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file at generation 0 grants nothing");
+}
+
+/// When the key store can't keep the generation of a write, the file written is one generation ahead
+/// of the kept one and grants nothing, so its plug-ins ask again; so does the earlier file, since
+/// the generation was raised past it before the write, and a file behind the kept generation.
+#[test]
+fn a_grants_file_whose_generation_was_not_kept_grants_nothing() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let shared = SharedKeys::new(&keys);
+ let fail = shared.file_generations_fail.clone();
+ let _keys = ThreadKeys::using(shared);
+ let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept");
+ let store = crate::store::plugin_store_key(&folder.0);
+ let id = "test.engine.permissions.generationunkept";
+ let other = "test.engine.permissions.generationunkeptother";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let written = std::fs::read(&grants).unwrap();
+
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ let ahead = std::fs::read(&grants).unwrap();
+ let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap();
+ assert_eq!((generation_of(&ahead), kept), (Some(6), Some(5)), "the file is one generation ahead");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing");
+ assert_eq!(starts_from(&folder.0, other, &other_data), (false, true));
+
+ std::fs::write(&grants, &written).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier file grants nothing");
+ crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 3).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant");
+ crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 4).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing");
+}
+
+/// A revoke over a signed file whose generation wasn't kept raises the generation past the file's,
+/// so the file left in place still grants nothing.
+#[test]
+fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let shared = SharedKeys::new(&keys);
+ let fail = shared.file_generations_fail.clone();
+ let _keys = ThreadKeys::using(shared);
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new("plugin-store-revoke-ahead");
+ let id = "test.engine.permissions.revokeahead";
+ let other = "test.engine.permissions.revokeaheadother";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ let ahead = std::fs::read(&grants).unwrap();
+ assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(6), Some(5)));
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.store_grant("test.engine.permissions.revokeaheadnone", None));
+ assert_eq!(std::fs::read(&grants).unwrap(), ahead, "the file is left as it is");
+ assert_eq!(kept(&folder.0), Some(7), "the generation is past the file's");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file still grants nothing");
+ assert_eq!(starts_from(&folder.0, other, &other_data), (false, true));
+}
+
+/// A signed write raises the generation before it writes the file, so a signed write whose generation
+/// wasn't kept also leaves the earlier file granting nothing; a revoke over that earlier file put back
+/// is then not at the generation of the unkept write, and a copy of that write put back after the
+/// revoke grants nothing.
+#[test]
+fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_nothing() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let shared = SharedKeys::new(&keys);
+ let fail = shared.file_generations_fail.clone();
+ let _keys = ThreadKeys::using(shared);
+ let folder = crate::tests_links::Folder::new("plugin-store-revoke-after-unkept");
+ let ids = ["test.engine.permissions.afterunkept", "test.engine.permissions.afterunkeptother", "test.engine.permissions.afterunkeptthird"];
+ let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect();
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]}));
+ run(&mut s, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]}));
+ let earlier = std::fs::read(&grants).unwrap();
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ _ = s.execute("plugin.install", &json!({"dataBase64": data[2], "grant": ["doc.read"]}));
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ let unkept = std::fs::read(&grants).unwrap();
+
+ std::fs::write(&grants, &earlier).unwrap();
+ assert_eq!(starts_from(&folder.0, ids[0], &data[0]), (false, true), "the earlier file grants nothing");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.store_grant(ids[1], None));
+ std::fs::write(&grants, &unkept).unwrap();
+ assert_eq!(starts_from(&folder.0, ids[1], &data[1]), (false, true), "the revoked grant doesn't come back");
+ assert_eq!(starts_from(&folder.0, ids[2], &data[2]), (false, true), "the unkept write grants nothing");
+ std::fs::remove_file(&grants).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ for id in ids {
+ _ = s.execute("plugin.remove", &json!({"id": id}));
+ }
+}
+
+/// A grant whose signed file fits the 1 MiB limit at the generation it is written at is kept, also
+/// when the file would not fit with a longer generation number.
+#[test]
+fn a_grants_file_that_fits_at_its_generation_is_written() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let folder = crate::tests_links::Folder::new("plugin-store-grants-fit");
+ let id = "test.engine.permissions.grantsfit";
+ let grant = doc_read_grant(id, &sha256_hex(b"module"));
+ let grants = folder.0.join("grants.json");
+ // The file as it is written: compact, since pretty-printed it is larger than the limit.
+ let size = |pad: &str| serde_json::to_vec(&json!({"version": 1, "generation": 3, "grants": [grant, pad], "mac": "0".repeat(64)})).unwrap().len();
+ let pad = "a".repeat((1 << 20) - size(""));
+ assert_eq!(size(&pad), 1 << 20);
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([pad]).to_string())).unwrap();
+ assert!(s.store_grant(id, Some(grant)), "the grant is kept");
+ let written = std::fs::read(&grants).unwrap();
+ assert_eq!((written.len(), generation_of(&written)), (1 << 20, Some(3)));
+ assert_eq!(kept_generation(&keys, &folder.0), Some(3));
+}
+
+/// A grants file edited to carry the largest generations doesn't stop a revoke and doesn't move the
+/// generation the key store keeps near the limit, so later grants are still kept: the generation
+/// comes from the key store alone.
+#[test]
+fn a_grants_file_at_the_largest_generations_doesnt_stop_a_revoke() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ for carried in [u64::MAX, u64::MAX - 1] {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new(&format!("plugin-store-largest-generation-{}", u64::MAX - carried));
+ let id = "test.engine.permissions.largestgeneration";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let edited = |entries: Value| json!({"version": 1, "generation": carried, "grants": entries, "mac": "0".repeat(64)}).to_string();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ assert_eq!(kept(&folder.0), Some(3));
+
+ // The edited file names the grant, which the revoke takes out.
+ std::fs::write(&grants, edited(json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]))).unwrap();
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ assert!(!grants.exists(), "generation {carried}: the entry is taken out");
+ assert_eq!(kept(&folder.0), Some(5), "generation {carried}: the kept generation is raised from its own value");
+
+ // The edited file names no grant for it.
+ std::fs::write(&grants, edited(json!([]))).unwrap();
+ assert!(s.store_grant(id, None), "generation {carried}: the revoke is recorded");
+ assert_eq!(kept(&folder.0), Some(7), "generation {carried}: the kept generation is raised from its own value");
+
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(10), Some(10)), "generation {carried}");
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "generation {carried}: a later grant is kept");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.remove", json!({"id": id}));
+ }
+}
+
+/// A signed write whose generation wasn't kept leaves a file one generation past the kept one. A
+/// revoke raises the generation past that file too, so a copy of it put back grants nothing: a revoke
+/// from a file without a MAC, one while the file is gone, one over a file that doesn't hold a list,
+/// and one that removes the last grant of a signed file.
+#[test]
+fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() {
+ use vectorcraft_plugins::permissions::sha256_hex;
+ for path in ["unsigned", "gone", "not-a-list", "signed"] {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let shared = SharedKeys::new(&keys);
+ let fail = shared.file_generations_fail.clone();
+ let _keys = ThreadKeys::using(shared);
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new(&format!("plugin-store-unkept-copy-{path}"));
+ let id = "test.engine.permissions.unkeptcopy";
+ let other = "test.engine.permissions.unkeptcopyother";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []}));
+ let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ let unkept = std::fs::read(&grants).unwrap();
+ let before = kept(&folder.0).unwrap();
+ assert_eq!(generation_of(&unkept), Some(before + 1), "{path}: the file is one generation past the kept one");
+
+ let other_grant = json!([{"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}]).to_string();
+ match path {
+ "unsigned" => std::fs::write(&grants, &other_grant).unwrap(),
+ "gone" => std::fs::remove_file(&grants).unwrap(),
+ "not-a-list" => std::fs::write(&grants, br#""not a list""#).unwrap(),
+ _ => std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &other_grant)).unwrap(),
+ }
+ assert!(s.store_grant(other, None), "{path}");
+ std::fs::write(&grants, &unkept).unwrap();
+ assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "{path}: the revoked grant doesn't come back");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{path}: the copy grants nothing");
+ assert_eq!(kept(&folder.0), Some(before + 2), "{path}: the generation is past the file whose generation wasn't kept");
+ std::fs::remove_file(&grants).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ _ = s.execute("plugin.remove", &json!({"id": id}));
+ _ = s.execute("plugin.remove", &json!({"id": other}));
+ }
+}
+
+/// A signed write that fails after raising the generation leaves the generation raised: the file
+/// left in place, signed at the generation before the raise, grants nothing and its plug-ins ask
+/// again, and so does a copy of it put back after a later write.
+#[test]
+fn a_grants_write_that_fails_leaves_the_generation_raised() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new("plugin-store-write-fails");
+ let id = "test.engine.permissions.writefails";
+ let other = "test.engine.permissions.writefailsother";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let earlier = std::fs::read(&grants).unwrap();
+ assert_eq!((generation_of(&earlier), kept(&folder.0)), (Some(3), Some(3)));
+
+ crate::store::GRANTS_WRITE_FAILS.set(true);
+ let grant = vectorcraft_plugins::permissions::Grant {
+ id: other.into(),
+ hash: vectorcraft_plugins::permissions::sha256_hex(b"module"),
+ permissions: vec![vectorcraft_plugins::permissions::Permission::DocRead],
+ };
+ let written = s.store_grant(other, Some(grant));
+ crate::store::GRANTS_WRITE_FAILS.set(false);
+ assert!(!written, "the write reports a failure");
+ assert_eq!(std::fs::read(&grants).unwrap(), earlier, "the file is left as it was");
+ assert_eq!(kept(&folder.0), Some(5), "the generation stays raised");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file left in place grants nothing");
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
+ assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(8), Some(8)), "the next write is past the raise");
+ assert_eq!(starts_from(&folder.0, other, &other_data), (true, false), "the next write keeps its grant");
+ std::fs::write(&grants, &earlier).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy from before the raise grants nothing");
+ std::fs::remove_file(&grants).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ _ = s.execute("plugin.remove", &json!({"id": id}));
+ _ = s.execute("plugin.remove", &json!({"id": other}));
+}
+
+/// A revoke whose signed grants file can't be removed leaves the generation raised: the grant left in
+/// the file doesn't come back, and a later removal takes the file away.
+#[test]
+fn a_revoke_whose_grants_file_cant_be_removed_doesnt_bring_the_grant_back() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
+ let folder = crate::tests_links::Folder::new("plugin-store-remove-fails");
+ let id = "test.engine.permissions.removefails";
+ let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})));
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ let recorded = std::fs::read(&grants).unwrap();
+
+ crate::store::GRANTS_DELETE_FAILS.set(true);
+ let revoked = s.store_grant(id, None);
+ crate::store::GRANTS_DELETE_FAILS.set(false);
+ assert!(!revoked, "the removal reports a failure");
+ assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file is left as it was");
+ assert_eq!(kept(&folder.0), Some(5), "the generation stays raised");
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the revoked grant doesn't come back");
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ assert!(s.store_grant(id, None), "a later removal is recorded");
+ assert!(!grants.exists(), "and takes the file away");
+ std::fs::write(&grants, &recorded).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing");
+ std::fs::remove_file(&grants).unwrap();
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ _ = s.execute("plugin.remove", &json!({"id": id}));
+}
+
+/// The key store's generation for a folder only goes up: a lower one is refused and the kept one
+/// stays, while the same one and a higher one are kept.
+#[test]
+fn the_kept_grants_generation_is_never_lowered() {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let folder = crate::tests_links::Folder::new("plugin-store-generation-lowered");
+ let store = crate::store::plugin_store_key(&folder.0);
+ assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok());
+ assert!(crate::store::grant_keys::set_current_generation(&store, 3).is_err(), "a lower generation is refused");
+ assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(5), "the kept one stays");
+ assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok(), "the same one is kept");
+ assert!(crate::store::grant_keys::set_current_generation(&store, 6).is_ok());
+ assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(6));
+}
+
+/// A kept generation within two of the largest 64-bit value isn't raised: a signed write leaves the
+/// file and the generation as they are, and the file keeps its grant. Three below it, the write goes
+/// to the largest value.
+#[test]
+fn a_kept_generation_near_the_largest_value_isnt_raised() {
+ use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex};
+ for (kept_before, written) in [(u64::MAX - 2, None), (u64::MAX - 3, Some(u64::MAX))] {
+ let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
+ let _keys = ThreadKeys::using(SharedKeys::new(&keys));
+ let folder = crate::tests_links::Folder::new(&format!("plugin-store-generation-near-max-{}", u64::MAX - kept_before));
+ let store = crate::store::plugin_store_key(&folder.0);
+ let id = "test.engine.permissions.nearmax";
+ let other = "test.engine.permissions.nearmaxother";
+ let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
+ let data = vectorcraft_format::base64_encode(&wasm);
+ let grants = folder.0.join("grants.json");
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
+ crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, kept_before).unwrap();
+ let file =
+ crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string());
+ std::fs::write(&grants, &file).unwrap();
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file grants");
+
+ let mut s = session();
+ s.attach_plugin_store(folder.0.clone());
+ let grant = Grant { id: other.into(), hash: sha256_hex(b"module"), permissions: vec![Permission::DocRead] };
+ assert_eq!(s.store_grant(other, Some(grant)), written.is_some(), "{kept_before}");
+ match written {
+ None => {
+ assert_eq!(std::fs::read(&grants).unwrap(), file, "{kept_before}: the file is left as it is");
+ assert_eq!(kept_generation(&keys, &folder.0), Some(kept_before), "{kept_before}: the generation too");
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file keeps its grant");
+ }
+ Some(generation) => {
+ assert_eq!(
+ (generation_of(&std::fs::read(&grants).unwrap()), kept_generation(&keys, &folder.0)),
+ (Some(generation), Some(generation))
+ );
+ assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the new file keeps the grant");
+ }
+ }
+ std::fs::remove_file(&grants).unwrap();
+ vectorcraft_plugins::registry::remove(id);
+ vectorcraft_plugins::registry::revoke(id);
+ }
+}
+
/// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next
/// start without asking, with its budget.
#[test]
@@ -6397,12 +7663,14 @@ fn deferred_move(s: &mut Session) -> NodeId {
r
}
-/// The rectangle a run that hands back what it is given left during [`deferred_move`]: moved, with
-/// the interaction ended and the move the last undo step, since the run changed nothing.
+/// The rectangle an echoing run during [`deferred_move`] left: moved, with the interaction ended and
+/// the move the last undo step, since the run handed the rectangle back as it was and so records
+/// none.
fn assert_moved_once(s: &Session, r: NodeId) {
assert!(!s.in_interaction());
assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle");
- assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move"));
+ let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
+ assert_eq!(labels, ["Move", "Rectangle"]);
}
/// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies
diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs
index 0f3e3ef459..7a339b6cbd 100644
--- a/crates/engine/src/tests/prefs.rs
+++ b/crates/engine/src/tests/prefs.rs
@@ -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);
diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs
index 4e705538d9..43ee65ba46 100644
--- a/crates/engine/src/tests/script_dom.rs
+++ b/crates/engine/src/tests/script_dom.rs
@@ -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();
diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs
index 78b0065b46..1b41d992fd 100644
--- a/crates/engine/src/tests/script_include.rs
+++ b/crates/engine/src/tests/script_include.rs
@@ -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)> = 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);
+}
diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs
index 0d766e238a..c12653602f 100644
--- a/crates/engine/src/tests/script_run.rs
+++ b/crates/engine/src/tests/script_run.rs
@@ -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"),
diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs
index 933ed15874..7a28a84ec7 100644
--- a/crates/engine/src/tests/toolsettings.rs
+++ b/crates/engine/src/tests/toolsettings.rs
@@ -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]
diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs
index 222657ac1c..965abf399c 100644
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@ -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";
diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs
index 25067f5c0e..07389dc866 100644
--- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs
+++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs
@@ -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"),
(
diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs
index 7a323390c9..488c094c63 100644
--- a/crates/engine/tests/plugin_clear_cache.rs
+++ b/crates/engine/tests/plugin_clear_cache.rs
@@ -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();
diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs
index 33bc8bc299..911b39de34 100644
--- a/crates/engine/tests/plugin_fuzz.rs
+++ b/crates/engine/tests/plugin_fuzz.rs
@@ -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());
diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs
index 9e23624a31..03bef1ea28 100644
--- a/crates/engine/tests/plugin_safe_mode.rs
+++ b/crates/engine/tests/plugin_safe_mode.rs
@@ -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
diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs
index 31414bb517..86b31414b3 100644
--- a/crates/js/src/builtins.rs
+++ b/crates/js/src/builtins.rs
@@ -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 {
+ 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 {
diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs
new file mode 100644
index 0000000000..276acf7e96
--- /dev/null
+++ b/crates/js/src/builtins/promise.rs
@@ -0,0 +1,1191 @@
+//! `Promise` (ECMA-262 11th edition, section 25.6, )
+//! and the run's queue of promise jobs (section 8.4), in realms with [`crate::Options::es2015`]:
+//! the constructor, `then`, `catch` and `finally`, and `Promise.resolve`, `reject`, `all`,
+//! `allSettled` and `race`. `Promise.any` (ES2021) is not provided.
+//!
+//! A job is queued when a promise settles with reactions waiting, when `then` is called on a
+//! settled promise, and when a promise is resolved with a thenable. Jobs run one at a time, in the
+//! order they were queued, once the script's own code has ended and no other code runs: at the end
+//! of [`crate::Realm::run`], and in the slices [`crate::Realm::advance`] runs after the script's
+//! code, before it reports the run done. A job that a job queues joins the end of the queue. A job
+//! takes a unit of fuel, its callback runs on the run's fuel, heap and frame limits, and a callback
+//! written in JavaScript runs as the script's own code, so a slice can pause inside it. Each queued
+//! job counts [`JOB_BYTES`] toward the heap limit, and more than [`MAX_JOBS`] queued jobs end the
+//! run with [`LimitKind::Jobs`]. A run that ends with an error or a limit, or is ended, drops the
+//! jobs still queued. A promise that is still pending when the queue is empty stays pending.
+//!
+//! A promise rejected while it has no handler is noted (HostPromiseRejectionTracker, section
+//! 25.6.1.9); one that still has none when the run ends successfully is reported by
+//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known.
+//!
+//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object
+//! whose `length` is a whole number by index, and a string by code point; other values reject the
+//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the
+//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species`
+//! are not read.
+
+use std::collections::VecDeque;
+use std::rc::Rc;
+
+use super::{arg, constructor, create_at, method, native, new_array};
+use crate::LimitKind;
+use crate::bytecode::Code;
+use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key};
+use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
+use crate::string_builtins::flat_charged;
+use crate::value::Value;
+
+/// Where a promise was rejected: the code and the instruction.
+pub(crate) type Site = (Rc, usize);
+
+/// The estimated bytes of a promise's state, without its reactions.
+pub(crate) const PROMISE_BYTES: usize = 64;
+/// The estimated bytes of a reaction a pending promise holds.
+pub(crate) const REACTION_BYTES: usize = 48;
+/// The estimated bytes of the state a promise operation's functions share.
+pub(crate) const RECORD_BYTES: usize = 48;
+/// The estimated bytes of a queued job.
+pub(crate) const JOB_BYTES: usize = 64;
+/// The most jobs the queue may hold at once.
+pub(crate) const MAX_JOBS: usize = 1 << 20;
+/// The most unhandled rejections a run reports one by one.
+pub(crate) const MAX_REPORTED: usize = 20;
+/// The most characters of a rejection's reason a report gives.
+const MAX_REASON_CHARS: usize = 500;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum State {
+ Pending,
+ Fulfilled,
+ Rejected,
+}
+
+/// A `then` waiting for a pending promise: the handlers (`undefined` when not callable) and the
+/// promise `then` returned.
+#[derive(Clone)]
+pub(crate) struct Reaction {
+ on_fulfilled: Value,
+ on_rejected: Value,
+ derived: ObjId,
+}
+
+/// A promise's internal slots (section 25.6.6), with where it was rejected.
+#[derive(Clone)]
+pub(crate) struct PromiseData {
+ pub(crate) state: State,
+ pub(crate) result: Value,
+ reactions: Vec,
+ pub(crate) handled: bool,
+ pub(crate) site: Option,
+}
+
+impl PromiseData {
+ fn new() -> Self {
+ Self { state: State::Pending, result: Value::Undefined, reactions: Vec::new(), handled: false, site: None }
+ }
+
+ /// The values the promise holds, for the collector.
+ pub(crate) fn values(&self) -> Vec {
+ let mut out = vec![self.result.clone()];
+ for r in &self.reactions {
+ out.extend([r.on_fulfilled.clone(), r.on_rejected.clone(), Value::Object(r.derived)]);
+ }
+ out
+ }
+
+ /// The estimated bytes of the state, beyond the object.
+ pub(crate) fn bytes(&self) -> usize {
+ PROMISE_BYTES + REACTION_BYTES * self.reactions.len()
+ }
+}
+
+/// The state the functions a promise operation makes share.
+#[derive(Clone)]
+pub(crate) enum Record {
+ /// A promise's resolve and reject functions (section 25.6.1.3): the first call wins.
+ Resolving { promise: ObjId, done: bool },
+ /// `Promise.all` and `allSettled`: the result's resolving record, the values so far and the
+ /// inputs not yet settled.
+ Combinator { resolving: ObjId, values: ObjId, remaining: u64 },
+ /// The functions for one input of `Promise.all` or `allSettled`.
+ Element { combinator: ObjId, index: u32, called: bool },
+ /// `finally`'s callback.
+ Finally { on_finally: Value },
+ /// A value `finally` passes on or throws again.
+ Thunk { value: Value },
+}
+
+impl Record {
+ /// The values the record holds, for the collector.
+ pub(crate) fn values(&self) -> Vec {
+ match self {
+ Record::Resolving { promise, .. } => vec![Value::Object(*promise)],
+ Record::Combinator { resolving, values, .. } => vec![Value::Object(*resolving), Value::Object(*values)],
+ Record::Element { combinator, .. } => vec![Value::Object(*combinator)],
+ Record::Finally { on_finally: v } | Record::Thunk { value: v } => vec![v.clone()],
+ }
+ }
+}
+
+/// A queued job.
+enum Job {
+ /// PromiseReactionJob (section 25.6.2.1): calls `handler` with `argument` and settles
+ /// `derived` with the result, or passes `argument` on when `handler` is not callable.
+ Reaction { handler: Value, argument: Value, reject: bool, derived: ObjId, site: Option },
+ /// PromiseResolveThenableJob (section 25.6.2.2): calls `then` on `thenable` with new
+ /// resolving functions for `promise`.
+ Thenable { promise: ObjId, thenable: Value, then: Value },
+}
+
+/// What happens when the running job's call ends.
+enum Then {
+ /// The result resolves this promise, and an exception rejects it.
+ Settle(ObjId),
+ /// An exception rejects through this resolving record.
+ Reject(ObjId),
+ /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or
+ /// Catch Finally function: `derived` is settled as that function's result settles it.
+ Finally { derived: ObjId, value: Value, throws: bool },
+}
+
+/// The built-in functions a promise operation's functions call, with their record.
+#[derive(Clone, Copy)]
+enum Kind {
+ Resolve,
+ Reject,
+ AllElement,
+ SettledFulfilled,
+ SettledRejected,
+ ThenFinally,
+ CatchFinally,
+ ValueThunk,
+ Thrower,
+}
+
+const KINDS: [(Kind, NativeFn); 9] = [
+ (Kind::Resolve, resolve_function),
+ (Kind::Reject, reject_function),
+ (Kind::AllElement, all_element),
+ (Kind::SettledFulfilled, settled_fulfilled),
+ (Kind::SettledRejected, settled_rejected),
+ (Kind::ThenFinally, then_finally),
+ (Kind::CatchFinally, catch_finally),
+ (Kind::ValueThunk, value_thunk),
+ (Kind::Thrower, thrower),
+];
+
+/// `Promise`'s objects and the run's job queue.
+pub(crate) struct Promises {
+ proto: Option,
+ ctor: Option,
+ /// The built-ins for each [`Kind`], in [`KINDS`] order.
+ natives: Vec,
+ queue: VecDeque,
+ running: Option,
+ /// The script's completion value while the jobs after it run.
+ completion: Option,
+ /// The script's own code has ended and the queue's jobs are running.
+ pub(crate) draining: bool,
+ /// Promises rejected in this run while they had no handler.
+ rejected: Vec,
+ /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower).
+ pub(crate) max_jobs: usize,
+}
+
+impl Default for Promises {
+ fn default() -> Self {
+ Self {
+ proto: None,
+ ctor: None,
+ natives: Vec::new(),
+ queue: VecDeque::new(),
+ running: None,
+ completion: None,
+ draining: false,
+ rejected: Vec::new(),
+ max_jobs: MAX_JOBS,
+ }
+ }
+}
+
+impl Promises {
+ /// Adds what the queue and the promise objects hold to the collector's roots.
+ pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) {
+ roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected));
+ roots.values.extend(self.completion.iter());
+ match &self.running {
+ Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o),
+ Some(Then::Finally { derived, value, .. }) => {
+ roots.objects.push(*derived);
+ roots.values.push(value);
+ }
+ None => {}
+ }
+ for job in &self.queue {
+ match job {
+ Job::Reaction { handler, argument, derived, site, .. } => {
+ roots.values.extend([handler, argument]);
+ roots.objects.push(*derived);
+ roots.codes.extend(site.iter().map(|(code, _)| &**code));
+ }
+ Job::Thenable { promise, thenable, then } => {
+ roots.values.extend([thenable, then]);
+ roots.objects.push(*promise);
+ }
+ }
+ }
+ }
+
+ /// The estimated bytes the queued jobs hold.
+ pub(crate) fn queue_bytes(&self) -> usize {
+ JOB_BYTES.saturating_mul(self.queue.len())
+ }
+
+ /// How many jobs are queued, and how many the queue's buffer has room for.
+ #[cfg(test)]
+ pub(crate) fn queue_size(&self) -> (usize, usize) {
+ (self.queue.len(), self.queue.capacity())
+ }
+
+ /// Drops the noted rejections whose promise has a handler now.
+ pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) {
+ self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled));
+ }
+}
+
+/// Creates `Promise`, its prototype methods and its statics.
+pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
+ let object_proto = interp.intrinsics.object_proto;
+ let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
+ interp.promises.proto = Some(proto);
+ let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?;
+ interp.promises.ctor = Some(ctor);
+ constructor(interp, "Promise", ctor, proto)?;
+ method(interp, proto, "then", promise_then, 2)?;
+ method(interp, proto, "catch", promise_catch, 1)?;
+ method(interp, proto, "finally", promise_finally, 1)?;
+ method(interp, ctor, "resolve", promise_resolve_static, 1)?;
+ method(interp, ctor, "reject", promise_reject_static, 1)?;
+ method(interp, ctor, "all", promise_all, 1)?;
+ method(interp, ctor, "allSettled", promise_all_settled, 1)?;
+ method(interp, ctor, "race", promise_race, 1)?;
+ for (_, f) in KINDS {
+ let n = native(interp, "", f, 1, NativeKind::Plain, false)?;
+ interp.promises.natives.push(n);
+ }
+ Ok(())
+}
+
+/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global
+/// `Promise` an earlier script defined, and leaves the language the realm's runs read as it is. A
+/// realm that has the built-in `Promise` already keeps it. When `Promise` cannot be created, every
+/// later run of the realm ends with an internal error, as for a realm whose built-ins could not be
+/// installed.
+pub(crate) fn add_to(interp: &mut Interp) {
+ if interp.promises.ctor.is_some() || interp.install_error.is_some() {
+ return;
+ }
+ if let Err(e) = install(interp) {
+ let reason = match e {
+ Abrupt::Throw(v) => interp.describe(&v),
+ Abrupt::Limit(kind) => format!("limit reached: {kind:?}"),
+ Abrupt::Internal(message) => message,
+ };
+ interp.install_error = Some(format!("the built-ins could not be installed: {reason}"));
+ }
+}
+
+// ---- helpers ----
+
+/// Runs `f`, then drops the temporary roots it added.
+fn scoped(interp: &mut Interp, f: impl FnOnce(&mut Interp) -> JsResult) -> JsResult {
+ let mark = interp.temp_roots.len();
+ let r = f(interp);
+ interp.temp_roots.truncate(mark);
+ r
+}
+
+fn root(interp: &mut Interp, v: &Value) {
+ interp.temp_roots.push(v.clone());
+}
+
+/// An exception that a promise operation turns into a rejection: it is no longer propagating, and
+/// the place it was thrown at, when known, is the rejection's.
+fn caught(interp: &mut Interp) -> Option {
+ interp.passing = Value::Undefined;
+ interp.thrown_mark = None;
+ interp.throw_site.take()
+}
+
+/// The instruction the innermost script frame is running.
+fn here(interp: &Interp) -> Option {
+ interp.frames.last().map(|f| (f.code.clone(), f.pc.saturating_sub(1)))
+}
+
+/// The value an error of type `t` with `message` is.
+fn error_value(interp: &mut Interp, t: ErrorType, message: &str) -> Value {
+ match interp.throw(t, message) {
+ Abrupt::Throw(v) => v,
+ _ => Value::Undefined,
+ }
+}
+
+fn promise_data(interp: &mut Interp, p: ObjId) -> JsResult<&mut PromiseData> {
+ match interp.heap.object_mut(p).map(|o| &mut o.class) {
+ Some(Class::Promise(d)) => Ok(d),
+ _ => Err(Abrupt::Internal("a promise operation lost its promise".into())),
+ }
+}
+
+fn record<'a>(interp: &'a mut Interp, r: &Value) -> JsResult<&'a mut Record> {
+ match r.as_object().and_then(|o| interp.heap.object_mut(o)).map(|o| &mut o.class) {
+ Some(Class::PromiseRecord(rec)) => Ok(rec),
+ _ => Err(Abrupt::Internal("a promise function lost its record".into())),
+ }
+}
+
+fn is_promise(interp: &Interp, v: &Value) -> bool {
+ v.as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Promise(_)))
+}
+
+/// `this` for a `Promise.prototype` method that needs a promise.
+fn this_promise(interp: &mut Interp, this: &Value, name: &str) -> JsResult {
+ match this.as_object() {
+ Some(o) if is_promise(interp, this) => Ok(o),
+ _ => Err(interp.type_error(&format!("Promise.prototype.{name} was called on a value that is not a promise"))),
+ }
+}
+
+/// Invoke (section 7.3.18): calls `v[name]` with `v` as `this`.
+fn invoke(interp: &mut Interp, v: &Value, name: &str, args: &[Value]) -> JsResult {
+ let f = interp.get_value(v, &key(name))?;
+ if !interp.is_callable(&f) {
+ return Err(interp.type_error(&format!("{name} is not a function")));
+ }
+ interp.call(&f, v, args)
+}
+
+/// A new pending promise.
+fn new_promise(interp: &mut Interp) -> JsResult {
+ interp.reserve_heap(OBJECT_BYTES + PROMISE_BYTES)?;
+ let proto = interp.promises.proto;
+ let o = interp.heap.alloc_object(Object::new(Class::Promise(Box::new(PromiseData::new())), proto));
+ interp.heap.bytes = interp.heap.bytes.saturating_add(PROMISE_BYTES);
+ Ok(o)
+}
+
+/// A new record. The values it holds must be rooted.
+fn new_record(interp: &mut Interp, rec: Record) -> JsResult {
+ interp.reserve_heap(OBJECT_BYTES + RECORD_BYTES)?;
+ let o = interp.heap.alloc_object(Object::new(Class::PromiseRecord(Box::new(rec)), None));
+ interp.heap.bytes = interp.heap.bytes.saturating_add(RECORD_BYTES);
+ Ok(o)
+}
+
+/// A function that calls the built-in for `kind` with `rec` before its own arguments. `rec` must
+/// be rooted.
+fn record_function(interp: &mut Interp, kind: Kind, rec: ObjId, length: u32) -> JsResult {
+ let Some(&target) = interp.promises.natives.get(kind as usize) else { return Err(Abrupt::Internal("Promise is not installed".into())) };
+ interp.reserve_heap(OBJECT_BYTES + PROP_BYTES + BOUND_ARG_BYTES + 16)?;
+ let proto = interp.intrinsics.function_proto;
+ let args: Rc<[Value]> = Rc::from([Value::Object(rec)]);
+ let f = interp.heap.alloc_object(Object::new(Class::Function(Func::Bound { target, this: Value::Undefined, args }), Some(proto)));
+ interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES);
+ interp.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?;
+ Ok(Value::Object(f))
+}
+
+/// CreateResolvingFunctions (section 25.6.1.3): the shared record, the resolve function and the
+/// reject function. `promise` must be rooted.
+fn resolving_functions(interp: &mut Interp, promise: ObjId) -> JsResult<(ObjId, Value, Value)> {
+ scoped(interp, |interp| {
+ let rec = new_record(interp, Record::Resolving { promise, done: false })?;
+ root(interp, &Value::Object(rec));
+ let resolve = record_function(interp, Kind::Resolve, rec, 1)?;
+ root(interp, &resolve);
+ let reject = record_function(interp, Kind::Reject, rec, 1)?;
+ Ok((rec, resolve, reject))
+ })
+}
+
+/// Checks that `n` more jobs fit in the queue and in the heap. Everything the caller still needs
+/// must be reachable from the roots.
+fn reserve_jobs(interp: &mut Interp, n: usize) -> JsResult<()> {
+ if interp.promises.queue.len().saturating_add(n) > interp.promises.max_jobs {
+ return Err(Abrupt::Limit(LimitKind::Jobs));
+ }
+ interp.reserve_heap(JOB_BYTES.saturating_mul(n))
+}
+
+/// Queues a job [`reserve_jobs`] made room for.
+fn push_job(interp: &mut Interp, job: Job) {
+ interp.heap.bytes = interp.heap.bytes.saturating_add(JOB_BYTES);
+ interp.promises.queue.push_back(job);
+}
+
+/// Settles pending promise `p` (FulfillPromise and RejectPromise, sections 25.6.1.4 and 25.6.1.7)
+/// and queues a job for each reaction. `p` and `value` must be rooted.
+fn settle(interp: &mut Interp, p: ObjId, fulfilled: bool, value: Value, site: Option) -> JsResult<()> {
+ let waiting = promise_data(interp, p)?.reactions.len();
+ reserve_jobs(interp, waiting)?;
+ let data = promise_data(interp, p)?;
+ if data.state != State::Pending {
+ return Ok(());
+ }
+ data.state = if fulfilled { State::Fulfilled } else { State::Rejected };
+ data.result = value.clone();
+ if !fulfilled {
+ data.site.clone_from(&site);
+ }
+ let reactions = std::mem::take(&mut data.reactions);
+ let handled = data.handled;
+ interp.heap.bytes = interp.heap.bytes.saturating_sub(REACTION_BYTES.saturating_mul(reactions.len()));
+ for r in reactions {
+ let handler = if fulfilled { r.on_fulfilled } else { r.on_rejected };
+ push_job(interp, Job::Reaction { handler, argument: value.clone(), reject: !fulfilled, derived: r.derived, site: site.clone() });
+ }
+ if !fulfilled && !handled {
+ interp.promises.rejected.push(p);
+ }
+ Ok(())
+}
+
+fn reject_promise(interp: &mut Interp, p: ObjId, reason: Value, site: Option) -> JsResult<()> {
+ scoped(interp, |interp| {
+ root(interp, &Value::Object(p));
+ root(interp, &reason);
+ settle(interp, p, false, reason, site)
+ })
+}
+
+/// A resolve function's steps after its first-call check (section 25.6.1.3.2): `resolution`
+/// fulfills `p`, unless it is `p` itself (a `TypeError` rejects it) or an object whose `then` is
+/// callable (a job adopts its state), and an exception reading `then` rejects it.
+fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult<()> {
+ scoped(interp, |interp| {
+ root(interp, &Value::Object(p));
+ root(interp, &resolution);
+ let Value::Object(o) = resolution else { return settle(interp, p, true, resolution, None) };
+ if o == p {
+ let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself");
+ let site = here(interp);
+ return reject_promise(interp, p, e, site);
+ }
+ let then = match interp.get_from(o, &key("then"), &resolution) {
+ Ok(t) => t,
+ Err(Abrupt::Throw(e)) => {
+ let site = caught(interp);
+ root(interp, &e);
+ return settle(interp, p, false, e, site);
+ }
+ Err(e) => return Err(e),
+ };
+ if !interp.is_callable(&then) {
+ return settle(interp, p, true, resolution, None);
+ }
+ root(interp, &then);
+ reserve_jobs(interp, 1)?;
+ push_job(interp, Job::Thenable { promise: p, thenable: resolution, then });
+ Ok(())
+ })
+}
+
+/// The resolve function of the resolving record `rec`.
+fn resolve_through(interp: &mut Interp, rec: ObjId, value: Value) -> JsResult<()> {
+ let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else {
+ return Err(Abrupt::Internal("not a resolving record".into()));
+ };
+ if *done {
+ return Ok(());
+ }
+ *done = true;
+ let p = *promise;
+ resolve_promise(interp, p, value)
+}
+
+/// The reject function of the resolving record `rec`.
+fn reject_through(interp: &mut Interp, rec: ObjId, reason: Value, site: Option) -> JsResult<()> {
+ let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else {
+ return Err(Abrupt::Internal("not a resolving record".into()));
+ };
+ if *done {
+ return Ok(());
+ }
+ *done = true;
+ let p = *promise;
+ reject_promise(interp, p, reason, site)
+}
+
+/// PerformPromiseThen (section 25.6.5.4.1) with `derived` as the result capability's promise.
+/// Every value must be rooted.
+fn perform_then(interp: &mut Interp, p: ObjId, on_fulfilled: Value, on_rejected: Value, derived: ObjId) -> JsResult<()> {
+ let on_fulfilled = if interp.is_callable(&on_fulfilled) { on_fulfilled } else { Value::Undefined };
+ let on_rejected = if interp.is_callable(&on_rejected) { on_rejected } else { Value::Undefined };
+ let state = promise_data(interp, p)?.state;
+ if state == State::Pending {
+ interp.reserve_heap(REACTION_BYTES)?;
+ interp.heap.bytes = interp.heap.bytes.saturating_add(REACTION_BYTES);
+ } else {
+ reserve_jobs(interp, 1)?;
+ }
+ let data = promise_data(interp, p)?;
+ data.handled = true;
+ match data.state {
+ State::Pending => {
+ data.reactions.push(Reaction { on_fulfilled, on_rejected, derived });
+ }
+ State::Fulfilled => {
+ let argument = data.result.clone();
+ push_job(interp, Job::Reaction { handler: on_fulfilled, argument, reject: false, derived, site: None });
+ }
+ State::Rejected => {
+ let (argument, site) = (data.result.clone(), data.site.clone());
+ push_job(interp, Job::Reaction { handler: on_rejected, argument, reject: true, derived, site });
+ }
+ }
+ Ok(())
+}
+
+/// PromiseResolve (section 25.6.4.5.1) with `c` as the constructor: `x` when it is a promise whose
+/// `constructor` is `c`, otherwise a new promise resolved with `x`.
+fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult {
+ scoped(interp, |interp| {
+ root(interp, &x);
+ if let Value::Object(o) = x
+ && is_promise(interp, &x)
+ {
+ let ctor = interp.get_from(o, &key("constructor"), &x)?;
+ if crate::interp::same_value(&ctor, c) {
+ return Ok(x);
+ }
+ }
+ let p = new_promise(interp)?;
+ root(interp, &Value::Object(p));
+ resolve_promise(interp, p, x)?;
+ Ok(Value::Object(p))
+ })
+}
+
+// ---- the job queue ----
+
+impl Interp {
+ /// A run begun with [`crate::Realm::start`] is going: its script's code or the jobs after it.
+ pub(crate) fn running(&self) -> bool {
+ !self.frames.is_empty() || self.promises.draining
+ }
+
+ /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's
+ /// code ended with `completion`, which this gives back.
+ pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult {
+ self.promises.completion = Some(completion);
+ loop {
+ if !self.frames.is_empty() {
+ let r = self.execute();
+ self.job_returned(r)?;
+ continue;
+ }
+ let Some(job) = self.promises.queue.pop_front() else { break };
+ self.start_job(job)?;
+ }
+ Ok(self.promises.completion.take().unwrap_or(Value::Undefined))
+ }
+
+ /// [`Interp::execute_slice`] for a run begun with [`crate::Realm::start`]: runs the script's
+ /// code and then the queued jobs, and gives `Some` with the script's completion value once the
+ /// code has ended and the queue is empty.
+ pub(crate) fn execute_run_slice(&mut self, pause_at: u64) -> JsResult> {
+ loop {
+ if self.frames.is_empty() {
+ let Some(job) = self.promises.queue.pop_front() else {
+ self.promises.draining = false;
+ // A pause asked for in the run's last step ends with the run.
+ self.pause.set(false);
+ return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined)));
+ };
+ self.start_job(job)?;
+ if self.can_pause_between_jobs(pause_at) {
+ return Ok(None);
+ }
+ continue;
+ }
+ match self.execute_slice(pause_at) {
+ Ok(None) => return Ok(None),
+ Ok(Some(v)) if self.promises.running.is_none() => {
+ // The script's own code ended.
+ if self.promises.queue.is_empty() {
+ self.pause.set(false);
+ return Ok(Some(v));
+ }
+ self.promises.completion = Some(v);
+ self.promises.draining = true;
+ }
+ Ok(Some(v)) => self.finish_job(Ok(v))?,
+ Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?,
+ Err(e) => return Err(e),
+ }
+ if self.can_pause_between_jobs(pause_at) {
+ return Ok(None);
+ }
+ }
+ }
+
+ /// No code is running and jobs are still queued, and the slice has used its fuel or the host
+ /// asked for a pause. With the queue empty the run is done instead, and the next turn of the
+ /// loop ends it.
+ fn can_pause_between_jobs(&self, pause_at: u64) -> bool {
+ self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false))
+ }
+
+ fn job_returned(&mut self, r: JsResult) -> JsResult<()> {
+ match r {
+ Ok(v) => self.finish_job(Ok(v)),
+ Err(Abrupt::Throw(v)) => self.finish_job(Err(v)),
+ Err(e) => Err(e),
+ }
+ }
+
+ /// Starts a job: a native callback runs to its end here, and a callback written in JavaScript
+ /// gets a frame the caller runs.
+ fn start_job(&mut self, job: Job) -> JsResult<()> {
+ self.heap.bytes = self.heap.bytes.saturating_sub(JOB_BYTES);
+ self.use_fuel()?;
+ scoped(self, |interp| {
+ let (f, this, args, then) = match job {
+ Job::Reaction { handler, argument, reject, derived, site } => {
+ if !interp.is_callable(&handler) {
+ return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) };
+ }
+ root(interp, &Value::Object(derived));
+ match finally_callback(interp, &handler) {
+ // The callback runs as the job's own call, so a slice can pause inside it.
+ Some((on_finally, throws)) => {
+ interp.temp_roots.extend([handler, argument.clone()]);
+ (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws })
+ }
+ None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)),
+ }
+ }
+ Job::Thenable { promise, thenable, then } => {
+ interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]);
+ let (rec, resolve, reject) = resolving_functions(interp, promise)?;
+ (then, thenable, vec![resolve, reject], Then::Reject(rec))
+ }
+ };
+ interp.temp_roots.push(f.clone());
+ interp.temp_roots.push(this.clone());
+ interp.temp_roots.extend(args.iter().cloned());
+ interp.promises.running = Some(then);
+ match interp.start_call(f, this, args) {
+ Ok(Some(v)) => interp.finish_job(Ok(v)),
+ Ok(None) => Ok(()),
+ Err(Abrupt::Throw(e)) => interp.finish_job(Err(e)),
+ Err(e) => Err(e),
+ }
+ })
+ }
+
+ /// Ends the running job with its call's result or exception.
+ fn finish_job(&mut self, r: Result) -> JsResult<()> {
+ let site = if r.is_err() { caught(self) } else { None };
+ let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) };
+ match (then, r) {
+ (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v),
+ (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site),
+ (Then::Reject(_), Ok(_)) => Ok(()),
+ (Then::Reject(rec), Err(e)) => scoped(self, |interp| {
+ root(interp, &Value::Object(rec));
+ reject_through(interp, rec, e, site)
+ }),
+ (Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| {
+ interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]);
+ match after_finally(interp, result, value, throws) {
+ Ok(v) => resolve_promise(interp, derived, v),
+ Err(Abrupt::Throw(e)) => {
+ let site = caught(interp);
+ reject_promise(interp, derived, e, site)
+ }
+ Err(e) => Err(e),
+ }
+ }),
+ (Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site),
+ }
+ }
+
+ /// Drops the run's queued jobs and its state; with `keep_rejections` false, the rejections it
+ /// noted too.
+ pub(crate) fn end_jobs(&mut self, keep_rejections: bool) {
+ let queued = self.promises.queue_bytes();
+ self.heap.bytes = self.heap.bytes.saturating_sub(queued);
+ // A new queue frees the old one's buffer, which the heap estimate does not count.
+ self.promises.queue = VecDeque::new();
+ self.promises.running = None;
+ self.promises.completion = None;
+ self.promises.draining = false;
+ if !keep_rejections {
+ self.promises.rejected.clear();
+ }
+ }
+
+ /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of
+ /// them described, and how many there are; the run's notes are cleared.
+ pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) {
+ let rejected = std::mem::take(&mut self.promises.rejected);
+ let mut out = Vec::new();
+ let mut count = 0;
+ for p in rejected {
+ let (reason, site) = match self.heap.object(p).map(|o| &o.class) {
+ Some(Class::Promise(d)) if !d.handled && d.state == State::Rejected => (d.result.clone(), d.site.clone()),
+ _ => continue,
+ };
+ count += 1;
+ if out.len() >= MAX_REPORTED {
+ continue;
+ }
+ // Two code units per character keeps MAX_REASON_CHARS characters and one more, so the
+ // cut below still marks a longer reason.
+ let mut message = self.describe_prefix(&reason, 2 * MAX_REASON_CHARS + 2);
+ if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) {
+ message.truncate(cut);
+ message.push('…');
+ }
+ let authored = self.thrown_by_script(&reason);
+ let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc)));
+ out.push(crate::Rejection { message, line, column, tag, authored });
+ }
+ (out, count)
+ }
+}
+
+// ---- Promise ----
+
+/// `new Promise(executor)` (section 25.6.3.1). Calling `Promise` without `new` is a `TypeError`.
+fn promise_ctor(interp: &mut Interp, _: Value, args: &[Value], constructed: bool) -> JsResult {
+ if !constructed {
+ return Err(interp.type_error("Promise must be called with new"));
+ }
+ let executor = arg(args, 0);
+ if !interp.is_callable(&executor) {
+ return Err(interp.type_error("the Promise executor is not a function"));
+ }
+ scoped(interp, |interp| {
+ root(interp, &executor);
+ let p = new_promise(interp)?;
+ root(interp, &Value::Object(p));
+ let (rec, resolve, reject) = resolving_functions(interp, p)?;
+ interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]);
+ match interp.call(&executor, &Value::Undefined, &[resolve, reject]) {
+ Ok(_) => {}
+ Err(Abrupt::Throw(e)) => {
+ let site = caught(interp);
+ root(interp, &e);
+ reject_through(interp, rec, e, site)?;
+ }
+ Err(e) => return Err(e),
+ }
+ Ok(Value::Object(p))
+ })
+}
+
+/// A promise's resolve function (section 25.6.1.3.2).
+fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
+ let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a resolve function lost its record".into()))?;
+ resolve_through(interp, rec, arg(args, 1))?;
+ Ok(Value::Undefined)
+}
+
+/// A promise's reject function (section 25.6.1.3.1).
+fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
+ let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?;
+ let site = here(interp);
+ reject_through(interp, rec, arg(args, 1), site)?;
+ Ok(Value::Undefined)
+}
+
+/// `Promise.prototype.then` (section 25.6.5.4).
+fn promise_then(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult {
+ let p = this_promise(interp, &this, "then")?;
+ scoped(interp, |interp| {
+ let derived = new_promise(interp)?;
+ root(interp, &Value::Object(derived));
+ perform_then(interp, p, arg(args, 0), arg(args, 1), derived)?;
+ Ok(Value::Object(derived))
+ })
+}
+
+/// `Promise.prototype.catch` (section 25.6.5.1).
+fn promise_catch(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult {
+ invoke(interp, &this, "then", &[Value::Undefined, arg(args, 0)])
+}
+
+/// `Promise.prototype.finally` (section 25.6.5.3).
+fn promise_finally(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult {
+ if !matches!(this, Value::Object(_)) {
+ return Err(interp.type_error("Promise.prototype.finally was called on a value that is not an object"));
+ }
+ let on_finally = arg(args, 0);
+ if !interp.is_callable(&on_finally) {
+ return invoke(interp, &this, "then", &[on_finally.clone(), on_finally]);
+ }
+ scoped(interp, |interp| {
+ let rec = new_record(interp, Record::Finally { on_finally })?;
+ root(interp, &Value::Object(rec));
+ let then_finally = record_function(interp, Kind::ThenFinally, rec, 1)?;
+ root(interp, &then_finally);
+ let catch_finally = record_function(interp, Kind::CatchFinally, rec, 1)?;
+ root(interp, &catch_finally);
+ invoke(interp, &this, "then", &[then_finally, catch_finally])
+ })
+}
+
+/// Then Finally and Catch Finally (sections 25.6.5.3.1 and 25.6.5.3.2): calls the callback, then
+/// passes `value` on, or throws it again when `throws`, once the callback's result settles.
+fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult {
+ let rec_value = arg(args, 0);
+ let value = arg(args, 1);
+ let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) };
+ let on_finally = on_finally.clone();
+ let result = interp.call(&on_finally, &Value::Undefined, &[])?;
+ after_finally(interp, result, value, throws)
+}
+
+/// The steps of Then Finally and Catch Finally after the callback returned `result`: a promise
+/// that passes `value` on, or throws it again when `throws`, once `result` settles.
+fn after_finally(interp: &mut Interp, result: Value, value: Value, throws: bool) -> JsResult {
+ scoped(interp, |interp| {
+ root(interp, &value);
+ root(interp, &result);
+ let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object);
+ let promise = promise_resolve(interp, &ctor, result)?;
+ root(interp, &promise);
+ let rec = new_record(interp, Record::Thunk { value })?;
+ root(interp, &Value::Object(rec));
+ let thunk = record_function(interp, if throws { Kind::Thrower } else { Kind::ValueThunk }, rec, 0)?;
+ root(interp, &thunk);
+ invoke(interp, &promise, "then", &[thunk])
+ })
+}
+
+/// When `handler` is the Then Finally or Catch Finally function of a `finally` call, its callback,
+/// and whether the function throws the value it gets again.
+fn finally_callback(interp: &Interp, handler: &Value) -> Option<(Value, bool)> {
+ let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else {
+ return None;
+ };
+ let natives = &interp.promises.natives;
+ let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) {
+ false
+ } else if natives.get(Kind::CatchFinally as usize) == Some(target) {
+ true
+ } else {
+ return None;
+ };
+ match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) {
+ Some(Class::PromiseRecord(rec)) => match &**rec {
+ Record::Finally { on_finally } => Some((on_finally.clone(), throws)),
+ _ => None,
+ },
+ _ => None,
+ }
+}
+
+fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
+ finally_step(interp, args, false)
+}
+
+fn catch_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
+ finally_step(interp, args, true)
+}
+
+fn thunk_value(interp: &mut Interp, args: &[Value]) -> JsResult {
+ match record(interp, &arg(args, 0))? {
+ Record::Thunk { value } => Ok(value.clone()),
+ _ => Err(Abrupt::Internal("not a thunk record".into())),
+ }
+}
+
+fn value_thunk(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
+ thunk_value(interp, args)
+}
+
+fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
+ Err(Abrupt::Throw(thunk_value(interp, args)?))
+}
+
+/// `v` is a constructor: a function written in JavaScript other than an arrow function or a
+/// method, a built-in constructor, or a bound function whose target is one.
+fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult {
+ let mut v = v.clone();
+ loop {
+ let func = match v.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) {
+ Some(Class::Function(f)) => f.clone(),
+ _ => return Ok(false),
+ };
+ match func {
+ Func::Closure { code, .. } => return Ok(!code.arrow && !code.method),
+ Func::Native { constructor, .. } => return Ok(constructor),
+ Func::Bound { target, .. } => {
+ interp.use_fuel()?;
+ v = Value::Object(target);
+ }
+ _ => return Ok(false),
+ }
+ }
+}
+
+/// The `this` value of a static method, which must be a constructor.
+fn this_constructor(interp: &mut Interp, this: &Value, name: &str) -> JsResult<()> {
+ if is_constructor(interp, this)? {
+ return Ok(());
+ }
+ Err(interp.type_error(&format!("Promise.{name} was called on a value that is not a constructor")))
+}
+
+/// `Promise.resolve` (section 25.6.4.6).
+fn promise_resolve_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult {
+ this_constructor(interp, &this, "resolve")?;
+ promise_resolve(interp, &this, arg(args, 0))
+}
+
+/// `Promise.reject` (section 25.6.4.5).
+fn promise_reject_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult {
+ this_constructor(interp, &this, "reject")?;
+ scoped(interp, |interp| {
+ let p = new_promise(interp)?;
+ root(interp, &Value::Object(p));
+ let site = here(interp);
+ reject_promise(interp, p, arg(args, 0), site)?;
+ Ok(Value::Object(p))
+ })
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Combine {
+ All,
+ AllSettled,
+ Race,
+}
+
+impl Combine {
+ fn name(self) -> &'static str {
+ match self {
+ Combine::All => "all",
+ Combine::AllSettled => "allSettled",
+ Combine::Race => "race",
+ }
+ }
+}
+
+fn promise_all(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult