Merge main into fix/native-geometry-accordion-replay

This commit is contained in:
dotCooCoo committed 2026-11-26 09:47:05 -08:00
commit 577778693e
246 files changed
+16386 -1177

No files matched your search

Generated
+307 -24
View File
@@ -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"
+4
View File
@@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services {
open_in_application: Some(Box::new(open_in_application)),
// File → Print: the system's printers and print queue.
print: Some(Box::new(printing::SystemPrint)),
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
// only while the active tool uses the wheel.
#[cfg(all(windows, not(target_vendor = "win7")))]
stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)),
..Default::default()
}
}
+1
View File
@@ -74,6 +74,7 @@ mod windows_cores;
mod windows_display_size;
mod windows_stylus;
mod windows_symbol_chars;
mod windows_wintab;
mod xwayland;
use std::sync::{Arc, Mutex};
+2 -1
View File
@@ -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);
}
}
+134 -15
View File
@@ -1,7 +1,8 @@
//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
//! barrel button and which end of the pen is down. For each pointer message of a pen,
//! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its
//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]):
//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's
//! [`PenSource`] ([`start`]):
//! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is
//! pressed") is the eraser end
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
@@ -24,9 +25,12 @@
//! `rotation` in degrees 0..359 clockwise
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
//! Toward the user is down the screen, so they are the sample's axes and direction as they come,
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel.
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which
//! comes from the tablet driver's Wintab interface instead, when it has one
//! ([`crate::windows_wintab`]).
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::Cell;
use std::sync::OnceLock;
use craft::behavior::PointerSample;
@@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
/// detection range.
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled.
const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000;
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
const PEN_FLAG_INVERTED: u32 = 0x0002;
const PEN_FLAG_ERASER: u32 = 0x0004;
@@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A;
/// A pen's tilt along x and y and its barrel rotation, in radians.
type Pose = ([f32; 2], f32);
thread_local! {
/// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that
/// took them, or the pen whose message last asked for the wheel when none has
/// ([`crate::windows_wintab::wheel_pen`]).
static WHEEL_PEN: Cell<Option<u32>> = const { Cell::new(None) };
}
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
static FEED: OnceLock<PenSource> = OnceLock::new();
@@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
let Some(pen) = FEED.get() else {
return false;
};
crate::windows_wintab::msg_hook(msg);
if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) {
crate::windows_wintab::forget();
}
let read_pen = || {
let mut info = POINTER_PEN_INFO::default();
let id = (msg.wParam.0 & 0xffff) as u32;
// SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a
// pointer that is not a pen.
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
unsafe { GetPointerPenInfo(id, &mut info) }.ok()?;
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser);
WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id)));
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel))
};
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
@@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
/// pressed; and how it is held, `pose` ([`pen_pose`]).
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample {
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
/// within 0..1 and none when it is not a number.
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<f32>) -> PointerSample {
let pressure = match pressure {
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
_ if in_contact => 1.0,
@@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t
sample.tilt = tilt;
sample.rotation = rotation;
sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0));
sample
}
@@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose {
([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn)
}
/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message
/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the
/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another
/// pen leaving keeps the readings.
fn forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
if pen != Some((wparam & 0xffff) as u32) {
return false;
}
let flags = wparam >> 16;
match message {
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => {
flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0
}
WM_POINTERLEAVE => true,
_ => false,
}
}
/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook
/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and
/// `WM_POINTERLEAVE` are sent
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>); the posted pointer
/// messages are left to [`msg_hook`].
fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen)
}
/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on
/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as
/// [`msg_hook`] does for the messages it sees.
#[cfg(windows)]
pub fn sent_message(message: u32, wparam: usize) {
if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) {
crate::windows_wintab::forget();
}
}
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
/// not from a pen or a touch.
fn is_mouse(extra_info: u32) -> bool {
@@ -175,7 +236,7 @@ mod tests {
#[test]
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser;
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser;
assert!(!eraser(0), "the tip");
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
@@ -194,19 +255,77 @@ mod tests {
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel");
assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges");
let pose = pen_pose(all, 10, 20, 180);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None);
assert_eq!((sample.tilt, sample.rotation), pose);
}
#[test]
fn an_airbrush_wheel_goes_into_the_sample() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25));
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
let pose = pen_pose(all, 10, 20, 180);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75));
assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation");
assert_eq!(sample.pressure, 0.5, "the pressure as before");
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel");
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number");
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1");
}
#[test]
fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() {
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7;
let pen = Some(7);
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert!(!forgets_wheel(m, in_range, pen), "{m:#x}");
assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}");
assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}");
}
assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen));
// WM_MOUSEMOVE and WT_PACKET.
assert!(!forgets_wheel(0x0200, 0, Some(0)));
assert!(!forgets_wheel(0x7FF0, 7, pen));
}
#[test]
fn another_pointer_leaving_keeps_the_wheel() {
// A touch, pointer 9, leaves the window and detection range while pen 7 hovers.
let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9;
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7)));
assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range");
let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9;
assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled");
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel");
assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself");
}
#[test]
fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() {
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let pen = Some(7);
assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window");
assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range");
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves");
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel");
assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window");
// Posted messages, which the message hook already sees.
for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}");
}
// WT_CTXCLOSE.
assert!(!sent_forgets_wheel(0x7FF2, 7, pen));
}
#[test]
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
}
#[test]
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="13" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="11" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 321 B

After

Width:  |  Height:  |  Size: 323 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 8H12A4 4 0 0 1 12 16H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M12 4V20" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M2 7H13A5 5 0 0 1 13 17H2Z" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 318 B

After

Width:  |  Height:  |  Size: 319 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="17" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="16" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 321 B

After

Width:  |  Height:  |  Size: 323 B

+1 -2
View File
@@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
let mut ends = vec![0.0];
for ch in 0..3 {
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) {
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
+6 -2
View File
@@ -406,8 +406,10 @@ impl Document {
/// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A
/// line at any other angle becomes a guide path with that line, on the guide's layer, named
/// as the guide was; `sel` then holds the path as a selected object instead of the guide.
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are.
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) {
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. Returns the ids
/// of the guide paths it adds, in the order it adds them.
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) -> Vec<NodeId> {
let mut paths = vec![];
for id in sel.guides.clone() {
let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue };
let (a, b) = match self.transformed_guide(&g, xf) {
@@ -431,7 +433,9 @@ impl Document {
}
self.retain_guides(sel, |g| g.id != Some(id));
sel.objects.push(path);
paths.push(path);
}
paths
}
/// The ruler guide node `g` names, if this document has it.
+27 -5
View File
@@ -131,6 +131,13 @@ impl Node {
matches!(self.kind, NodeKind::Layer { template: true, .. })
}
/// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this
/// object out: a template layer while templates are hidden, or a path made into a guide while
/// guides are hidden. The canvas draws ruler guides apart from the art.
pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool {
(templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. }))
}
/// The art objects of this container: its children, looking through sublayers, which are not
/// objects (bottom first). With `editable`, only the visible, unlocked objects in visible,
/// unlocked, non-template sublayers.
@@ -360,17 +367,32 @@ impl Node {
self.geometric(Some(symbols))
}
/// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a
/// hidden bitmap for re-tracing/release; only source-image views measure that bitmap.
/// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for
/// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline
/// [`Node::drawn_children`].
pub fn editing_children(&self) -> &[Arc<Node>] {
let children = self.children().map(Vec::as_slice).unwrap_or_default();
let trace_source = self.extras().trace.is_some()
&& !self.trace_view().shows_source()
&& children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_)));
let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible);
let skip = usize::from(self.extras().shaper.is_some() || trace_source);
children.get(skip..).unwrap_or_default()
}
/// The children a selection highlight outlines: [`Node::editing_children`] without the hidden
/// members, which the canvas does not draw. An Image Trace object's hidden source image stays
/// when the object's view shows it, and every path of a compound path stays, since the compound
/// path draws all of them.
pub fn drawn_children(&self) -> impl Iterator<Item = &Arc<Node>> {
let members = !matches!(self.kind, NodeKind::Compound { .. });
let source = self.trace_source().filter(|_| self.trace_view().shows_source());
self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)))
}
/// The first child of an Image Trace object when it is an image: the bitmap the trace keeps.
fn trace_source(&self) -> Option<&Arc<Node>> {
self.extras().trace.as_ref()?;
self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_)))
}
/// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols`
/// is given.
pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
+30 -2
View File
@@ -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) {
+4
View File
@@ -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,
+215
View File
@@ -0,0 +1,215 @@
//! The ranges the character and paragraph style commands keep each numeric attribute to, checked
//! in one place: the style commands check the attributes a call changes, and type a plug-in
//! returns has every attribute checked.
use std::fmt;
use std::ops::RangeInclusive;
use super::{CharStyle, JustificationOptions, ParaStyle, TabStop};
/// Font size ([`CharStyle::size`]), in points.
pub const FONT_SIZE: RangeInclusive<f64> = 0.1..=1296.0;
/// Leading ([`CharStyle::leading`]) other than Auto, in points.
pub const LEADING: RangeInclusive<f64> = 0.1..=5000.0;
/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
pub const CHAR_SCALE: RangeInclusive<f64> = 1.0..=10000.0;
/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`],
/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em.
pub const CHAR_SPACING: RangeInclusive<f64> = -1000.0..=10000.0;
/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points.
pub const MAX_BASELINE_SHIFT: f64 = 1296.0;
/// Character rotation ([`CharStyle::rotation`]), in degrees.
pub const CHAR_ROTATION: RangeInclusive<f64> = -360.0..=360.0;
/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
pub const CHAR_MITER_LIMIT: RangeInclusive<f64> = 1.0..=500.0;
/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points.
pub const MAX_PARA_DISTANCE: f64 = 1296.0;
/// An attribute outside the range the style commands keep it to.
#[derive(Clone, Debug, PartialEq)]
pub struct AttrRangeError {
/// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`).
pub key: String,
/// What is wrong, naming the attribute.
pub message: String,
}
impl fmt::Display for AttrRangeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for AttrRangeError {}
fn out(key: &str, message: String) -> AttrRangeError {
AttrRangeError { key: key.to_string(), message }
}
/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside).
fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> {
if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) }
}
impl CharStyle {
/// Checks each numeric attribute `check` names, by its JSON key, against the range the
/// character style commands keep it to: size, leading, scales, tracking, kerning, baseline
/// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert
/// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the
/// variable font axes. The first attribute out of its range is the error.
pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> {
for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] {
if check(key) {
within(key, value, *range.start(), *range.end())?;
}
}
if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) {
let (lo, hi) = (LEADING.start(), LEADING.end());
return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto")));
}
let shift = MAX_BASELINE_SHIFT;
for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] {
if check(key) {
within(key, value, -shift, shift)?;
}
}
let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))];
for (key, value) in spacing {
if check(key)
&& let Some(value) = value
{
within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?;
}
}
if check("rotation") {
within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?;
}
for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] {
if check(key) {
within(key, value, 0.0, super::MAX_AKI)?;
}
}
if check("tsume") {
within("tsume", self.tsume, 0.0, super::MAX_TSUME)?;
}
let hi = super::MAX_DIACRITIC_POSITION;
for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] {
if check(key) {
within(key, value, -hi, hi)?;
}
}
let lines = super::WARICHU_LINES;
if check("warichuLines") && !lines.contains(&self.warichu_lines) {
return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
}
let scale = super::WARICHU_SCALE;
for (key, value, lo, hi) in
[("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())]
{
if check(key) {
within(key, value, lo, hi)?;
}
}
if check("stroke_width") {
within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?;
}
if check("stroke_miter_limit") {
within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?;
}
if check("stroke_dash")
&& let Some(dash) = &self.stroke_dash
{
for value in &dash.pattern {
within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?;
}
within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?;
}
if check("small_caps")
&& let Some(value) = self.small_caps
{
within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?;
}
if check("fontAxes")
&& let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite())
{
return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number")));
}
Ok(())
}
}
impl ParaStyle {
/// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its
/// field, against the range the paragraph style commands keep it to: the indents and the space
/// before and after, each Hyphenation option, each Justification option in `justification`
/// (the options as given, since reading a paragraph style brings them into range) with
/// Minimum, Desired and Maximum in order, and the number of tab stops with the position and
/// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the
/// error.
pub fn check_ranges(
&self,
justification: Option<&JustificationOptions>,
kept_tabs: &[TabStop],
check: impl Fn(&str, Option<&str>) -> bool,
) -> Result<(), AttrRangeError> {
for (key, value) in [
("left_indent", self.left_indent),
("right_indent", self.right_indent),
("first_line_indent", self.first_line_indent),
("space_before", self.space_before),
("space_after", self.space_after),
] {
if check(key, None) {
within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?;
}
}
let h = &self.hyphenation;
for (field, value, lo, hi) in [
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
("after_first", f64::from(h.after_first), 1.0, 15.0),
("before_last", f64::from(h.before_last), 1.0, 15.0),
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
("zone", h.zone, 0.0, MAX_PARA_DISTANCE),
] {
if check("hyphenation", Some(field)) {
within(&format!("hyphenation.{field}"), value, lo, hi)?;
}
}
if let Some(j) = justification {
for (field, values, (lo, hi)) in [
("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING),
("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING),
("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING),
] {
if !check("justification", Some(field)) {
continue;
}
let name = format!("justification.{field}");
for value in values {
within(&name, value, lo, hi)?;
}
if !(values[0] <= values[1] && values[1] <= values[2]) {
return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
}
}
if check("justification", Some("auto_leading")) {
let (lo, hi) = JustificationOptions::AUTO_LEADING;
within("justification.auto_leading", j.auto_leading, lo, hi)?;
}
}
if check("tabs", None) {
let max = TabStop::MAX_STOPS;
if self.tabs.len() > max.max(kept_tabs.len()) {
return Err(out("tabs", format!("at most {max} tab stops")));
}
for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
if stop.leader.chars().count() > max {
return Err(out("tabs.leader", format!("{label} must be at most {max} characters")));
}
}
}
Ok(())
}
}
+39
View File
@@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() {
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
}
/// The default character and paragraph styles are in range, and each number outside its range,
/// one that is not a number included, is the error naming its attribute; an attribute the check
/// is not asked about is not checked.
#[test]
fn style_ranges_name_the_attribute_out_of_range() {
let all = |_: &str| true;
assert_eq!(CharStyle::default().check_ranges(all), Ok(()));
let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key);
let d = CharStyle::default();
assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into()));
assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into()));
assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into()));
assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into()));
assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into()));
assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into()));
assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into()));
assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into()));
let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect();
assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into()));
let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false });
assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into()));
assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(()));
let all = |_: &str, _: Option<&str>| true;
let p = ParaStyle::default();
assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(()));
let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key);
assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into()));
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into()));
let far = TabStop { position: -1.0, ..stop.clone() };
assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into()));
assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop");
let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() };
assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into()));
let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() };
assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into()));
}
#[test]
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
use super::file_fonts::*;
+3 -3
View File
@@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"stylize.dropShadow",
"Drop Shadow…",
STYLIZE,
"{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
"{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}),
),
r(
"stylize.innerGlow",
"Inner Glow…",
STYLIZE,
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}),
),
r(
"stylize.outerGlow",
"Outer Glow…",
STYLIZE,
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
),
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
+3 -2
View File
@@ -82,11 +82,12 @@ pub use group::{
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use placement::pinned_gradient_item;
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
without_geometry,
RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps,
staged_effects, without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
+22
View File
@@ -1,6 +1,28 @@
use vectorcraft_doc::color::BlendMode;
use super::catalog::{catalog_index, plugin_info};
use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util};
/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in.
pub fn takes_blend_mode(effect: &str, key: &str) -> bool {
key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow")
}
/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode.
pub fn parse_blend_mode(s: &str) -> Option<BlendMode> {
let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
BlendMode::parse(&name)
}
/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`.
pub fn blend_mode_id(mode: BlendMode) -> String {
let mut name = format!("{mode:?}");
if let Some(first) = name.get_mut(..1) {
first.make_ascii_lowercase();
}
name
}
/// Dialog defaults for `id` (`None` for unknown effects).
pub fn default_params(id: &str) -> Option<Value> {
match catalog_index().get(id) {
+17
View File
@@ -80,11 +80,28 @@ rustix = { workspace = true, features = ["std", "process"] }
# (walkdir), so this adds no new crate.
[target.'cfg(windows)'.dependencies]
same-file = "1.0.6"
# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below).
windows-native-keyring-store = "1.1"
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
rayon = { version = "1.12", optional = true }
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
# Linux. All MIT OR Apache-2.0.
hmac = "0.12.1"
sha2 = { version = "0.10", default-features = false }
getrandom = "0.4"
keyring-core = "1.1"
# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same
# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0.
[target.'cfg(target_os = "macos")'.dependencies]
apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies]
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
[dev-dependencies]
# JPEG XL files for the `.jxl` open and place tests.
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Parametric Shape",
[],
None,
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
has_doc,
set
),
@@ -1172,6 +1172,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
}
/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where
/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it
/// back.
#[test]
fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() {
let mut s = session();
let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("tangentCircle", view).unwrap();
s.set_tool_option("addPoints", &json!(true));
let n = steps(&s);
for (kind, x, y) in
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
{
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
assert_eq!(steps(&s), n + 1, "one undo step");
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6)
};
assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a));
assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b));
let st = s.doc().unwrap();
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap();
assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2));
assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too");
}
/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the
/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected.
#[test]
fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() {
let mut s = session();
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false);
select(&mut s, &[other]);
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("tangentCircle", view).unwrap();
s.set_tool_option("addPoints", &json!(true));
for (kind, x, y) in
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
{
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
let st = s.doc().unwrap();
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index));
let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") };
assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}");
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
+1 -1
View File
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill Area",
[],
None,
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
has_doc,
sb_copy_region
),
+4 -3
View File
@@ -141,7 +141,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Contrast",
[],
None,
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
always,
contrast
),
@@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
.transpose()
};
let drawing;
// Selected objects that share a color but draw it differently have no one answer.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) {
// Selected objects that share a color but draw it differently have no one answer. While the
// active tool paints with the proxy's color, the selection does not draw it.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) {
let item = s.appearance_item();
// Every painted object inside a selected group counts, as the proxy's color comes from all,
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
+28 -5
View File
@@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
/// from. → a note for each profile, and whether `d` changed.
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
// Without a choice nothing can fail.
apply_open_policies_choosing(d, None).unwrap_or_default()
apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default()
}
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
@@ -879,10 +879,14 @@ impl ProfileQuestion {
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
/// choice tags the document after the policies ran. A choice for the other kind of question, or
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
/// to assign is not a profile of that model.
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
let working = cms::working_settings();
let question = ProfileQuestion::of(d, &working);
/// to assign is not a profile of that model. `working` is the settings snapshot the question is
/// built from and the policies are read from.
pub(crate) fn apply_open_policies_choosing(
d: &mut vectorcraft_doc::Document,
choice: Option<&ProfileChoice>,
working: &ColorSettings,
) -> Result<(Vec<String>, bool)> {
let question = ProfileQuestion::of(d, working);
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
// A mismatch answer stands in for the policy of the document's color mode.
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
@@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"name": name, "spot": spot}))
}
#[cfg(test)]
mod tests {
use super::*;
/// The policies come from the settings snapshot the question was built from, not from the
/// working settings as they are when the policies run.
#[test]
fn open_policies_use_the_snapshot_they_are_given() {
let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string());
let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() };
let mut d = vectorcraft_doc::Document::new(100.0, 100.0);
tagged(&mut d);
let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap();
assert!(changed, "the Off policy of the snapshot takes the profile off");
assert_eq!(d.color_profiles.rgb, None);
assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}");
}
}
+8 -3
View File
@@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption
}
}
/// The effect an apply request names, including the older `id` parameter.
pub(crate) fn requested_effect(p: &Value) -> Option<&str> {
str_param(p, "effect").or_else(|| str_param(p, "id"))
}
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one.
/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.apply";
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?;
// An effect given as `id` names no objects: the targets are read with that `id` as null.
let effect_as_id;
let p = if str_param(p, "effect").is_none() {
+1 -1
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d Line truncated
has_doc,
export::export
),
+28
View File
@@ -256,6 +256,11 @@ struct RasterOptions {
dither: Option<String>,
dither_amount: Option<u8>,
transparency: Option<bool>,
/// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by
/// [`RasterOptions::transparency_dither`] (other formats do not check it).
transparency_dither: Option<Value>,
/// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is.
transparency_dither_amount: Option<Value>,
matte: Option<Value>,
lossless: Option<bool>,
lzw: Option<bool>,
@@ -295,6 +300,26 @@ impl RasterOptions {
}
}
/// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not
/// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error.
fn transparency_dither(&self) -> Result<(Dither, u8)> {
const IDS: &str = "none, diffusion, pattern or noise";
let method = match &self.transparency_dither {
None | Some(Value::Null) => PaletteOptions::default().transparency_dither,
Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?,
Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))),
};
let amount = match &self.transparency_dither_amount {
None | Some(Value::Null) => 100,
Some(v) => v
.as_u64()
.filter(|n| *n <= 100)
.and_then(|n| u8::try_from(n).ok())
.ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?,
};
Ok((method, amount))
}
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
let checked = |key: &str, n: f64| {
@@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
{
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
}
if matches!(format, RasterFormat::Gif | RasterFormat::Png8) {
(settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?;
}
check_options(format, &settings)?;
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
let chosen = match use_artboards {
+16
View File
@@ -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,
];
+4 -2
View File
@@ -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);
+77 -1
View File
@@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() {
}
}
/// The shares of opaque pixels in the left and right halves of a 40×30 image file.
fn opaque_halves(file: &[u8]) -> [f64; 2] {
let img = craft_image_codecs::decode(file).unwrap();
assert_eq!(img.dimensions(), (40, 30));
let alpha: Vec<u8> = img.to_rgba8().chunks(4).map(|p| p[3]).collect();
[0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0)
}
/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`.
#[test]
fn palette_exports_take_the_transparency_dither() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();
s.execute("transparency.set", &json!({"opacity": 25})).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap();
s.execute("transparency.set", &json!({"opacity": 75})).unwrap();
for format in ["gif", "png8"] {
let mut file = |extra: Value| {
let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra);
b64(&s.execute("document.export", &p).unwrap())
};
// By default the pixels under half opacity are transparent and the others opaque.
let none = file(json!({}));
assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}");
assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}");
assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
for method in ["diffusion", "pattern", "noise"] {
let dithered = file(json!({"transparencyDither": method}));
let [left, right] = opaque_halves(&dithered);
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
// Without transparency the dither does nothing.
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}");
}
let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})));
assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}");
// null is the same as leaving a key out.
assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}");
for bad in [
json!({"transparencyDither": "spray"}),
json!({"transparencyDither": 3}),
json!({"transparencyDitherAmount": 101}),
json!({"transparencyDitherAmount": -1}),
json!({"transparencyDitherAmount": "50"}),
json!({"transparencyDitherAmount": 50.5}),
] {
assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}");
}
let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string();
assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}");
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string();
assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}");
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string();
assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}");
}
// Formats without a palette do not read the keys: their values are not checked, and the
// warnings name them.
for format in ["png", "jpg", "tiff"] {
for keys in [
json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}),
json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}),
] {
let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone()));
let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string();
assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}");
}
}
}
#[test]
fn palette_formats_reach_export_as_and_screens() {
let mut s = session();
@@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() {
let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone();
assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false)));
assert_eq!(f("gif")["write"], true);
for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] {
for k in
["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"]
{
assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}");
}
assert_eq!(format_for_name("a.png").unwrap().id, "png");
+6 -3
View File
@@ -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)
})?
+1 -1
View File
@@ -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] = [
+20 -3
View File
@@ -34,7 +34,8 @@
//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names
//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown
//! shadow or glow blend mode, which the effect draws as Normal.
use std::collections::HashMap;
use std::sync::OnceLock;
@@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> {
/// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the
/// effect takes (those of its dialog defaults and of its params description), each of the type
/// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`])
/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range
/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or
/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range
/// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its
/// manifest, and an unknown effect is the command's to report.
pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> {
@@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) {
return Err(unknown(id, key, &keys));
}
check_effect_blend(id, effect, params)?;
check_effect_types(id, effect, params)?;
// An SVG filter's XML is one drawable <filter> element.
if effect == vectorcraft_render::effects::SVG_FILTER
@@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re
Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", "))))
}
/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was
/// given it: a parameter error naming the blend modes unless the effect reads it as one
/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal.
fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> {
use vectorcraft_render::effects;
let key = "mode";
let Some(v) = params.get(key) else { return Ok(()) };
if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() {
return Ok(());
}
let modes: Vec<String> = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect();
Err(bad(id, format!("`{key}` must be one of {}", modes.join(", "))))
}
/// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id`
/// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's
/// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they
@@ -1067,7 +1084,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> {
fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
let Some(spec) = find_command(id) else { return Ok(()) };
if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) =
(id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params"))
(id, super::effectcmd::requested_effect(params), params.get("params"))
{
check_effect_params(id, effect, given)?;
}
+3 -6
View File
@@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res
/// [`transform_selected`] on the active document's selection, as one undo step `label`. A
/// transform other than a move also transforms the selected ruler guides
/// ([`Document::transform_ruler_guides`]).
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds.
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<Vec<NodeId>> {
let sel = s.doc()?.selection.clone();
// As [`transform_selected`] tells a move apart, which moves the guides itself.
let c = xf.as_coeffs();
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
s.edit(label, |doc, live| {
transform_selected(doc, &sel, xf, sc, interpolate)?;
if !is_translation {
doc.transform_ruler_guides(live, xf);
}
Ok(())
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
})
}
+126 -28
View File
@@ -42,7 +42,9 @@
//!
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds
//! among them it may change: type's runs and paragraph styles, an image's transform and opacity,
//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]).
//!
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
//! also given the parts of the active document it names in `_context.document`, whether or not
@@ -53,7 +55,7 @@ use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Document, Effect, Node};
use vectorcraft_doc::{Document, Effect, Node, NodeKind};
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
@@ -113,6 +115,9 @@ pub fn describe(p: &Plugin) -> Value {
if !m.inputs.is_empty() {
v["inputs"] = json!(m.inputs);
}
if !m.writes.is_empty() {
v["writes"] = json!(m.writes);
}
if !m.context.is_empty() {
v["context"] = json!(m.context);
}
@@ -377,7 +382,7 @@ impl FilterRun {
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?;
if out.document_data.is_some() && !may.contains(&Permission::State) {
return Err(not_granted(&m.name, Permission::State));
}
@@ -393,18 +398,52 @@ impl FilterRun {
if s.script_running() {
return Err(EngineError::Busy);
}
if !s.previewing && super::typing_in_progress(s) {
// Typing whose text Real-time Drawing off left out of the document isn't in what the
// plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it
// before the run is prepared).
if unapplied_typing(s) {
return Err(err(vectorcraft_plugins::Error::Output(
"typing in progress isn't in what the plug-in was given: nothing was changed".into(),
)));
}
let data = out.document_data;
// The output applied to `now`, with the checks that refuse it.
let build = |now: &Document, objects: Vec<objects::OutObject>| -> Result<(Document, Vec<NodeId>)> {
let mut d = now.clone();
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
}
// Type whose text the output changed is laid out again.
let retyped: Vec<NodeId> = ids
.iter()
.copied()
.filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) {
(Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para,
_ => false,
})
.collect();
super::typecmd::refresh_bounds_of(&mut d, &retyped);
if let Some(data) = data.clone() {
d.set_plugin_data(&m.id, data);
}
Ok((d, ids))
};
// Typing in progress, its text already in the document, is kept as `s.edit` keeps it once
// nothing can refuse the output, so a refused output leaves it in progress. Keeping it can
// change the document, and the output is then applied to the document as kept.
let typing = !s.previewing && super::typing_in_progress(s);
let again = typing.then(|| out.objects.clone());
let mut now = s.doc()?.doc.clone();
let (mut d, mut ids) = build(&now, out.objects)?;
if let Some(objects) = again {
super::settle_interaction(s)?;
}
let now = s.doc()?.doc.clone();
let mut d = (*now).clone();
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
let kept = s.doc()?.doc.clone();
if !Arc::ptr_eq(&kept, &now) {
now = kept;
(d, ids) = build(&now, objects)?;
}
}
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
@@ -447,6 +486,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError {
err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed")))
}
/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a
/// preview's run)? A run prepared now isn't given that text.
pub fn unapplied_typing(s: &Session) -> bool {
!s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some()
}
/// Keeps typing in progress whose text Real-time Drawing off left out of the document
/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the
/// typed text; one prepared before it is prepared again.
pub fn keep_unapplied_typing(s: &mut Session) -> Result<bool> {
if !unapplied_typing(s) {
return Ok(false);
}
super::settle_interaction(s)?;
Ok(true)
}
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
/// parameters and `_context` (what it keeps with the document included), and applies its output as
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with
@@ -464,6 +520,8 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r };
return r.run_with_calls(s);
}
// Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it.
let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r };
// Handed in for this very run (the app ran it in the background), it is what running the
// plug-in again would return.
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
@@ -887,6 +945,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
};
return r.run_with_calls(s).map_err(failed);
}
let r = match keep_unapplied_typing(s)? {
true => {
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
FilterRun::prepare_with(s, plugin, Some(command), id, p)?
}
false => r,
};
let output = r.run().map_err(&failed)?;
r.finish(s, &output).map_err(failed)
}
@@ -1808,18 +1873,49 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let installed = registry::get(id).is_some();
// Settings and cache the store keeps for an id that isn't installed are deleted too.
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
// Installed again, it asks again. A grant that can't be removed still approves the module, and
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
// list approves nothing and doesn't stop the removal.
let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id);
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
// tries again.
// A module stored for an id that isn't installed (one no grant covers is skipped at startup)
// counts as removed once its file is gone.
let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id);
// An installed plug-in's stored module is deleted with its grant too, so that one that can't be
// deleted leaves the plug-in installed. Without a plug-in folder it has none.
let unstore = module || (installed && s.plugin_dir.is_some());
// The grant the store keeps for an installed plug-in, which may differ from the one the session
// holds (an update whose module couldn't be stored): written back when its module can't be
// deleted, so that the stored module still loads at the next launch.
let kept_grant = if installed { s.stored_plugin_grant(id) } else { None };
let module_left = std::cell::Cell::new(false);
let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default());
// Installed again, it asks again. A grant that can't be removed may still approve the module, and
// so may a grants file that can't be opened or read, or a signed copy of the file put back when
// the generation couldn't be raised (the key store can't be reached). Without a plug-in folder
// nothing keeps a grant. The stored module is deleted next, while its settings and cache can
// still be moved back.
let forget = || {
if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() {
return false;
}
let deleted = !unstore || s.unstore_plugin(&turn, id);
if !deleted
&& let Some(grant) = kept_grant.clone()
&& !s.store_grant_in(&turn, id, Some(grant))
{
log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch");
}
module_left.set(!deleted);
deleted
};
// Its settings and cache are moved aside, its grant removed and its stored module deleted before
// anything else is deleted: when one of them can't be done, the settings and cache are moved back,
// the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id
// names no grant and no module.
let failed = if installed || stored {
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
} else {
} else if vectorcraft_plugins::manifest::valid_id(id) {
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
} else {
None
};
let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e });
if let Some(e) = failed {
if installed {
s.attach_plugin_storage(&turn, id);
@@ -1827,8 +1923,10 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other(e));
}
registry::revoke(id);
s.unstore_plugin(&turn, id);
if !stored && (!installed || !registry::remove(id)) {
if !s.unstore_plugin(&turn, id) && module {
return Err(EngineError::Other(cant_delete()));
}
if !stored && !module && (!installed || !registry::remove(id)) {
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
}
Ok(json!({"removed": id}))
@@ -1860,7 +1958,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1878,7 +1976,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
has_doc,
run
),
@@ -1887,7 +1985,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Install Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
always,
install
),
@@ -1905,7 +2003,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Plug-in",
[],
None,
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
always,
remove
),
+15 -7
View File
@@ -710,6 +710,12 @@ impl Prefs {
}
impl Session {
/// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a
/// reset of every category. A frontend resets the settings it keeps itself in them.
pub fn take_prefs_resets(&mut self) -> Vec<Option<&'static str>> {
std::mem::take(&mut self.prefs_resets)
}
/// Replace the preferences and push the ones with engine-side consumers into open documents
/// and the renderer (grid, history depth, render threads).
pub fn apply_prefs(&mut self, mut p: Prefs) {
@@ -817,7 +823,7 @@ pub fn specs() -> Vec<CommandSpec> {
always,
set
),
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset),
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
cmd!(
query "prefs.export",
@@ -1000,15 +1006,17 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
fn reset(s: &mut Session, p: &Value) -> Result<Value> {
let cat = str_param(p, "category");
if let Some(c) = cat
&& !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c))
{
return Err(bad("prefs.reset", format!("unknown category `{c}`")));
}
let cat = text_param(p, "category", "prefs.reset")?;
let known = |c: &str| {
PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`")))
};
let category = cat.map(known).transpose()?;
let mut next = s.prefs.clone();
next.reset(cat);
s.apply_prefs(next);
if !s.prefs_resets.contains(&category) {
s.prefs_resets.push(category);
}
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
}
+23 -128
View File
@@ -157,13 +157,13 @@ pub fn specs() -> Vec<CommandSpec> {
"charStyle",
"Character Styles",
"Character",
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings"
);
v.push(spec(
"charStyle.edit",
"Edit Character Style",
&[],
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
|s, p| edit_style(s, p, Kind::Char),
true,
));
@@ -636,52 +636,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
}
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
for (key, value, lo, hi) in
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
{
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
}
let shift_max = 1296.0;
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
}
}
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME);
if changed(key) && !(lo..=hi).contains(&st.tsume) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
let lo = -hi;
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
let lines = vectorcraft_doc::text::WARICHU_LINES;
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
}
let scale = vectorcraft_doc::text::WARICHU_SCALE;
for (key, value, lo, hi) in [
("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP),
("warichuScale", st.warichu_scale, *scale.start(), *scale.end()),
] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
st.check_ranges(changed).map_err(|e| bad(&c, e.message))?;
// A language of the list, stored as its tag (as text.setFormat takes it).
if let Some(l) = &st.language
&& kept.and_then(|k| k.get("language")) != m.get("language")
@@ -693,10 +648,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
style_paint(d, paint, key, &c)?;
}
}
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
if changed("features") {
style_features(&st.features, kept, &c)?;
}
@@ -753,85 +704,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
}
}
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
/// as `text.setFormat` keeps them.
const PARA_DISTANCE: f64 = 1296.0;
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
/// `kept` does not hold. A value `kept` has is not checked.
/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options
/// as `attrs` gives them. A value `kept` has is not checked.
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
let within = |key: &str, value: f64, lo: f64, hi: f64| {
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
};
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
let nested_changed = |key: &str, field: &str| {
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
let check = |key: &str, field: Option<&str>| match field {
None => changed(key),
Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)),
};
for (key, value) in [
("left_indent", st.left_indent),
("right_indent", st.right_indent),
("first_line_indent", st.first_line_indent),
("space_before", st.space_before),
("space_after", st.space_after),
] {
if changed(key) {
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
}
}
let h = &st.hyphenation;
for (field, value, lo, hi) in [
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
("after_first", f64::from(h.after_first), 1.0, 15.0),
("before_last", f64::from(h.before_last), 1.0, 15.0),
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
("zone", h.zone, 0.0, PARA_DISTANCE),
] {
if nested_changed("hyphenation", field) {
within(&format!("hyphenation.{field}"), value, lo, hi)?;
}
}
// Read as given: a paragraph's attributes keep justification options in range as they load.
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
for (field, values, (lo, hi)) in [
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
] {
if !nested_changed("justification", field) {
continue;
}
let name = format!("justification.{field}");
for value in values {
within(&name, value, lo, hi)?;
}
if !(values[0] <= values[1] && values[1] <= values[2]) {
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
}
}
if nested_changed("justification", "auto_leading") {
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
within("justification.auto_leading", j.auto_leading, lo, hi)?;
}
}
if changed("tabs") {
let kept_tabs = kept_tab_stops(kept);
let max = TabStop::MAX_STOPS;
if st.tabs.len() > max.max(kept_tabs.len()) {
return Err(bad(c, format!("at most {max} tab stops")));
}
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
if stop.leader.chars().count() > max {
return Err(bad(c, format!("{label} must be at most {max} characters")));
}
}
}
Ok(())
let given = attrs.get("justification").filter(|_| changed("justification"));
let justification: Option<vectorcraft_doc::JustificationOptions> =
given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?;
st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message))
}
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
@@ -1204,17 +1090,22 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps,
/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
/// `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 24] = [
const RANGED: [&str; 32] = [
"size",
"h_scale",
"v_scale",
"leading",
"tracking",
"kerning",
"kerningBefore",
"baseline_shift",
"rotation",
"akiLeft",
"akiRight",
"tsume",
@@ -1226,6 +1117,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
"warichuGap",
"warichuScale",
"stroke_width",
"stroke_miter_limit",
"stroke_dash",
"small_caps",
"fontAxes",
"left_indent",
"right_indent",
"first_line_indent",
+17 -4
View File
@@ -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"]);
}
+6 -2
View File
@@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection,
use super::edit::selected_roots;
use super::fileio::{absolute_path, read_file_head, write_file};
use super::textedit::set_story_text;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param};
use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links,
str_param,
};
mod csv;
mod library;
@@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "variable.unbind";
let ids = checked_ids_or_selection(s, p, C)?;
// Explicit bindings can include both a group and its children; retain every supplied ID.
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? };
let name = defined_variable(s, p, C)?;
let n = edit_variables(s, "Unbind Variable", |vars| {
let mut n = 0;
+1 -1
View File
@@ -248,7 +248,7 @@ impl History {
/// The document at row `row` of the History panel, `now` being the document now: the rows before
/// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first.
pub(crate) fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
pub fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
let current = self.undo.len();
match row.cmp(&current) {
std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc),
+2
View File
@@ -136,6 +136,8 @@ pub struct Session {
/// Set when a command that draws a shape was journaled outside saved steps
/// ([`Session::take_shape_drawn`]).
shape_drawn: bool,
/// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]).
prefs_resets: Vec<Option<&'static str>>,
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
tool_panic: Option<EngineError>,
/// How many times switching or closing documents, or replacing the active one, has started the
+65 -2
View File
@@ -772,6 +772,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Bool(open))
}
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
/// strings are the ones
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
/// lists, and `Fit Artboard to artwork bounds` is the one
/// <https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee> gives for Object ›
/// Artboards › Fit to Artwork Bounds.
const MENU_COMMANDS: &[(&str, &str)] = &[
("selectall", "select.all"),
("deselectall", "select.none"),
("group", "object.group"),
("ungroup", "object.ungroup"),
("makeMask", "object.clippingMask.make"),
("releaseMask", "object.clippingMask.release"),
("compoundPath", "object.compoundPath.make"),
("noCompoundPath", "object.compoundPath.release"),
("Fit Artboard to artwork bounds", "artboard.fitToArt"),
];
/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names
/// ([`MENU_COMMANDS`]) on the active document, as
/// <https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts> describes the method. A
/// name it does not list throws an error that names it. A menu item that is not available, with
/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does
/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error
/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does
/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims
/// the item then ([`DocState::any_art_to_fit`]).
fn app_menu_command(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) };
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the menu command is too long".into()));
}
let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else {
return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\"")));
};
let params = {
let s = h.session.borrow();
let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) };
if (spec.enabled)(&s).is_err() {
return Ok(Data::Undefined);
}
match (id, s.active()) {
("artboard.fitToArt", Some(st)) => {
let index = active_artboard(st);
if !st.any_art_to_fit(&[index]) {
return Ok(Data::Undefined);
}
json!({"index": index})
}
_ => json!({}),
}
};
command(h, id, &params)?;
Ok(Data::Undefined)
}
// ---- Documents ----
fn docs_length(h: &Host, _: &[Data]) -> Answer {
@@ -1303,6 +1359,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
d => vec![d],
};
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
// The document is read once for every object: nothing changes it while the list is checked.
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
let locks = d.locked_artboards();
@@ -1317,7 +1374,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
}
if !ids.contains(&item.id) {
if seen.insert(item.id) {
ids.push(item.id);
}
}
@@ -1378,6 +1435,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("PageItems"))
}
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
items_doc(h, a)?;
Ok(text("[PageItems]"))
}
fn items_parent(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
@@ -2085,6 +2147,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("selection", property(l, app_selection, app_set_selection)),
("coordinateSystem", property(l, app_coords, app_set_coords)),
("getIsFileOpen", method(l, app_is_open)),
("executeMenuCommand", method(l, app_menu_command)),
("toString", class_text("Application")),
]);
application.push(later(l, "Application", "beep"));
@@ -2148,7 +2211,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("index", method(l, items_index)),
("getByName", method(l, items_by_name)),
("removeAll", method(l, items_remove_all)),
("toString", class_text("PageItems")),
("toString", method(l, items_to_string)),
]),
Some(function(l, items_at)),
));
+59 -8
View File
@@ -1649,24 +1649,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in,
/// with that file's name unless it is the run's own script.
fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<str>>) {
let map = |m: &include::SourceMap| {
let (index, file, line, column) = m.locate(e.line, e.column);
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
};
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
// file's place.
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
}
placed(host, e, realm.error_source(), realm.error_tag())
}
/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`]
/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name
/// unless it is the run's own script.
fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option<Arc<str>>) {
let map = |m: &include::SourceMap| {
let (index, file, line, column) = m.locate(e.line, e.column);
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
};
if e.line == 0 {
return (e.clone(), None);
}
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
// is given without a place.
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
match realm.error_source() {
match source {
0 => {
let (e, index, file) = map(&host.script_map.borrow());
(e, (index > 0).then_some(file))
@@ -1683,7 +1690,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
// `$.evalFile` gave. A script given as text is named by that run's name.
_ => {
let kept = host.kept_maps.as_ref().map(|k| k.borrow());
match kept.as_ref().and_then(|k| k.get(realm.error_tag())) {
match kept.as_ref().and_then(|k| k.get(tag)) {
Some(kept) => {
let (e, index, file) = map(&kept.map);
let file = match &kept.script {
@@ -2025,7 +2032,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;
@@ -2034,6 +2042,9 @@ impl Session {
Some(mut realm) => {
realm.set_limits(limits);
realm.set_es2015(es2015);
if es2015 {
realm.add_es2015();
}
realm
}
None => {
@@ -2338,6 +2349,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());
@@ -2383,6 +2399,29 @@ const NO_RUN: &str = "this function's script run has ended";
const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped";
const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web";
const ENGINE_BUSY: &str = "the script engine is in use by another run";
const UNHANDLED_REJECTION: &str = "unhandled promise rejection";
const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections";
/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when
/// known, the line, column and file it was rejected at.
fn rejections_report(host: &Host, realm: &Realm) -> Vec<Value> {
let mut out = Vec::new();
for r in realm.unhandled_rejections() {
let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored };
let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag);
let mut o = json!({
"message": e.message,
"messageOrigin": if e.authored { "script" } else { "built-in" },
"line": e.line,
"column": e.column,
});
if let (Some(file), Some(map)) = (file, o.as_object_mut()) {
map.insert("file".into(), json!(&*file));
}
out.push(o);
}
out
}
/// The report of a run that failed; `file` is the included file the error is in.
fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
@@ -2463,6 +2502,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());
+1
View File
@@ -78,6 +78,7 @@ impl Session {
depth: 0,
replaying: false,
shape_drawn: false,
prefs_resets: Vec::new(),
tool_panic: None,
tool_resets: 0,
tool_set_since_reset: false,
+325 -37
View File
@@ -20,7 +20,10 @@
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional
//! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
//! stored there that list permissions (id, module hash, permissions); a stored plug-in whose
//! permissions it doesn't grant is skipped with a log record, and stays in the folder.
//! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file
//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's
//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the
//! one the key store keeps for the folder, grants nothing.
//! * **Plug-in settings and caches**: `storage/id-<id>/` in the plug-in store, the id written as
//! [`case_safe`] writes it, holds what a plug-in
//! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a
@@ -52,6 +55,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
use crate::Session;
use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile};
pub mod grant_keys;
/// Files read from one store folder, at most (the rest are ignored).
pub const MAX_STORE_FILES: usize = 1000;
/// The largest PDF presets file read (a preset is a few kilobytes).
@@ -463,6 +468,11 @@ fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool {
if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) {
return true;
}
#[cfg(test)]
if file == GRANTS_FILE && GRANTS_WRITE_FAILS.get() {
log::warn!("can't save {}: the test fails it", path.display());
return false;
}
let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes));
if let Err(e) = &written {
log::warn!("can't save {}: {e}", path.display());
@@ -560,6 +570,9 @@ thread_local! {
/// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when
/// another program holds it open.
pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: writing [`GRANTS_FILE`] fails on this thread and leaves the file as it was, as on a
/// full volume.
pub(crate) static GRANTS_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then
/// reports a failure, as when the last flush of a copy fails.
pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
@@ -810,18 +823,10 @@ impl Session {
}
let dir = load.dir.clone();
// The grants file is read once for this turn. `written` holds whether it names each id
// whose grant this turn removed or put back.
// whose grant this turn removed or put back. Only a signed file grants anything
// ([`signed_grants`]).
let file = read_grants(&dir);
let mut grants = self.counted(
&dir,
match &file {
Ok(file) => file.grants.clone(),
Err(e) => {
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
BTreeMap::new()
}
},
);
let mut grants = self.counted(&dir, signed_grants(&dir, &file));
let mut written: BTreeMap<String, bool> = BTreeMap::new();
let named = |written: &BTreeMap<String, bool>, id: &str| {
written.get(id).copied().unwrap_or_else(|| match &file {
@@ -1304,9 +1309,25 @@ impl Session {
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
/// other grants as they are; with none left, remove the file. Entries this version can't use
/// are written back as they were, except one for `id`. A grants file that is too large, can't
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and
/// are written back as they were, except one for `id`. The generation is raised, and the file is
/// written at the generation after the raised one with the MAC of its grants for this folder
/// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that
/// generation ([`put_grants`]). A signed file left empty is removed after raising the generation
/// ([`take_signed_grants`]). The generation is never lowered: when the file can't be written or
/// removed after the raise, the file in place grants nothing and its plug-ins ask again. A file
/// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant replaces it with a file that holds that grant alone, and removing one
/// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the
/// rest unsigned. Removing a grant when there is no file, or when the file grants nothing
/// (unsigned, too large or not a list) and has no entry to take out, also raises the generation
/// when the key store holds a key ([`retire_signed_copies`]), so that a signed copy put back
/// doesn't grant it again. The generation is never read from the file; when it can't be raised,
/// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or
/// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry
/// for `id` stays; a removal then reports a failure, also when the file doesn't name `id`. A
/// grants file that is too large, can't be read or doesn't hold a list is left as it is, with a
/// log record, and nothing is recorded; so is one whose new content would be larger than
/// `MAX_GRANTS_FILE`. A removal still holds for a file that is too large or doesn't hold a list
/// once the generation is raised ([`retire_signed_copies`]). The file is read and
/// written in `turn`. → whether the store now holds what was asked (`false` without a folder,
/// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every
/// session in the process attached to the store ([`Session::ignore_stored_grant`]).
@@ -1364,13 +1385,33 @@ impl Session {
Ok(file) => file,
Err(e) => {
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
return false;
// A file that is too large or doesn't hold a list grants nothing and is left as it
// is, but a signed copy made before it must not grant `id` again once it is put back:
// the removal holds once no such copy can.
return grant.is_none() && !e.unread && retire_signed_copies(dir);
}
};
#[cfg(test)]
if let Some(between) = AFTER_GRANTS_READ.take() {
between();
}
match (file.trust, &grant) {
// Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for
// the session only, and one the file may still hold for `id` can't be removed. A file
// that doesn't name `id` may not be the one the kept generation was signed for, so the
// removal isn't known to hold either.
(Trust::Unknown, _) => return false,
// The file grants nothing. A new grant replaces it with a signed file that holds that
// grant alone; removing one takes its entry out and leaves the rest unsigned.
(Trust::Unsigned, Some(_)) => {
log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display());
file.grants.clear();
file.other.clear();
}
(Trust::Unsigned | Trust::Signed, _) => {}
}
let signed = file.trust == Trust::Signed || grant.is_some();
let removing = grant.is_none();
let others = file.other.len();
file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id));
let changed = match grant {
@@ -1378,23 +1419,25 @@ impl Session {
None => file.grants.remove(id).is_some(),
} || file.other.len() != others;
if !changed {
return true;
// Without a file, or with one that grants nothing, the last signed file may still be
// around as a copy at the kept generation: a removal raises the generation so that the
// copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id`
// is the latest, so every copy that does is at an earlier generation already. The new
// generation is past every one a file was signed at, so the file left in place grants
// nothing either.
return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir);
}
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
entries.extend(file.other);
if entries.is_empty() {
return take(dir, GRANTS_FILE);
if signed {
return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) };
}
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
// and not at all when that is too.
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) {
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
None => {
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE));
false
}
// An unsigned file loses an entry: the generation is raised first, so that no signed copy
// made before brings the entry back, nor the file itself when it can't be rewritten.
if raise_generation(dir).is_none() {
return false;
}
if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) }
}
/// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this
@@ -1408,6 +1451,19 @@ impl Session {
})
}
/// The grant the attached plug-in store's signed grants file holds for the plug-in `id` (`None`
/// without a folder, and when the file grants nothing: unsigned, unreadable or without an entry
/// for `id`).
pub(crate) fn stored_plugin_grant(&self, id: &str) -> Option<vectorcraft_plugins::permissions::Grant> {
self.plugin_dir.as_deref().and_then(|dir| stored_grants(dir).remove(id))
}
/// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one
/// that no grant covers is skipped at startup and stays in the folder)?
pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool {
self.plugin_dir.as_deref().is_some_and(|dir| std::fs::symlink_metadata(dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)))).is_ok())
}
/// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a
/// folder, and when `turn` isn't held).
pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool {
@@ -2049,10 +2105,16 @@ impl Storage for PluginStorage {
/// What the grants file of a plug-in store holds.
#[derive(Default)]
struct GrantsFile {
/// The grants this version can use, by plug-in id.
/// The grants this version can use, by plug-in id. They grant something only when the file is
/// [`Trust::Signed`].
grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
/// The entries it can't use (a permission it doesn't know, an invalid id), as they were.
other: Vec<serde_json::Value>,
/// Whether VectorCraft wrote the grants for this folder.
trust: Trust,
/// Whether there is a grants file: `false` when there is none, and the file is then empty and
/// [`Trust::Signed`].
present: bool,
}
impl GrantsFile {
@@ -2062,6 +2124,207 @@ impl GrantsFile {
}
}
/// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]).
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
enum Trust {
/// There is no file, or it is at the generation kept for its folder and carries the MAC of that
/// generation, its grants and its folder made with the user's key.
#[default]
Signed,
/// It doesn't: an older version wrote it, another program wrote or changed it, it was copied
/// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept
/// (its generation is not the one the key store keeps), or the key store holds no key. It grants
/// nothing.
Unsigned,
/// The key store can't be reached, so it is not known which. It grants nothing, and is left as
/// it is.
Unknown,
}
/// The version of the grants file this version writes ([`SignedGrants::version`]).
const GRANTS_VERSION: u64 = 1;
/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]),
/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as
/// compact JSON.
#[derive(serde::Serialize, serde::Deserialize)]
struct SignedGrants {
version: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
generation: Option<u64>,
grants: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
mac: Option<String>,
}
/// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it
/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft
/// writes one.
#[cfg(test)]
pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec<u8> {
let entries: Vec<serde_json::Value> = serde_json::from_str(grants).unwrap_or_default();
let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}"));
let folder = plugin_store_key(dir);
let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}"));
let canonical = serde_json::to_vec(&entries).unwrap_or_default();
let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default();
format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes()
}
/// Tests: the entries of the grants file `bytes`, signed or not.
#[cfg(test)]
pub(crate) fn grant_entries(bytes: &[u8]) -> Vec<serde_json::Value> {
match serde_json::from_slice::<serde_json::Value>(bytes) {
Ok(serde_json::Value::Array(entries)) => entries,
Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") {
Some(serde_json::Value::Array(entries)) => entries,
_ => vec![],
},
_ => vec![],
}
}
/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept
/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key.
/// A file at another generation, one behind or one ahead of the kept one included, is
/// [`Trust::Unsigned`].
fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust {
let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned };
let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned };
let folder = plugin_store_key(dir);
let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose());
match kept {
Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed,
Ok(_) => Trust::Unsigned,
Err(e) => {
log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
Trust::Unknown
}
}
}
/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when
/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the
/// key or the generation can't be had or it is too large either way. When `signed`, the generation
/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one
/// with its MAC, and the key store keeps that generation once the file is written. Every signed write
/// is then at a generation no file was signed at before, a write whose generation wasn't kept
/// included, since that one is at most one past the generation the key store kept. A file too large
/// either way is found before the raise, and then nothing changes. The kept generation only goes up:
/// when the file isn't written after the raise, the generation stays raised, so the file in place
/// grants nothing and its plug-ins ask again. When the file's generation can't be kept, the file is
/// at a generation the key store doesn't hold, so it grants nothing either. Both report a failure.
/// Call it in the store's turn ([`StoreTurn`]).
fn put_grants(dir: &Path, entries: Vec<serde_json::Value>, signed: bool) -> bool {
let path = dir.join(GRANTS_FILE);
let folder = plugin_store_key(dir);
if !signed {
return match grants_bytes(serde_json::to_value(entries).ok()) {
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
None => {
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
false
}
};
}
let key = match grant_keys::signing_key() {
Ok(key) => key,
Err(e) => {
log::warn!("not updating the stored plug-in grants {}: {e}", path.display());
return false;
}
};
// A file too large to keep is found before the raise, at the generation it would be written at
// (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place
// keeps its grants when nothing can be written. When the kept generation can't be read, the raise
// fails too.
let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX);
let mut file =
SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) };
if grants_bytes(serde_json::to_value(&file).ok()).is_none() {
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
return false;
}
let Some(raised) = raise_generation(dir) else { return false };
let Some(next) = raised.checked_add(1) else {
log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display());
return false;
};
file.generation = Some(next);
file.mac = serde_json::to_vec(&file.grants).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants));
let Some(bytes) = file.mac.as_ref().and_then(|_| grants_bytes(serde_json::to_value(&file).ok())) else {
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
return false;
};
put(dir, GRANTS_FILE, &bytes) && keep_generation(dir, &folder, next)
}
/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than
/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap.
fn grants_bytes(file: Option<serde_json::Value>) -> Option<Vec<u8>> {
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits)))
}
/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) →
/// whether the key store kept it; a failure is logged.
fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool {
match grant_keys::set_current_generation(folder, generation) {
Ok(()) => true,
Err(e) => {
log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display());
false
}
}
}
/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is
/// raised first, so that no copy of the file grants anything once it is gone. The generation stays
/// raised when the file can't be removed: the file left in place then grants nothing, and its
/// plug-ins ask again. The file holds no grant but the one being removed. Nothing is removed when
/// the generation can't be raised. Call it in the store's turn ([`StoreTurn`]).
fn take_signed_grants(dir: &Path) -> bool {
raise_generation(dir).is_some() && take(dir, GRANTS_FILE)
}
/// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that
/// no signed copy of the file made before grants anything → the generation kept now; `None`, with a
/// log record, when the key store can't read or keep it or the generation is within two of the
/// largest 64-bit value. A signed write whose generation wasn't kept is at the generation after the
/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the
/// key store alone, never from a file, which anyone can edit, and it is never lowered again.
fn raise_generation(dir: &Path) -> Option<u64> {
let folder = plugin_store_key(dir);
let raised = grant_keys::current_generation(&folder).and_then(|generation| {
// A signed write goes one past the raised generation, so that one must fit too.
let next = generation.checked_add(3).and(generation.checked_add(2));
let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?;
grant_keys::set_current_generation(&folder, next).map(|()| next)
});
match raised {
Ok(generation) => Some(generation),
Err(e) => {
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
None
}
}
}
/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything →
/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key,
/// and left as it is when it holds none, since no file is then signed. `false`, with a log record,
/// when the key store can't read or keep it. Call it in the store's turn ([`StoreTurn`]).
fn retire_signed_copies(dir: &Path) -> bool {
match grant_keys::current_key() {
Ok(None) => true,
Ok(Some(_)) => raise_generation(dir).is_some(),
Err(e) => {
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
false
}
}
}
/// Why the grants file of a plug-in store gave no grants.
struct GrantsError {
/// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is
@@ -2072,8 +2335,10 @@ struct GrantsError {
}
/// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too
/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an
/// invalid id, is kept in [`GrantsFile::other`] with a log record.
/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it),
/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An
/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`]
/// with a log record.
fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
let path = dir.join(GRANTS_FILE);
let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) {
@@ -2084,8 +2349,23 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
if bytes.len() as u64 > MAX_GRANTS_FILE {
return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) });
}
let entries = serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?;
let mut file = GrantsFile::default();
let not_a_list = |why: String| GrantsError { unread: false, why };
let (entries, trust) = match serde_json::from_slice::<serde_json::Value>(&bytes).map_err(|e| not_a_list(e.to_string()))? {
serde_json::Value::Array(entries) => (entries, Trust::Unsigned),
serde_json::Value::Object(_) => {
let signed = serde_json::from_slice::<SignedGrants>(&bytes).map_err(|e| not_a_list(e.to_string()))?;
let trust = trust_of(dir, &signed);
(signed.grants, trust)
}
_ => return Err(not_a_list("not a list of grants".into())),
};
if trust == Trust::Unsigned {
log::warn!(
"the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again",
path.display()
);
}
let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() };
let mut first_error = None;
for entry in entries {
let why = match serde_json::from_value::<vectorcraft_plugins::permissions::Grant>(entry.clone()) {
@@ -2106,11 +2386,19 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
}
/// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when
/// there is no grants file, and none, with a log record, when it is too large, can't be read or
/// doesn't hold a list.
/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked
/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a
/// list.
fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
match read_grants(dir) {
Ok(file) => file.grants,
signed_grants(dir, &read_grants(dir))
}
/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`]
/// read it.
fn signed_grants(dir: &Path, file: &Result<GrantsFile, GrantsError>) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
match file {
Ok(file) if file.trust == Trust::Signed => file.grants.clone(),
Ok(_) => BTreeMap::new(),
Err(e) => {
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
BTreeMap::new()
+541
View File
@@ -0,0 +1,541 @@
//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an
//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of
//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps
//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one
//! an older version wrote, one another program wrote or changed, one copied from another folder or
//! machine) grants nothing.
//!
//! The key store also keeps a generation for each plug-in folder, raised on every signed write of
//! its grants file and never lowered, and the file carries its generation inside the MAC. A file
//! whose generation is not the one kept (an earlier copy put back over the current file, or a write
//! whose generation the key store didn't keep or that failed after the raise) grants nothing either.
//!
//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's
//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key
//! store can't be reached: a grant holds for the session only.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
/// The length of a key, in bytes, and of the MAC.
pub const KEY_LEN: usize = 32;
/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`.
#[derive(Clone, PartialEq, Eq)]
pub struct GrantKey([u8; KEY_LEN]);
impl GrantKey {
/// The key with the bytes `bytes`.
pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self {
GrantKey(bytes)
}
/// A new key from the system's random source.
#[cfg(not(target_arch = "wasm32"))]
pub fn random() -> Result<Self, KeyStoreError> {
let mut bytes = [0u8; KEY_LEN];
getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?;
Ok(GrantKey(bytes))
}
/// The browser keeps no grants file.
#[cfg(target_arch = "wasm32")]
pub fn random() -> Result<Self, KeyStoreError> {
Err(KeyStoreError("there is no key store".into()))
}
}
impl std::fmt::Debug for GrantKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("GrantKey(..)")
}
}
/// Why a key store gave no key or didn't keep one. The message never holds key bytes.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct KeyStoreError(pub String);
/// Where the key of grants files is kept.
pub trait GrantKeyStore: Send + Sync {
/// The key kept, `None` when there is none; an error when the store can't be reached or read.
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError>;
/// Keep `key` in place of any kept before.
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>;
/// The key kept, after making and keeping a new one when there is none. The key returned is the
/// one read back from the store, so a key another process kept first wins.
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
if let Some(key) = self.key()? {
return Ok(key);
}
self.set_key(&GrantKey::random()?)?;
self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
}
/// The generation kept for the grants file of the plug-in store whose folder is `folder`
/// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept.
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError>;
/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`.
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>;
}
/// A key store in memory: the key and the generations last as long as the store. For tests and
/// embedders.
#[derive(Default)]
pub struct MemoryGrantKeys {
key: Mutex<Option<GrantKey>>,
generations: Mutex<BTreeMap<PathBuf, u64>>,
}
impl MemoryGrantKeys {
/// A store that holds `key`.
pub fn with_key(key: GrantKey) -> Self {
MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() }
}
}
impl GrantKeyStore for MemoryGrantKeys {
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone())
}
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
*self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone());
Ok(())
}
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError> {
Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied())
}
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation);
Ok(())
}
}
/// The key store of the process ([`set_grant_key_store`]).
static PROCESS_STORE: Mutex<Option<Arc<dyn GrantKeyStore>>> = Mutex::new(None);
/// The one memory store of [`keep_grant_keys_in_memory`].
static SHARED_MEMORY: LazyLock<Arc<MemoryGrantKeys>> = LazyLock::new(Arc::default);
#[cfg(test)]
thread_local! {
/// Tests: the key store this thread uses in place of the process's.
pub(crate) static THREAD_STORE: std::cell::RefCell<Option<Arc<dyn GrantKeyStore>>> = const { std::cell::RefCell::new(None) };
}
/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no
/// key store, so grants hold for the session only).
pub fn set_grant_key_store(store: Option<Arc<dyn GrantKeyStore>>) {
*PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store;
}
/// Keep the key in memory for the rest of the process, one key for every caller: grants files
/// written in the process count in it, and not in another process. For tests.
pub fn keep_grant_keys_in_memory() {
let shared: Arc<dyn GrantKeyStore> = SHARED_MEMORY.clone();
set_grant_key_store(Some(shared));
}
/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the
/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service
/// `org.storytold.vectorcraft.plugin-grants`.
#[cfg(not(target_arch = "wasm32"))]
pub fn use_os_grant_keys() {
set_grant_key_store(Some(Arc::new(OsGrantKeys::default())));
}
/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory
/// store when the process set none.
fn current_store() -> Option<Arc<dyn GrantKeyStore>> {
#[cfg(test)]
if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) {
return Some(store);
}
let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone();
#[cfg(test)]
let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc<dyn GrantKeyStore>));
store
}
/// The key kept for grants files: `None` when there is none yet, an error when there is no key
/// store or it can't be reached.
pub(crate) fn current_key() -> Result<Option<GrantKey>, KeyStoreError> {
current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key()
}
/// The key to sign a grants file with: the one kept, else a new one, kept first
/// ([`GrantKeyStore::create_key`]).
pub(crate) fn signing_key() -> Result<GrantKey, KeyStoreError> {
let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?;
match store.key()? {
Some(key) => Ok(key),
None => store.create_key(),
}
}
/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when
/// none is kept yet, an error when there is no key store or it can't be reached.
pub(crate) fn current_generation(folder: &Path) -> Result<u64, KeyStoreError> {
Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0))
}
/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept
/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a
/// lower one could match a file signed before.
pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?;
if store.generation(folder)?.is_some_and(|kept| generation < kept) {
return Err(KeyStoreError("the key store keeps a later generation".into()));
}
store.set_generation(folder, generation)
}
/// The start of every MAC input: what it is a MAC of, and the version of the file.
#[cfg(not(target_arch = "wasm32"))]
const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0";
/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose
/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation
/// go in with their lengths first.
#[cfg(not(target_arch = "wasm32"))]
fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option<hmac::Hmac<sha2::Sha256>> {
use hmac::Mac;
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&key.0).ok()?;
let folder = folder.as_os_str().as_encoded_bytes();
let generation = generation.to_be_bytes();
mac.update(DOMAIN);
mac.update(&(folder.len() as u64).to_be_bytes());
mac.update(folder);
mac.update(&(generation.len() as u64).to_be_bytes());
mac.update(&generation);
mac.update(grants);
Some(mac)
}
/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option<String> {
use hmac::Mac;
Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect())
}
/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]),
/// compared in constant time; a shorter or longer tag is not.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool {
use hmac::Mac;
let Some(tag) = from_hex(tag) else { return false };
mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok())
}
/// The browser keeps no grants file.
#[cfg(target_arch = "wasm32")]
pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option<String> {
None
}
/// The browser keeps no grants file.
#[cfg(target_arch = "wasm32")]
pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool {
false
}
/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them;
/// `None` for anything else.
#[cfg(not(target_arch = "wasm32"))]
fn from_hex(tag: &str) -> Option<Vec<u8>> {
let digits = tag.as_bytes();
let (pairs, rest) = digits.as_chunks::<2>();
if !rest.is_empty() || pairs.len() > KEY_LEN {
return None;
}
let digit = |d: u8| match d {
b'0'..=b'9' => Some(d - b'0'),
b'a'..=b'f' => Some(d - b'a' + 10),
_ => None,
};
pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect()
}
/// The system's key store, through `keyring-core` and the store crate of the platform. The key is
/// read from the store each time it is needed. The key and the generations are kept as lower-case
/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8.
#[cfg(not(target_arch = "wasm32"))]
struct OsGrantKeys {
/// Held while a key is kept, so that the threads of the process that make the first key at the
/// same time keep one.
making: Mutex<()>,
/// The connection to the system's key store, once one is made. A failed connection is not
/// kept, and a kept one is dropped when the key store can't be reached through it or fails
/// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after
/// VectorCraft, or restarts, is used.
store: Mutex<Option<Arc<keyring_core::CredentialStore>>>,
/// How a connection is made ([`connect`]).
connect: fn() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for OsGrantKeys {
fn default() -> Self {
OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect }
}
}
#[cfg(not(target_arch = "wasm32"))]
impl OsGrantKeys {
const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants";
const ACCOUNT: &str = "hmac-sha256-v1";
/// The system's key store: the connection made before, else a new one.
fn store(&self) -> Result<Arc<keyring_core::CredentialStore>, KeyStoreError> {
let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner());
if let Some(store) = store.as_ref() {
return Ok(store.clone());
}
Ok(store.insert((self.connect)().map_err(store_error)?).clone())
}
/// What the key store error `e` says ([`store_error`]). When the key store can't be reached or
/// fails, the connection is dropped first, so the next call makes a new one: the Secret Service
/// loses the session of a connection when it restarts. An entry that isn't there keeps it.
fn failed(&self, e: keyring_core::Error) -> KeyStoreError {
if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) {
*self.store.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
store_error(e)
}
fn entry(&self, account: &str) -> Result<keyring_core::Entry, KeyStoreError> {
self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e))
}
fn key_entry(&self) -> Result<keyring_core::Entry, KeyStoreError> {
self.entry(Self::ACCOUNT)
}
/// The key the system's key store keeps, read from it.
fn stored(&self, entry: &keyring_core::Entry) -> Result<Option<GrantKey>, KeyStoreError> {
match entry.get_secret() {
// A secret that is not 64 hexadecimal digits is not a key this version made: there is none.
Ok(secret) => Ok(std::str::from_utf8(&secret)
.ok()
.and_then(from_hex)
.and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok())
.map(GrantKey)),
Err(keyring_core::Error::NoEntry) => Ok(None),
Err(e) => Err(self.failed(e)),
}
}
/// The entry of the generation of the plug-in store whose folder is `folder`: the account
/// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits.
fn generation_entry(&self, folder: &Path) -> Result<keyring_core::Entry, KeyStoreError> {
use sha2::Digest;
let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes());
self.entry(&format!("generation-v1-{}", to_hex(&digest)))
}
}
/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the
/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2
/// uses, so entries it kept are read.
#[cfg(not(target_arch = "wasm32"))]
fn connect() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
#[cfg(target_os = "macos")]
{
let store: Arc<keyring_core::CredentialStore> = apple_native_keyring_store::keychain::Store::new()?;
Ok(store)
}
#[cfg(windows)]
{
let store: Arc<keyring_core::CredentialStore> = windows_native_keyring_store::Store::new()?;
Ok(store)
}
#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))]
{
let store: Arc<keyring_core::CredentialStore> = zbus_secret_service_keyring_store::Store::new()?;
Ok(store)
}
#[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))]
Err(keyring_core::Error::NoDefaultStore)
}
/// `bytes` as lower-case hexadecimal digits.
#[cfg(not(target_arch = "wasm32"))]
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(not(target_arch = "wasm32"))]
impl GrantKeyStore for OsGrantKeys {
/// Read from the key store each time, so that a key removed or replaced there is not used.
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
self.stored(&self.key_entry()?)
}
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e))
}
/// Reads the key store again and makes the key only while holding [`creation_lock`], so that
/// processes of this user that make the first key at the same time all keep the first one made.
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
let entry = self.key_entry()?;
if let Some(key) = self.stored(&entry)? {
return Ok(key);
}
let _turn = creation_lock()?;
match self.stored(&entry)? {
Some(key) => Ok(key),
None => {
entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?;
self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
}
}
}
/// Read from the key store each time, since another process on the folder may have raised it.
/// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed
/// with it.
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError> {
match self.generation_entry(folder)?.get_secret() {
Ok(secret) => std::str::from_utf8(&secret)
.ok()
.and_then(from_hex)
.and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok())
.map(|bytes| Some(u64::from_be_bytes(bytes)))
.ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())),
Err(keyring_core::Error::NoEntry) => Ok(None),
Err(e) => Err(self.failed(e)),
}
}
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e))
}
}
/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is
/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary
/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file
/// can't be locked: no key is made then.
#[cfg(not(target_arch = "wasm32"))]
fn creation_lock() -> Result<std::fs::File, KeyStoreError> {
#[cfg(windows)]
let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%");
#[cfg(target_os = "macos")]
let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR");
#[cfg(not(any(windows, target_os = "macos")))]
let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR");
let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute());
let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?;
let file = std::fs::File::options()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(dir.join("vectorcraft-plugin-grant-key.lock"))
.map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?;
file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?;
Ok(file)
}
/// What a key store error says, without the secret some of them hold.
#[cfg(not(target_arch = "wasm32"))]
fn store_error(e: keyring_core::Error) -> KeyStoreError {
KeyStoreError(match e {
keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"),
keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"),
keyring_core::Error::NoDefaultStore => "there is no key store".into(),
_ => "the key store can't read or keep the key".into(),
})
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use keyring_core::api::CredentialStoreApi;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Connections asked for from [`flaky`].
static TRIES: AtomicUsize = AtomicUsize::new(0);
/// The store [`flaky`] connects to.
static MOCK: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
/// A key store that can't be reached on the first try and is reached on every later one.
fn flaky() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
if TRIES.fetch_add(1, Ordering::SeqCst) == 0 {
return Err(keyring_core::Error::NoDefaultStore);
}
let store: Arc<keyring_core::CredentialStore> = MOCK.clone();
Ok(store)
}
/// Connections asked for from [`restarting`].
static RESTARTS: AtomicUsize = AtomicUsize::new(0);
/// The store [`restarting`] connects to first.
static BEFORE: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
/// The store [`restarting`] connects to on every later try.
static AFTER: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
/// A key store that restarts after the first connection: later connections reach another store.
fn restarting() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
let store: Arc<keyring_core::CredentialStore> = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() };
Ok(store)
}
/// A connection that the key store can't be reached through is dropped, and the next call
/// connects again; an entry that isn't there keeps the connection.
#[test]
fn the_system_key_store_reconnects_after_it_restarts() {
let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() };
assert_eq!(keys.key().unwrap(), None, "no key is kept yet");
keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap();
assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection");
AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap();
let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap();
let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap();
cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into()));
assert!(keys.key().is_err(), "the connection fails");
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection");
assert_eq!(RESTARTS.load(Ordering::SeqCst), 2);
}
/// The secret `MOCK` keeps for `account`, as it is kept.
fn kept(account: &str) -> Vec<u8> {
MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap()
}
/// The system key store is connected again after a connection fails, the key and the
/// generations are kept as hexadecimal text, and the key is read from the store each time; a
/// value kept as raw bytes is not read as a key or a generation.
#[test]
fn the_system_key_store_reconnects_and_keeps_text() {
let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() };
assert!(keys.key().is_err(), "the first connection fails");
let key = GrantKey::from_bytes([0xa7; KEY_LEN]);
keys.set_key(&key).unwrap();
assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text");
assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back");
let folder = Path::new("/plug-ins");
keys.set_generation(folder, 0x1_0000_0005).unwrap();
let account = format!("generation-v1-{}", to_hex(&<sha2::Sha256 as sha2::Digest>::digest(folder.as_os_str().as_encoded_bytes())));
assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text");
assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005));
MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap();
assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error");
MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap();
assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read");
MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap();
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used");
}
}
+25
View File
@@ -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();
+56
View File
@@ -232,6 +232,29 @@ fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() {
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
}
/// Parts of an outline that lie on the mask's edge show: a square without a fill, clipped by a mask
/// of the same square, keeps all four sides and bounds its whole area. A square just outside the
/// mask is hidden and bounds nothing.
#[test]
fn fill_area_keeps_outline_parts_on_the_mask_edge() {
let mut s = session();
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"none": true})).unwrap();
clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0);
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
assert!((area(&s, id_of(&r)) - 10000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
let mut s = session();
let square = rect(&mut s, -0.005, -0.005, 100.01, 100.01);
s.execute("paint.setFill", &json!({"none": true})).unwrap();
clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0);
deselect(&mut s);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).is_err());
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
}
/// In a clipping group inside another, clipped art shows only where both masks show it.
#[test]
fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() {
@@ -305,6 +328,39 @@ fn fill_area_stays_inside_the_isolated_group() {
assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer());
}
/// In isolation mode, `ids` naming the isolated group, or the layer or a group that holds it, takes
/// every path of the isolated group. The other paths of that layer or group, and other listed
/// objects outside the isolated group, do not bound areas.
#[test]
fn fill_area_ids_naming_what_holds_the_isolated_group_take_its_paths() {
let mut s = session();
let outside =
[line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))];
let lines = triangle(&mut s);
let ids: Vec<u64> = lines.iter().map(|l| l.0).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let outer = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
deselect(&mut s);
let layer = s.doc().unwrap().doc.default_layer().unwrap();
let (undo, kids) = (undo_len(&s), stack(&s));
for named in [vec![layer.0], vec![outer.0], vec![g.0], vec![layer.0, outside[0].0]] {
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named}));
assert!(r.is_err(), "the area outside the isolated group, ids {named:?}");
assert_eq!((undo_len(&s), stack(&s)), (undo, kids.clone()));
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).unwrap();
let new = id_of(&r);
assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g), "ids {named:?}");
assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new));
s.execute("edit.undo", &json!({})).unwrap();
}
let named: Vec<u64> = outside.iter().map(|l| l.0).collect();
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).is_err(), "only art outside it listed");
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
}
/// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and
/// changes nothing: the compound path cannot hold the new path. The same goes for an isolated
/// Objects on Path group, a group with a Transform effect and a group that is a clipping mask.
+41
View File
@@ -4644,6 +4644,47 @@ fn a_ruler_guide_rotates_with_the_selected_art() {
assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s));
}
/// The reply to a transform lists the guide paths it makes of ruler guides: for a guide alone,
/// with a copy, beside selected art and beside direct-selected anchors.
#[test]
fn a_transform_replies_with_the_guide_paths_it_makes() {
fn reply_ids(r: &Value) -> Vec<NodeId> {
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
}
let mut s = session();
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
// A copy keeps the ruler guide and adds a guide path, the only new object.
let r = s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap();
let [copy] = selected(&s)[..] else { panic!("the copy is selected") };
assert_eq!(reply_ids(&r), vec![copy]);
// Without a copy the guide becomes a guide path.
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let [path] = selected(&s)[..] else { panic!("one guide path selected") };
assert_ne!(path, copy);
assert_eq!(reply_ids(&r), vec![path]);
// With art selected, the reply lists the art and then the guide path.
let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
sel(&mut s, &[a]);
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
let r = s.execute("object.rotate", &json!({"angle": 20})).unwrap();
let paths: Vec<NodeId> = selected(&s).into_iter().filter(|id| *id != a).collect();
let [mixed] = paths[..] else { panic!("the guide path is selected with the art") };
assert_eq!(reply_ids(&r), vec![a, mixed]);
// With direct-selected anchors, the guide path joins the reply too.
s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
assert!(!s.doc().unwrap().selection.anchors.is_empty());
let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let anchored: Vec<NodeId> = selected(&s).into_iter().filter(|id| *id != a).collect();
let [made] = anchored[..] else { panic!("the guide path is selected with the path") };
assert!(line_ends(&s, made).1, "it is a guide path");
assert!(reply_ids(&r).contains(&made), "{r}");
}
#[test]
fn ruler_guides_and_lock() {
let mut s = session();
File diff suppressed because it is too large. Load diff
+18
View File
@@ -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);
+71 -3
View File
@@ -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();
+56
View File
@@ -692,3 +692,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() {
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_js_script_has_promise_and_a_jsx_script_does_not() {
let base = folder("promise-realm");
let main = base.join("main/main.js");
write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);");
let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
assert_eq!(r["log"], json!(["function", 1, 2]));
assert!(r.get("unhandledRejections").is_none(), "{r}");
let r = run(&base, "vc.log(typeof Promise);").unwrap();
assert_eq!(r["log"], json!(["undefined"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() {
let base = folder("promise-engine");
let jsx = base.join("main/a.jsx");
let js = base.join("main/b.js");
let mut s = Session::new();
let mut go = |path: &Path, text: &str| {
write(path, text);
s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone()
};
assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"]));
assert_eq!(
go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"),
json!([1, "function", 2])
);
assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() {
let base = folder("promise-rejections");
write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n");
let main = base.join("main/main.js");
write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n");
let mut s = Session::new();
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
let got: Vec<(String, u64, Option<bool>)> = r["unhandledRejections"]
.as_array()
.unwrap()
.iter()
.map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc"))))
.collect();
assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}");
assert_eq!(r["unhandledRejectionCount"], 2);
let c = s.execute("script.console", &json!({})).unwrap();
let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect();
assert_eq!(errors.len(), 2, "{errors:?}");
assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}");
assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}");
let _ = std::fs::remove_dir_all(base);
}
+1 -1
View File
@@ -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"),
+19
View File
@@ -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]
+15 -1
View File
@@ -1069,6 +1069,12 @@ impl Session {
self.tool.wants_samples()
}
/// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel
/// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open.
pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.reads_wheel(cx))
}
/// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input
/// held until an edit it computes is applied, or are requests for the UI left from making it?
pub fn tool_waiting(&self) -> bool {
@@ -1582,7 +1588,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";
+50
View File
@@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() {
assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha"));
}
/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused
/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it
/// takes, and the document and its undo history stay as they were. Blend-mode names in any
/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays.
#[test]
fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap();
let state = |s: &Session| {
let st = s.active().unwrap();
(st.doc.clone(), st.history.undo.len())
};
let before = state(&s);
let why = "`mode` must be one of normal, darken, multiply, colorBurn";
for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] {
for (cmd, params) in [
("effect.setParams", json!({"index": 0, "params": {"mode": bad}})),
("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})),
("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})),
("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
assert!(e.contains(why), "{cmd} {params}: {e}");
let checked = s.check_params(cmd, &params).unwrap_err().to_string();
assert!(checked.contains(why), "{cmd} {params}: {checked}");
assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history");
}
}
let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone();
let shadow = effect(&s);
let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params);
assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default");
for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] {
let params = json!({"index": 0, "params": {"mode": good}});
s.check_params("effect.setParams", &params).unwrap_or_else(|e| panic!("{good}: {e}"));
s.execute("effect.setParams", &params).unwrap_or_else(|e| panic!("{good}: {e}"));
assert_eq!(effect(&s).params["mode"], json!(good));
}
s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap();
assert_eq!(effect(&s).params["mode"], json!("multipy"));
assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal);
for mode in vectorcraft_color::BlendMode::ALL {
let id = vectorcraft_render::effects::blend_mode_id(mode);
assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode));
assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode);
}
}
/// What a command adds to its own journal entry passes the check, so a recorded journal can be
/// sent back through the control channel or MCP.
#[test]
@@ -82,8 +82,8 @@ const INSIDE: &[(&str, &str)] = &[
("Application.", "prototype"),
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \
selection selection= toString typename",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
getIsFileOpen selection selection= toString typename",
),
("DocumentPreset.", "prototype"),
(
@@ -39,6 +39,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() {
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
let ids = ["test.clearcache.a", "test.clearcache.b"];
vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory();
let mut s = Session::new();
s.allow_plugin_grants_from_requests();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
+1
View File
@@ -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());
+3 -1
View File
@@ -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
+18 -2
View File
@@ -1,8 +1,8 @@
//! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the
//! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`,
//! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex
//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with
//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in
//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and
//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and
//! the iterators of arrays, strings and `arguments` objects (in `iterator`).
//!
@@ -17,6 +17,7 @@ pub(crate) mod iterator;
mod json;
mod math;
mod object;
pub(crate) mod promise;
mod symbol;
use std::rc::Rc;
@@ -242,6 +243,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
method(interp, function_proto, "bind", function_bind, 1)?;
method(interp, function_proto, "toString", function_to_string, 0)?;
let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?;
constructor(interp, "Boolean", boolean, boolean_proto)?;
method(interp, boolean_proto, "toString", boolean_to_string, 0)?;
method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?;
@@ -262,6 +265,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
if interp.options.e4x {
crate::xml_builtins::install(interp)?;
}
if interp.options.es2015 {
promise::install(interp)?;
}
Ok(())
}
@@ -516,6 +522,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J
Ok(Value::str(&format!("[object {class}]")))
}
/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2).
fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult<Value> {
let b = args.first().is_some_and(Value::truthy);
if !construct {
return Ok(Value::Bool(b));
}
let proto = interp.intrinsics.boolean_proto;
Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto)))))
}
/// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a
/// primitive, or the primitive value of a Boolean object.
fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult<bool> {
File diff suppressed because it is too large. Load diff
+15
View File
@@ -407,6 +407,21 @@ fn boolean_prototype_converts_booleans() {
throws("Object.getPrototypeOf(true).valueOf.call({})", "TypeError");
}
#[test]
fn the_boolean_constructor_converts_and_wraps() {
// Called as a function it gives ToBoolean of its argument (section 15.6.1).
truth("Boolean() === false && Boolean(0) === false && Boolean('') === false && Boolean(NaN) === false && Boolean(null) === false");
truth("Boolean(1) === true && Boolean('false') === true && Boolean({}) === true && Boolean(new Boolean(false)) === true");
truth("['', 'a', 0, 2].filter(Boolean).length === 2");
// With new it makes a Boolean object (section 15.6.2), which is truthy whatever it holds.
truth("var b = new Boolean(0); typeof b === 'object' && b.valueOf() === false && !!b && b instanceof Boolean");
assert_eq!(string("Object.prototype.toString.call(new Boolean(1)) + new Boolean('')"), "[object Boolean]false");
// The constructor and Boolean.prototype are linked, and true and false look methods up there.
truth("Boolean.prototype === Object.getPrototypeOf(true) && Boolean.prototype.constructor === Boolean && true.constructor === Boolean");
truth("Boolean.length === 1 && Object(false) instanceof Boolean");
truth("!Object.getOwnPropertyDescriptor(this, 'Boolean').enumerable && !Object.getOwnPropertyDescriptor(Boolean, 'prototype').writable");
}
#[test]
fn array_methods_overwriting_elements_need_no_heap_for_new_ones() {
// With the heap exactly at its limit, an array method's write over an existing element
+21 -1
View File
@@ -268,6 +268,10 @@ pub(crate) enum Class {
Host(crate::host_classes::HostObj),
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
UnitValue(Box<crate::unit_value::Measure>),
/// A promise (ECMA-262 11th edition, section 25.6) and its state.
Promise(Box<crate::builtins::promise::PromiseData>),
/// The state that the functions a promise operation makes share; scripts never see it.
PromiseRecord(Box<crate::builtins::promise::Record>),
}
/// What an XML value is.
@@ -331,7 +335,8 @@ impl Class {
Class::XmlList(_) => "XMLList",
Class::Namespace(_) => "Namespace",
Class::QName { .. } => "QName",
Class::XmlFilter(_) => "Object",
Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object",
Class::Promise(_) => "Promise",
Class::Math => "Math",
Class::Json => "JSON",
Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
@@ -779,6 +784,21 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
}
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
Class::Promise(p) => {
for v in p.values() {
mark_value(&v, work, strings);
}
if let Some((code, _)) = &p.site {
mark_code(code, strings);
}
extra = p.bytes();
}
Class::PromiseRecord(r) => {
for v in r.values() {
mark_value(&v, work, strings);
}
extra = crate::builtins::promise::RECORD_BYTES;
}
_ => {}
}
OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra
+12 -3
View File
@@ -91,6 +91,8 @@ pub(crate) struct Entry {
parent: Option<u32>,
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
own: Rc<HashSet<Key>>,
/// The names of the members this class declares as unavailable.
unavailable: Rc<HashSet<Key>>,
}
impl Entry {
@@ -143,7 +145,9 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
impl Interp {
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
/// class, and `k` names an available member of that class or of a class it descends from.
/// class, and `k` names an available member of that class or of a class it descends from. The
/// nearest class that declares `k` decides, so a member a class declares unavailable is not
/// reported even when a class it descends from has it.
pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(false) };
let mut class = Some(h.class);
@@ -152,6 +156,9 @@ impl Interp {
if e.own.contains(k) {
return Ok(true);
}
if e.unavailable.contains(k) {
return Ok(false);
}
class = e.parent;
}
Ok(false)
@@ -307,7 +314,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
let r = fill_class(i, proto, &class);
i.temp_roots.truncate(mark);
let ctor = r?;
let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect();
let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::<HashSet<Key>>();
i.host_classes.push(Entry {
name: class.name.as_str().into(),
proto,
@@ -315,7 +323,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
index: class.index,
family,
parent: parent_class,
own: Rc::new(members),
own: Rc::new(names(members)),
unavailable: Rc::new(names(unavailable)),
});
let global = i.global;
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
+47
View File
@@ -756,6 +756,53 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
);
}
#[test]
fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() {
let mut r = realm(1_000_000);
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
let base = HostClass {
name: "Base".into(),
parent: None,
members: vec![("size".to_string(), HostMember::Get(value.clone())), ("grow".to_string(), HostMember::Method(value))],
index: None,
construct: None,
};
let leaf = HostClass {
name: "Leaf".into(),
parent: Some("Base".into()),
members: vec![("size".to_string(), HostMember::Unavailable(missing))],
index: None,
construct: None,
};
r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), it.hasOwnProperty('grow')].join()").unwrap();
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
}
#[test]
fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
let mut r = realm(1_000_000);
let calls: Rc<Cell<u32>> = Rc::default();
let seen = calls.clone();
let index: HostFunction = Rc::new(move |a| {
seen.set(seen.get() + 1);
match a.get(1) {
Some(Data::Number(_)) => Ok(Data::Undefined),
_ => Err(HostError::Error("no such member".into())),
}
});
let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), index: Some(index), construct: None };
r.define_host_classes(vec![class], vec![("it".into(), host_ref("List", &[1.0]))]).unwrap();
r.start("Object.prototype.extra = 1; it.extra = 2; it.extra").unwrap();
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::Number(1.0));
assert_eq!(calls.get(), 0);
// A name nothing has still goes to the indexer, which throws.
r.start("it.nope = 2").unwrap();
assert!(finish(&mut r, 1_000_000).0.is_err());
assert_eq!(calls.get(), 1);
}
#[test]
fn a_converted_function_reads_each_argument_as_its_list_says() {
let mut r = realm(1_000_000);
+95 -13
View File
@@ -55,12 +55,37 @@ pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]).
fn description_hash(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::hash::DefaultHasher::new();
text.hash(&mut h);
let mut h = DescriptionHash::default();
h.text(text);
h.finish()
}
/// A [`description_hash`] fed the description's code units a run at a time, so a long string is
/// hashed without being copied.
#[derive(Default)]
struct DescriptionHash(std::hash::DefaultHasher);
impl DescriptionHash {
fn units(&mut self, units: &[u16]) {
use std::hash::Hasher;
for &u in units {
self.0.write_u16(u);
}
}
fn text(&mut self, text: &str) {
use std::hash::Hasher;
for u in text.encode_utf16() {
self.0.write_u16(u);
}
}
fn finish(&self) -> u64 {
use std::hash::Hasher;
self.0.finish()
}
}
/// The kinds of error object the engine throws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ErrorType {
@@ -354,6 +379,8 @@ pub(crate) struct Interp {
pub(crate) error_mark: Option<u32>,
/// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs.
pub(crate) strict_writes: bool,
/// `Promise` and the run's promise job queue ([`crate::builtins::promise`]).
pub(crate) promises: crate::builtins::promise::Promises,
/// The well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a
/// realm with [`crate::Options::es2015`].
pub(crate) symbols: crate::symbol::Symbols,
@@ -625,6 +652,7 @@ impl Interp {
finally_sites: Vec::new(),
error_mark: None,
strict_writes: false,
promises: crate::builtins::promise::Promises::default(),
symbols: crate::symbol::Symbols::default(),
};
// With `Options::es2015`, the first run names the built-in functions, under the limits
@@ -676,7 +704,7 @@ impl Interp {
let Value::Object(o) = v else { return true };
let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true };
let hash = *hash;
description_hash(&self.describe(v)) != hash
self.describe_hash(*o) != hash
}
pub(crate) fn type_error(&mut self, message: &str) -> Abrupt {
@@ -854,6 +882,7 @@ impl Interp {
pub(crate) fn collect_garbage(&mut self) {
self.drop_left_finally_marks();
self.drop_left_finally_sites(self.stack.len());
self.promises.forget_handled(&self.heap);
let mut roots = Roots::default();
roots.values.extend(self.stack.iter());
roots.values.extend(self.temp_roots.iter());
@@ -890,13 +919,20 @@ impl Interp {
}
self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0));
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
self.promises.add_roots(&mut roots);
self.heap.collect(&roots);
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
// The collection counts the live total again, so bytes already released are not in it.
self.held.released.set(0);
self.flattened.set(0);
self.heap.bytes =
self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(self.symbols.registry_bytes());
let queued = self.promises.queue_bytes();
self.heap.bytes = self
.heap
.bytes
.saturating_add(self.held_bytes)
.saturating_add(self.held.now.get())
.saturating_add(self.symbols.registry_bytes())
.saturating_add(queued);
}
/// Runs frames until the boundary frame on top returns, and returns its value.
@@ -1904,16 +1940,18 @@ impl Interp {
None => {}
}
let proto = self.object(id)?.proto;
match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() {
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
match inherited {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"),
_ => {}
}
if !self.object(id)?.extensible {
// A name that an object of a host class with an indexer lacks is read with the indexer
// first, so assigning it throws what reading it throws.
if array_index(&k).is_none()
// A name that an object of a host class with an indexer lacks, and its prototypes lack
// too, is read with the indexer first, so assigning it throws what reading it throws.
if inherited.is_none()
&& array_index(&k).is_none()
&& let Some(f) = self.host_indexer(id)?
{
self.host_index(&f, id, Self::indexer_key(&k), false)?;
@@ -2792,9 +2830,12 @@ impl Interp {
return Err(self.type_error("apply was called on a value that is not a function"));
}
let list = args.get(1).cloned().unwrap_or(Value::Undefined);
let mut roots = vec![f.clone(), this.clone()];
roots.extend(args.iter().cloned());
let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?;
f = this;
this = args.first().cloned().unwrap_or(Value::Undefined);
args = self.list_from_array_like(&list)?;
args = expanded;
}
Func::Bound { target, this: bound_this, args: bound_args } => {
self.use_fuel()?;
@@ -3247,6 +3288,21 @@ impl Interp {
r
}
/// Starts a call to `f` with no frame running, for a promise job: a native or host function
/// runs now and gives `Some` with its result, and a function written in JavaScript gets a
/// boundary frame that the caller runs, and gives `None`. A host function called here cannot
/// wait for its result, since no script code is running; a function written in JavaScript
/// runs as the script's own code does.
pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec<Value>) -> JsResult<Option<Value>> {
self.reentry += 1;
let prepared = self.prepare_call(f, this, args);
self.reentry -= 1;
match prepared? {
Prepared::Done(v) => Ok(Some(v)),
Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None),
}
}
fn call_rooted(&mut self, f: Value, this: Value, args: Vec<Value>, saved: usize) -> JsResult<Value> {
match self.prepare_call(f, this, args)? {
Prepared::Done(v) => Ok(v),
@@ -4082,9 +4138,15 @@ impl Interp {
/// A description of a thrown value that runs no JavaScript: `Name: message` for an error,
/// the text of a primitive.
pub(crate) fn describe(&mut self, v: &Value) -> String {
let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() };
self.describe_prefix(v, usize::MAX)
}
/// [`Interp::describe`] with each string it reads cut to its first `max_units` code units
/// before it is copied.
pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String {
let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) };
let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) {
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()),
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)),
_ => None,
};
match (data(self, "name"), data(self, "message")) {
@@ -4094,6 +4156,26 @@ impl Interp {
(None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())),
}
}
/// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read
/// along its strings without copying them.
fn describe_hash(&self, o: ObjId) -> u64 {
let data = |k: &str| match self.find_property(o, &key(k)) {
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s),
_ => None,
};
let mut h = DescriptionHash::default();
match (data("name"), data("message")) {
(Some(n), Some(m)) if m.len() != 0 => {
n.for_each_chunk(|c| h.units(c));
h.text(": ");
m.for_each_chunk(|c| h.units(c));
}
(Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)),
(None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))),
}
h.finish()
}
}
/// A compile failure, before it becomes an exception or a run error.
+20
View File
@@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() {
assert_eq!(realm.run(src), Ok(JsValue::Number(42.0)));
}
#[test]
fn successive_apply_expansions_keep_getter_receivers_alive() {
for queued in [false, true] {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() });
let src = "var result; function callback(a) { result = this.kept + a; } \
var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \
var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};";
realm.run(src).unwrap();
let collections = realm.interp().heap.collections;
let call = if queued {
"Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));"
} else {
"Function.prototype.apply.apply(callback, outer);"
};
realm.run(call).unwrap();
assert!(realm.interp().heap.collections > collections);
assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}");
}
}
#[test]
fn to_number_skips_the_white_space_the_lexer_skips() {
let mut realm = small(Limits::default());
+20 -7
View File
@@ -26,7 +26,7 @@
//! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these
//! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`),
//! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String`
//! (15.5), `Boolean.prototype`'s `toString` and `valueOf` (15.6.4), `Number` (15.7), `Math` (15.8),
//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8),
//! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods
//! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1
//! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no
@@ -78,6 +78,14 @@
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
//! entry counts against the heap limit.
//!
//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section
//! 25.6, <https://262.ecma-international.org/11.0/#sec-promise-objects>): the constructor, `then`,
//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise
//! jobs a script queues run in order once its code has ended, before its run ends, on the run's
//! limits; a promise still rejected with no handler at the end is reported by
//! [`Realm::unhandled_rejections`]. [`Realm::add_es2015`] gives a realm made without the option
//! `Promise` for its next runs.
#![forbid(unsafe_code)]
pub mod ast;
@@ -121,7 +129,9 @@ pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostIte
pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts};
pub use lexer::{Goal, Lexer};
pub use number::to_string as number_to_string;
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE};
pub use realm::{
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
};
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
/// How a script is read.
@@ -145,11 +155,12 @@ pub struct Options {
/// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
/// with Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects.
/// A realm made with it off has the ES5.1 built-ins only, as the app's scripts expect. Those
/// built-ins are chosen when the realm is made: turning the option on or off later with
/// [`Realm::set_es2015`] changes the language later runs read, and does not add or remove
/// them. Runs with it on also convert `0b` and `0o` strings to numbers.
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, and
/// `Promise` with its job queue. A realm made with it off has the ES5.1 built-ins only, as the
/// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option
/// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does
/// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it.
/// Runs with it on also convert `0b` and `0o` strings to numbers.
pub es2015: bool,
}
@@ -266,6 +277,8 @@ mod host_tests;
#[cfg(test)]
mod interp_tests;
#[cfg(test)]
mod promise_tests;
#[cfg(test)]
mod symbol_tests;
#[cfg(test)]
mod tests;
+448
View File
@@ -0,0 +1,448 @@
//! `Promise` and the promise job queue in realms with [`Options::es2015`].
use super::*;
fn realm() -> Realm {
Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default())
}
fn run(src: &str) -> JsValue {
match realm().run(src) {
Ok(v) => v,
Err(e) => panic!("{src}\n{e:?}"),
}
}
fn string(src: &str) -> String {
match run(src) {
JsValue::String(s) => s,
other => panic!("{src}: {other:?}"),
}
}
/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran.
fn log(src: &str) -> String {
let mut r = realm();
if let Err(e) = r.run(&format!("var log = [];\n{src}")) {
panic!("{src}\n{e:?}");
}
match r.run("log.join(' ')") {
Ok(JsValue::String(s)) => s,
other => panic!("{src}: {other:?}"),
}
}
#[test]
fn an_extendscript_realm_has_no_promise() {
assert_eq!(Realm::new().run("typeof Promise").unwrap(), JsValue::String("undefined".into()));
assert_eq!(string("typeof Promise"), "function");
}
#[test]
fn adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() {
let mut r = Realm::new();
r.add_es2015();
assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into()));
assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into()));
assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. })));
r.set_es2015(true);
assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0));
}
#[test]
fn promise_prototype_cannot_be_replaced() {
let src = "var before = Promise.prototype; Promise.prototype = {}; \
var p = new Promise(function () {}); \
[Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()";
assert_eq!(string(src), "true,true,true");
}
#[test]
fn then_callbacks_run_after_the_scripts_code_in_order() {
let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\
new Promise(function (res) { log.push('executor'); res(2); }).then(function (v) { log.push('b' + v); });\n\
log.push('sync');";
assert_eq!(log(src), "executor sync a1 b2");
}
#[test]
fn jobs_run_first_in_first_out_and_a_jobs_jobs_join_the_end() {
let src = "var p = Promise.resolve();\n\
p.then(function () { log.push(1); Promise.resolve().then(function () { log.push(4); }); });\n\
p.then(function () { log.push(2); });\n\
p.then(function () { log.push(3); });";
assert_eq!(log(src), "1 2 3 4");
}
#[test]
fn a_thenable_is_adopted_in_a_later_job() {
let src = "var thenable = { then: function (res) { log.push('then'); res(7); } };\n\
Promise.resolve(thenable).then(function (v) { log.push('got' + v); });\n\
log.push('sync');";
assert_eq!(log(src), "sync then got7");
let rejecting = "var t = { then: function (res, rej) { rej('no'); res(1); } };\n\
new Promise(function (res) { res(t); }).then(null, function (r) { log.push('rejected ' + r); });";
assert_eq!(log(rejecting), "rejected no");
let throwing = "var t = { then: function (res) { res(1); throw new Error('late'); } };\n\
Promise.resolve(t).then(function (v) { log.push('kept ' + v); });";
assert_eq!(log(throwing), "kept 1");
}
#[test]
fn a_promise_resolved_with_itself_rejects_with_a_type_error() {
let src = "var res; var p = new Promise(function (r) { res = r; }); res(p);\n\
p.then(null, function (e) { log.push(e instanceof TypeError); });";
assert_eq!(log(src), "true");
}
#[test]
fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\
for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }";
let mut finished = 0;
for spare in (40_000..240_000).step_by(641) {
let mut r = realm();
let live = r.collect_garbage();
r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() });
match r.run(src) {
Ok(_) => finished += 1,
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue,
Err(e) => panic!("{spare}: {e:?}"),
}
r.set_limits(Limits::default());
assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}");
}
assert!(finished > 0);
}
#[test]
fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\
Promise.resolve(5).finally(function () { log.push('finally'); return 9; }).then(function (v) { log.push('kept ' + v); });\n\
Promise.all([1, Promise.resolve(2), { then: function (r) { r(3); } }]).then(function (v) { log.push('all ' + v.join(',')); });\n\
Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\
Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\
Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\
Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\
Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\
Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });";
let out = log(src);
for part in [
"caught x",
"finally",
"kept 5",
"all 1,2,3",
"rejected:r fulfilled:4",
"race fast",
"chars 2",
"not a list true",
"no length true",
"bad length true",
] {
assert!(out.contains(part), "{part} in {out}");
}
}
#[test]
fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() {
// `Promise.resolve` runs once for each input and appends to the input while it is read.
let src = "var resolve = Promise.resolve; var input;\n\
Promise.resolve = function (x) {\n\
if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\
return resolve.call(this, x);\n\
};\n\
input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\
input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });";
let out = log(src);
assert!(out.contains("array 1,2,3"), "{out}");
assert!(out.contains("object 1"), "{out}");
assert!(!out.contains("object 1,"), "{out}");
}
#[test]
fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() {
// A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap
// has room for. The combinator would stop at its first input.
let mut r = realm();
r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap();
let live = r.collect_garbage();
r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() });
let e = r.run("Promise.race(s)").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
r.set_limits(Limits::default());
assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0));
}
#[test]
fn calling_promise_without_new_or_without_an_executor_is_a_type_error() {
let mut r = realm();
for src in [
"Promise(function () {})",
"new Promise(1)",
"Promise.prototype.then.call({}, null)",
"Promise.resolve.call(1, 2)",
"Promise.all.call(Math.max, [])",
"Promise.resolve.call(() => {}, 1)",
"Promise.reject.call({ m() {} }.m, 1)",
"Promise.race.call((() => {}).bind(null), [])",
] {
match r.run(src) {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
}
#[test]
fn an_unhandled_rejection_is_reported_with_its_line() {
let mut r = realm();
r.run("var a = 1;\nPromise.reject(new Error('lost'));\nnew Promise(function () {\n throw new TypeError('also');\n});\nPromise.reject(2).catch(function () {});")
.unwrap();
let got: Vec<(String, u32)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.line)).collect();
assert_eq!(got, vec![("Error: lost".to_string(), 2), ("TypeError: also".to_string(), 4)]);
assert_eq!(r.unhandled_rejection_count(), 2);
assert!(r.unhandled_rejections().iter().all(|j| j.authored));
}
#[test]
fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() {
let mut r = realm();
r.run(
"function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\
var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
Promise.reject(ab);\n\
Promise.reject(new RangeError(ab));\n\
Promise.reject(rep('\\ud83d\\ude00', 600));\n\
Promise.reject(rep('x', 500));",
)
.unwrap();
let got: Vec<String> = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect();
let want = vec![
format!("{}…", "ab".repeat(250)),
format!("RangeError: {}…", "ab".repeat(244)),
format!("{}…", "\u{1F600}".repeat(500)),
"x".repeat(500),
];
assert_eq!(got, want);
}
#[test]
fn combinator_rejection_relays_keep_the_input_location() {
for method in ["all", "race"] {
let mut r = realm();
r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap();
let reported = r.unhandled_rejections();
assert_eq!(reported.len(), 1, "{method}: {reported:?}");
assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]);
assert!(reported[0].column > 0);
assert_eq!(reported[0].tag, r.script_tag());
}
let mut r = realm();
r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});")
.unwrap();
assert_eq!(r.unhandled_rejections().len(), 1);
assert_eq!(r.unhandled_rejections()[0].line, 3);
assert!(r.unhandled_rejections()[0].column > 0);
let mut r = realm();
r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap();
let reported = r.unhandled_rejections();
assert_eq!(reported.len(), 2);
assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}");
}
#[test]
fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() {
let mut r = realm();
r.run(
"var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
var e; try { null.x; } catch (x) { e = x; }\n\
e.message = ab;\n\
Promise.reject(e);\n\
try { null.x; } catch (x) { Promise.reject(x); }",
)
.unwrap();
let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect();
assert_eq!(got.len(), 2);
assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true));
assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]);
let interp = r.interp();
match interp.find_property(interp.global, &crate::heap::key("ab")) {
Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"),
other => panic!("{other:?}"),
}
}
#[test]
fn a_rejection_handled_in_a_later_job_is_not_reported() {
let mut r = realm();
r.run("var p = Promise.reject(1); Promise.resolve().then(function () { p.catch(function () {}); });").unwrap();
assert!(r.unhandled_rejections().is_empty());
assert_eq!(r.unhandled_rejection_count(), 0);
}
#[test]
fn a_run_that_fails_reports_no_rejections_and_drops_its_jobs() {
let mut r = realm();
let e = r.run("var ran = false; Promise.reject(1); Promise.resolve().then(function () { ran = true; }); throw 'stop';").unwrap_err();
assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Thrown, "stop"));
assert!(r.unhandled_rejections().is_empty());
assert_eq!(r.run("ran").unwrap(), JsValue::Bool(false));
}
#[test]
fn an_endless_then_chain_is_stopped_by_fuel() {
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 200_000, ..Limits::default() });
let e = r.run("function again() { return Promise.resolve().then(again); } again();").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
let e = r.run("var res; var p = new Promise(function (r) { res = r; }); function loop() { p.then(loop); } p.then(loop); res(1);").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
assert!(!r.is_running());
}
#[test]
fn each_job_takes_fuel() {
// `then` on a settled promise queues a job, and on a pending one it does not; the difference in
// fuel between 50 calls and none is the jobs' fuel.
let used = |start: &str, calls: usize| {
let mut r = realm();
r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() });
r.run(&format!("var p = {start};{}", "p.then();".repeat(calls))).unwrap();
1_000_000 - r.fuel_left()
};
let settled = used("Promise.resolve()", 50) - used("Promise.resolve()", 0);
let pending = used("new Promise(function () {})", 50) - used("new Promise(function () {})", 0);
assert_eq!(settled - pending, 50);
}
#[test]
fn more_jobs_than_the_queue_holds_end_the_run_with_a_clear_error() {
let mut r = realm();
r.interp().promises.max_jobs = 100;
let e = r.run("var p = Promise.resolve(); for (var i = 0; i < 200; i++) p.then(function () {});").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Jobs));
assert!(e.message.contains("more than 100 promise jobs"), "{}", e.message);
assert!(r.run("var q = Promise.resolve(); for (var i = 0; i < 50; i++) q.then(function () {}); 1").is_ok());
}
#[test]
fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() {
let mut r = realm();
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
r.start("var t = 0; Promise.resolve().then(function () { for (var i = 0; i < 5000; i++) t += i; }); 'done'").unwrap();
let mut paused_in_jobs = 0;
let v = loop {
match r.advance(500).unwrap() {
Progress::Paused => {
if r.interp().promises.draining {
paused_in_jobs += 1;
}
}
Progress::Done(v) => break v,
}
};
assert_eq!(v, JsValue::String("done".into()));
assert!(paused_in_jobs > 1, "{paused_in_jobs}");
assert!(!r.is_running());
assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0));
}
#[test]
fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() {
let mut r = realm();
r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap();
let v = loop {
match r.advance(1).unwrap() {
Progress::Paused => {
let interp = r.interp();
assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run");
}
Progress::Done(v) => break v,
}
};
assert_eq!(v, JsValue::String("done".into()));
assert!(!r.is_running());
}
#[test]
fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() {
let mut r = realm();
let flag = r.pause_flag();
r.define_function("pauseNow", move |_| {
flag.set(true);
Ok(JsValue::Undefined)
});
r.start("Promise.resolve().then(pauseNow); 'first'").unwrap();
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into())));
r.start("var a = 1; var b = 2; a + b").unwrap();
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0)));
}
#[test]
fn a_sliced_run_pauses_inside_a_finally_callback() {
let mut r = realm();
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
r.set_unbroken_fuel(5_000);
r.start(
"var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\
Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\
Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\
'done'",
)
.unwrap();
let mut paused_in_jobs = 0;
let v = loop {
match r.advance(500).unwrap() {
Progress::Paused => {
if r.interp().promises.draining {
paused_in_jobs += 1;
}
}
Progress::Done(v) => break v,
}
};
assert_eq!(v, JsValue::String("done".into()));
assert!(paused_in_jobs > 10, "{paused_in_jobs}");
assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into()));
}
#[test]
fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() {
let mut r = realm();
r.run(
"var log = [], settle = {};\n\
function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\
function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\
var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\
Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\
Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\
Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\
Promise.reject(4).finally(wait('d')).then(d[0], d[1]);",
)
.unwrap();
assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into()));
r.collect_garbage();
r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap();
assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into()));
}
#[test]
fn an_ended_sliced_run_drops_its_jobs() {
let mut r = realm();
r.start(
"var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });",
)
.unwrap();
let mut slices = 0;
while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining {
slices += 1;
assert!(slices < 1000);
}
assert!(r.is_running());
assert_eq!(r.interp().promises.queue_size().0, 1);
r.end();
assert!(!r.is_running());
assert_eq!(r.interp().promises.queue_bytes(), 0);
assert_eq!(r.interp().promises.queue_size(), (0, 0));
assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into()));
assert_eq!(r.run("after").unwrap(), JsValue::Bool(false));
}
+72 -14
View File
@@ -57,6 +57,23 @@ pub enum LimitKind {
Unbroken,
/// A host function ended the run ([`crate::HostError::Abort`]).
Host,
/// More promise jobs were waiting to run than a run may queue.
Jobs,
}
/// A promise the last run rejected that still had no rejection handler when the run ended
/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`,
/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rejection {
/// The reason, described as an uncaught exception's message is.
pub message: String,
pub line: u32,
pub column: u32,
/// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]).
pub tag: u32,
/// `message` is text the script supplied ([`RunError::authored`]).
pub authored: bool,
}
/// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an
@@ -172,6 +189,8 @@ pub struct Realm {
/// before the first script, for a script the realm did not compile, and once the tags are used
/// up.
script_tag: u32,
/// The unhandled rejections of the last run that ended successfully, and how many there were.
rejections: (Vec<Rejection>, usize),
}
impl Default for Realm {
@@ -189,7 +208,7 @@ impl Realm {
/// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it
/// counted together.
pub fn with_options(options: Options, limits: Limits) -> Self {
Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE }
Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) }
}
/// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default
@@ -218,6 +237,14 @@ impl Realm {
self.interp.reset_gc_threshold();
}
/// Gives a realm made without [`Options::es2015`] the `Promise` that option adds, for its next
/// runs; a realm that has it already is left as it is. It does not take it away again, and it
/// does not add the option's other built-ins (`Symbol` and the iterators). Call it between
/// runs.
pub fn add_es2015(&mut self) {
crate::builtins::promise::add_to(&mut self.interp);
}
/// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
/// `const` names earlier runs declared stay visible when it is turned off. A run begun with
/// [`Realm::start`] that is still going keeps the language it started with for the code it
@@ -247,19 +274,21 @@ impl Realm {
let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN });
}
/// Runs `source` as a script in the global environment and returns its completion value (the
/// value of the last expression statement that ran). A realm whose built-ins could not be
/// installed runs nothing and gives an internal error.
/// Runs `source` as a script in the global environment, then the promise jobs it queued, and
/// returns its completion value (the value of the last expression statement that ran). A realm
/// whose built-ins could not be installed runs nothing and gives an internal error.
pub fn run(&mut self, source: &str) -> Result<JsValue, RunError> {
let code = self.compile(source)?;
let result = self.interp.run_global(code, false);
let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v));
self.outcome(result)
}
/// Compiles `source` and readies the realm for a run.
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
self.script_tag = UNKNOWN_SOURCE;
self.rejections = (Vec::new(), 0);
let interp = &mut self.interp;
interp.end_jobs(false);
if let Some(message) = &interp.install_error {
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false });
}
@@ -330,11 +359,15 @@ impl Realm {
interp.constructing = false;
interp.resuming = None;
interp.passing = Value::Undefined;
interp.end_jobs(result.is_ok());
if let Some(es2015) = interp.next_es2015.take() {
interp.set_es2015(es2015);
}
match result {
Ok(v) => Ok(interp.to_js_value(&v)),
Ok(v) => {
self.rejections = interp.take_unhandled();
Ok(interp.to_js_value(&v))
}
Err(Abrupt::Throw(v)) => {
let message = interp.describe(&v);
let authored = interp.thrown_by_script(&v);
@@ -345,6 +378,11 @@ impl Realm {
let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host));
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false })
}
Err(Abrupt::Limit(LimitKind::Jobs)) => {
let max = interp.promises.max_jobs;
let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)");
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false })
}
Err(Abrupt::Limit(kind)) => {
Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false })
}
@@ -364,12 +402,14 @@ impl Realm {
/// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one
/// instruction), and pauses where it can resume: between two instructions of the script's own
/// code. A getter, a built-in's callback or another nested run has native frames under it, so
/// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned
/// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code
/// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback
/// written in JavaScript, and the run is done once the queue is empty. Once this has returned
/// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its
/// result ([`Realm::waits`]), the run does not advance: this gives an internal error.
pub fn advance(&mut self, slice: u64) -> Result<Progress, RunError> {
let interp = &mut self.interp;
if interp.frames.is_empty() {
if !interp.running() {
return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false });
}
if interp.waiting {
@@ -385,7 +425,7 @@ impl Realm {
let cap = slice.saturating_add(self.unbroken_fuel).min(total);
interp.fuel = cap;
interp.in_slice = true;
let r = interp.execute_slice(cap - slice.min(cap));
let r = interp.execute_run_slice(cap - slice.min(cap));
interp.in_slice = false;
let used = cap - interp.fuel;
interp.fuel = total - used;
@@ -400,7 +440,28 @@ impl Realm {
/// Is a run begun with [`Realm::start`] still going?
pub fn is_running(&self) -> bool {
!self.interp.frames.is_empty()
self.interp.running()
}
/// The promises the last run rejected that still had no rejection handler when it ended
/// successfully, in the order they were rejected: the first 20 of them. Empty after a run that
/// ended with an error, and until a run ends.
pub fn unhandled_rejections(&self) -> &[Rejection] {
&self.rejections.0
}
/// How many unhandled rejections the last run that ended successfully had, the ones
/// [`Realm::unhandled_rejections`] leaves out included.
pub fn unhandled_rejection_count(&self) -> usize {
self.rejections.1
}
/// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error.
pub fn source_of(&self, tag: u32) -> u32 {
match tag {
UNKNOWN_SOURCE => UNKNOWN_SOURCE,
tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE),
}
}
/// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's
@@ -483,10 +544,7 @@ impl Realm {
/// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which
/// includes code from an earlier script and from the sources given during its run.
pub fn error_source(&self) -> u32 {
match self.interp.error_tag {
UNKNOWN_SOURCE => UNKNOWN_SOURCE,
tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE),
}
self.source_of(self.interp.error_tag)
}
/// The source tag of the code the last error's `line` and `column` are in, which stays the same
+40
View File
@@ -221,6 +221,46 @@ impl Str {
pub(crate) fn to_rust_string(&self) -> String {
String::from_utf16_lossy(&self.flat())
}
/// The first `max_units` code units as a Rust string, read along the rope without flattening
/// it, so a long string is not copied whole.
pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String {
if self.len() <= max_units {
return self.to_rust_string();
}
let mut units = Vec::with_capacity(max_units);
let mut stack = vec![self.clone()];
while let Some(s) = stack.pop() {
let room = max_units - units.len();
if room == 0 {
break;
}
match &*s.0.borrow() {
Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]),
Node::Concat { left, right, .. } => {
stack.push(right.clone());
stack.push(left.clone());
}
Node::Taken => {}
}
}
String::from_utf16_lossy(&units)
}
/// Calls `f` with each run of code units in order, read along the rope without flattening it.
pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) {
let mut stack = vec![self.clone()];
while let Some(s) = stack.pop() {
match &*s.0.borrow() {
Node::Flat(units) => f(units),
Node::Concat { left, right, .. } => {
stack.push(right.clone());
stack.push(left.clone());
}
Node::Taken => {}
}
}
}
}
impl PartialEq for Str {
+146 -2
View File
@@ -40,6 +40,12 @@
//! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without
//! `test/annexB/` skips them; a folder there with no test to parse or run fails them.
//!
//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`:
//! those whose feature tags name only `Promise`, `Promise.allSettled` and
//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests
//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its
//! failures go to `promise-failures.txt`.
//!
//! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of
//! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with
//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and
@@ -58,7 +64,6 @@ use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize};
/// A test file's metadata, from its `/*--- … ---*/` block.
#[derive(Default)]
struct Meta {
@@ -364,7 +369,7 @@ fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> {
/// Globals and method names the interpreter does not provide yet: a test that names one, in its
/// own source or in a harness file it includes, is skipped.
const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \
const MISSING_BUILTINS: &str = "String Number Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \
WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array charAt charCodeAt fromCharCode substring substr split replace \
match search exec test toUpperCase toLowerCase trim toFixed toPrecision toExponential now";
@@ -899,6 +904,145 @@ fn run_annex_b(dir: &Path) {
assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display());
}
/// The feature tags a `test/built-ins/Promise` test may carry and still run: `Promise`,
/// `Promise.allSettled` and `Promise.prototype.finally`.
const PROMISE_FEATURES: &[&str] = &["Promise", "Promise.allSettled", "Promise.prototype.finally"];
#[test]
fn promise_builtins_run() {
let Some(dir) = suite_dir() else {
println!("test262 Promise: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_promise(&dir)).unwrap();
handle.join().unwrap();
}
/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global
/// `print` that collects its output; an `async` test passes when it prints
/// `Test262:AsyncTestComplete`.
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> {
let options = Options { es2015: true, ..Options::default() };
let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
let out = printed.clone();
realm.define_function("print", move |args| {
let line = match args.first() {
Some(JsValue::String(s)) => s.clone(),
Some(other) => format!("{other:?}"),
None => String::new(),
};
out.borrow_mut().push_str(&line);
out.borrow_mut().push('\n');
Ok(JsValue::Undefined)
});
let result = realm.run(script);
if asynchronous && result.is_ok() && negative_type.is_none() {
let printed = printed.borrow();
return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") {
Ok(())
} else {
Err(format!("printed {:?}", printed.trim()))
};
}
match (result, negative_type) {
(Ok(_), None) => Ok(()),
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
(Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => {
realm.bind_last_thrown("__thrown");
match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) {
Ok(JsValue::Bool(true)) => Ok(()),
_ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)),
}
}
(Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)),
}
}
/// Runs the tests under `test/built-ins/Promise` whose feature tags are all in
/// [`PROMISE_FEATURES`], whose code parses as ES5 and uses only the built-ins present, as sloppy
/// and strict code as [`run_tests`] does, `async` tests included. Prints the counts and writes the
/// failures to `promise-failures.txt` beside the suite.
fn run_promise(dir: &Path) {
let root = or_fail(inside(dir, "test/built-ins/Promise"));
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
// A harness file is named by the test's `includes:`, so it is read only inside `harness/`.
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
let done = harness("doneprintHandle.js");
let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]);
let mut groups: std::collections::BTreeMap<String, RunCounts> = std::collections::BTreeMap::new();
let (mut files, mut other_features) = (0usize, 0usize);
for path in or_fail(test_files(&root)) {
files += 1;
let source = or_fail(read_source(&path));
let meta = meta(&source);
if meta.features.iter().any(|f| !PROMISE_FEATURES.contains(&f.as_str())) {
other_features += 1;
continue;
}
let asynchronous = meta.flags.iter().any(|f| f == "async");
let tags = if meta.features.is_empty() { "no feature tag".to_string() } else { meta.features.join(", ") };
let counts = groups.entry(format!("{tags}, {}", if asynchronous { "async" } else { "sync" })).or_default();
let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution"));
if negative_parse || meta.flags.iter().any(|f| f == "module") {
counts.skipped += 1;
continue;
}
let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
if asynchronous {
includes.push_str(&done);
includes.push('\n');
}
if parse(&source, &Options::default()).is_err() || needs_missing_builtin(&[&source, &includes], &missing) {
counts.skipped += 1;
continue;
}
counts.tests += 1;
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
for &strict in modes(&meta) {
let mode = if strict { "strict" } else { "sloppy" };
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) {
Ok(Ok(())) => counts.passed += 1,
Ok(Err(why)) => {
counts.failed += 1;
counts.failures.push_str(&format!("{rel} ({mode}): {why}\n"));
}
Err(_) => {
counts.failed += 1;
counts.panicked += 1;
counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n"));
}
}
}
}
let mut all = RunCounts::default();
for (group, counts) in &groups {
println!("test262 built-ins/Promise, {group}: {}.", counts.summary());
all.tests += counts.tests;
all.skipped += counts.skipped;
all.passed += counts.passed;
all.failed += counts.failed;
all.panicked += counts.panicked;
all.failures.push_str(&counts.failures);
}
let report = dir.join("promise-failures.txt");
if let Err(e) = std::fs::write(&report, &all.failures) {
println!("could not write {}: {e}", report.display());
}
println!(
"test262 built-ins/Promise through the interpreter: {files} files, {other_features} with other feature tags left out; {}. Failures: {}",
all.summary(),
report.display()
);
assert!(all.tests > 0, "no Promise tests ran under {}", root.display());
assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display());
}
/// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and
/// strings, which run in a realm with [`Options::es2015`].
const SYMBOL_BUILT_INS: &[&str] = &[
+4 -4
View File
@@ -658,19 +658,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.toolbar.dock",
"Dock Toolbar",
"",
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}",
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` as a column of the dock along the window's left or right edge (omitted: the edge it docks at, else the edge it docked at last, the left at first), as dragging its title bar to that edge does; a hidden toolbar shows; `order` is its column's place in that edge's dock, 0 at the window's edge (omitted: the innermost, or where it is when it docks at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}, `pos` its top-left corner while it floats (else null)",
),
(
"window.toolbar.float",
"Float Toolbar",
"",
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}",
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in window points (both or neither, each from -1000000 to 1000000; omitted: where the dock floats a panel, and a floating toolbar stays where it is), as dragging its title bar out of the dock does; a hidden toolbar shows; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.list",
"List Toolbars",
"",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
),
("window.taskBar", "Contextual Task Bar", "", "{}"),
(
@@ -1525,7 +1525,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.corners",
"Corners…",
"",
"{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape",
"{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radii (relative|absolute), radius (pt, or with relative radii a percentage of each corner's own maximum); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape, as one command.batch undo step when relative radii give the corners different lengths",
),
(
"ui.simplifyAuto",
+89 -1
View File
@@ -1,5 +1,6 @@
//! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`,
//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters).
//! `group`, `help`, `helpUrl`, `visibleWhen` and `widget` keys of each one
//! (docs/plugins.md › Parameters).
//!
//! These keys are presentation only. A host from before them ignores them, so a plug-in that
//! declares them still installs there, and a plug-in is given every parameter whether its dialog
@@ -58,6 +59,48 @@ pub struct ParamUi {
/// Shown only while each parameter named here has one of the values listed for it.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub visible_when: BTreeMap<String, Vec<Value>>,
/// The control that shows a number: [`Widget::Slider`] adds a slider beside its field.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub widget: Option<Widget>,
}
/// The control a `number` or `int` parameter's row shows besides its number field (`widget`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Widget {
/// A slider over `min..max`, beside the number field.
Slider,
}
/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range.
const EXACT_INT: i64 = 1 << 53;
impl ParamUi {
/// The range a slider shows `spec`'s value over, when the parameter asks for one
/// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on.
pub fn slider_range(&self, spec: &ParamSpec) -> Option<std::ops::RangeInclusive<f64>> {
if self.widget != Some(Widget::Slider) {
return None;
}
match spec {
ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max),
ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64),
_ => None,
}
}
/// Checks `widget` against parameter `spec`; `bad` builds the error.
fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> {
if self.widget.is_none() || self.slider_range(spec).is_some() {
return Ok(());
}
match spec {
ParamSpec::Number { .. } | ParamSpec::Int { .. } => {
bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}"))
}
_ => bad("a slider is only for `number` and `int` parameters"),
}
}
}
/// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless
@@ -86,6 +129,9 @@ impl ParamUi {
return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes"));
}
}
if let Some((_, p)) = m.params.get(index) {
self.validate_slider(&p.spec, bad)?;
}
if self.visible_when.len() > MAX_CONDITIONS {
return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters"));
}
@@ -304,4 +350,46 @@ mod tests {
let fine = with("help", r#""Two\nlines.""#);
assert!(Manifest::parse(fine.as_bytes()).is_ok());
}
/// A `number` or `int` parameter with a range may ask for a slider; the key reads back as
/// written, and a parameter without it asks for none.
#[test]
fn slider_key_parses_and_round_trips() {
let m = Manifest::parse(
br#"{"id":"a","name":"x","kind":"filter","params":{
"area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"},
"count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"},
"plain":{"type":"number","min":0,"max":100,"default":10}}}"#,
)
.unwrap();
let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap());
assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0));
assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0));
assert_eq!(plain.ui.slider_range(&plain.spec), None);
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider"));
}
#[test]
fn slider_keys_that_cannot_apply_are_refused() {
let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#);
for bad in [
// Only numbers have a slider, over a range that has room to move.
r#"{"type":"bool","widget":"slider"}"#,
r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#,
r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#,
r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#,
r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#,
// A control the host doesn't have.
r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#,
] {
assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}");
}
// A command's parameters are checked the same way.
let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#);
assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok());
assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err());
let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#);
assert!(Manifest::parse(fine.as_bytes()).is_ok());
}
}
+112 -1
View File
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::dialog::ParamUi;
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission};
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
use crate::{Error, Result};
/// Longest manifest the host reads.
@@ -456,6 +456,11 @@ pub struct Manifest {
/// lists them. Left out or empty, it is given paths and compound paths alone.
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
pub inputs: Vec<String>,
/// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at
/// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or
/// empty, every kind it reads stays read-only.
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")]
pub writes: Vec<String>,
/// The parts of the document a run is given in `_context.document`, by
/// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command
/// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty,
@@ -519,6 +524,7 @@ impl Manifest {
api: 1,
permissions: None,
inputs: Vec::new(),
writes: Vec::new(),
context: Vec::new(),
params: Vec::new(),
extensions: Vec::new(),
@@ -591,6 +597,7 @@ impl Manifest {
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
}
self.validate_inputs()?;
self.validate_writes()?;
self.validate_context()?;
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
@@ -691,6 +698,37 @@ impl Manifest {
Ok(())
}
/// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at
/// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`.
fn validate_writes(&self) -> Result<()> {
if self.writes.is_empty() {
return Ok(());
}
if self.kind != Kind::Filter {
return Err(Error::Manifest("only a filter declares `writes`".into()));
}
for (i, name) in self.writes.iter().enumerate() {
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
if InputKind::parse(name).is_none() {
return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance")));
}
if self.writes.get(..i).is_some_and(|before| before.contains(name)) {
return Err(Error::Manifest(format!("`writes` lists `{shown}` twice")));
}
if !self.inputs.contains(name) {
return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list")));
}
}
if self.api < WRITES_API {
return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later")));
}
let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name()));
if !listed(Permission::DocWrite) {
return Err(Error::Manifest("`writes` needs the permission `doc.write`".into()));
}
Ok(())
}
/// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect
/// with commands, at `api` 3 or later lists any, with a `permissions` list that holds
/// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]).
@@ -764,6 +802,11 @@ impl Manifest {
self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect()
}
/// The kinds among those it reads that it may change (`writes`).
pub fn write_kinds(&self) -> Vec<InputKind> {
self.writes.iter().filter_map(|n| InputKind::parse(n)).collect()
}
/// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16
/// lower-case letters and digits; other kinds list none.
fn validate_extensions(&self) -> Result<()> {
@@ -933,6 +976,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
}
}
/// Reads `writes` as [`input_names`] reads `inputs`.
fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance");
match Value::deserialize(d)? {
Value::Null => Ok(Vec::new()),
Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(),
_ => Err(wrong()),
}
}
/// Reads `context`: a list of names (`null`: none). Anything else is the error
/// [`Manifest::validate_context`] gives a wrong entry.
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
@@ -1419,6 +1472,64 @@ mod tests {
assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice"));
}
/// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with
/// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key
/// isn't written back. Anything else is refused naming `writes`.
#[test]
fn a_filter_at_api_3_lists_the_kinds_it_writes() {
let m = Manifest::parse(
br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#,
)
.unwrap();
assert_eq!(m.write_kinds(), InputKind::ALL);
assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"]));
let some = Manifest::parse(
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#,
)
.unwrap();
assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image]));
for none in [
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#,
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#,
r#"{"id":"a","name":"x","kind":"filter","writes":null}"#,
] {
let m = Manifest::parse(none.as_bytes()).unwrap();
assert!(m.write_kinds().is_empty(), "{none}");
assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}");
}
let rw = r#""permissions":["doc.read","doc.write"]"#;
for (bad, says) in [
(
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#),
"`writes` names an unknown object kind `text`",
),
(
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#),
"`writes` lists `type` twice",
),
(
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#),
"`writes` lists `image`, which `inputs` doesn't list",
),
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"),
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"),
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"),
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"),
(
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(),
"`writes` needs the permission `doc.write`",
),
(
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(),
"`inputs` needs the permission `doc.read`",
),
(r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"),
] {
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
/// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document
/// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks
/// for approval. Left out or empty, it asks for none and isn't written back. Anything else is
+79 -31
View File
@@ -82,6 +82,10 @@ pub struct OutObject {
/// A read-only input object (type, an image or a symbol instance) returned as it was given:
/// it stays as it is, and new objects listed after it go above it.
pub kept: bool,
/// A type object, an image or a symbol instance of a kind the filter may change (`writes`)
/// returned with changes: the fields it changes, by their names in the input, checked when
/// they are applied ([`apply_output`]).
pub edit: Option<serde_json::Map<String, Value>>,
}
/// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's
@@ -295,7 +299,7 @@ fn affine_json(xf: Affine) -> Value {
/// paragraphs: [style]}` with the native character and paragraph attributes, one paragraph style
/// for each paragraph, and `truncated`: true, with no runs or paragraphs, past [`MAX_INPUT_TEXT`]
/// or [`MAX_INPUT_RUNS`];
/// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
/// - an image (`"image"`): `opacity` (0 to 1), `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
/// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`]
/// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks
/// through the working CMYK profile, as sRGB). A linked image's file and path are never read or
@@ -332,6 +336,7 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left
if let Some(q) = n.image_quad() {
o["corners"] = json!(q.map(|p| [p.x, p.y]));
}
o["opacity"] = json!(n.opacity);
o["pixelSize"] = json!([im.width, im.height]);
o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode));
o["linked"] = json!(im.link.is_some());
@@ -672,6 +677,15 @@ fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
Ok(p)
}
/// An object's name from plug-in output (`null`: no name), without control characters and at most
/// 256 of them.
fn decode_name(n: &Value, at: &str) -> Result<String> {
Ok(match n {
Value::Null => String::new(),
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
})
}
fn opt<'a>(o: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a Value> {
o.get(key).filter(|v| !v.is_null())
}
@@ -693,11 +707,7 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result<OutObject>
});
}
if let Some(n) = o.get("name") {
let name = match n {
Value::Null => String::new(),
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
};
out.name = Some(name);
out.name = Some(decode_name(n, at)?);
}
if let Some(p) = opt(o, "path") {
out.path = Some(decode_path(p, &format!("{at}.path"), anchors)?);
@@ -813,8 +823,18 @@ pub fn decode_output(bytes: &[u8]) -> Result<Output> {
/// differs, before anything changes. Each object is parsed from `input` only to compare it, one at
/// a time, and an object that can't be read from there is an error.
pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result<Output> {
decode_output_writing(bytes, input, read_only, &[])
}
/// [`decode_output_with`] for a filter that may change the objects of kinds `writes` among them
/// (its manifest's `writes`): such an object is still listed exactly once, and an entry for it may
/// leave fields out, which keep their values, and give its name, its transform, and type's
/// `text.runs` and `text.paragraphs`, an image's `opacity` or an instance's `symbolId` changed.
/// Such an entry is [`OutObject::edit`] with the fields it changes; one that changes nothing is
/// [`OutObject::kept`]. Any other field must be as given, and the error names the first that isn't.
pub fn decode_output_writing(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Output> {
let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
let objects = decode_objects(&v, input, read_only)?;
let objects = decode_objects(&v, input, read_only, writes)?;
let document_data = match v.get_mut("documentData").map(Value::take) {
None => None,
Some(Value::Null) => Some(None),
@@ -896,12 +916,12 @@ fn draws_nothing(c: char) -> bool {
/// declined (the message reaches the user). A live effect's other keys don't matter.
pub fn decode(bytes: &[u8]) -> Result<Vec<OutObject>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
decode_objects(&v, &[], &HashMap::new())
decode_objects(&v, &[], &HashMap::new(), &[])
}
/// The objects of output `v`, or its decline; entries for `read_only` objects as
/// [`decode_output_with`] reads them.
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<Vec<OutObject>> {
/// [`decode_output_writing`] reads them, those of kinds `writes` changeable.
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Vec<OutObject>> {
if let Some(e) = declined(v) {
return Err(e);
}
@@ -910,6 +930,8 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
}
let mut anchors = 0;
// Bytes of type text the output writes, over all its objects.
let mut text = 0;
let mut returned: HashSet<NodeId> = HashSet::new();
let out = objects
.iter()
@@ -920,12 +942,19 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
if !returned.insert(id) {
return Err(out_err(&at, "is listed twice"));
}
let kept = OutObject { id: Some(id), kept: true, ..OutObject::default() };
// `{"id": …}` alone keeps the object, so there is nothing to compare it with.
if o.as_object().is_none_or(|m| m.len() != 1) {
let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
let Some(entry) = o.as_object().filter(|m| m.len() != 1) else { return Ok(kept) };
let given: Value = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
let kind = given.get("type").and_then(Value::as_str).and_then(InputKind::parse).filter(|k| writes.contains(k));
let Some(kind) = kind else {
check_unchanged(o, &given, &at)?;
}
Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() })
return Ok(kept);
};
Ok(match writes::changes(entry, &given, kind, &at, &mut text)? {
Some(edit) => OutObject { id: Some(id), edit: Some(edit), ..OutObject::default() },
None => kept,
})
}
None => decode_object(o, &format!("objects[{i}]"), &mut anchors),
})
@@ -951,28 +980,40 @@ fn output_id(o: &Value) -> Option<NodeId> {
/// numbers compared by value. Otherwise the error names the first field that differs
/// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as
/// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the
/// plug-in's.
/// plug-in's. An image's `opacity`, which filters are given from plug-in API level 3, may be left
/// out, so an entry that a filter built for level 2 writes as it was given there still matches.
fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> {
let changed = match (o, given) {
(Value::Object(x), Value::Object(y)) => {
let mut keys: Vec<&String> = x.keys().collect();
keys.sort();
keys.into_iter().find_map(|k| match y.get(k) {
Some(q) => first_difference(&x[k], q, k),
None => Some(k.clone()),
})
keys.into_iter()
.find_map(|k| match y.get(k) {
Some(q) => first_difference(&x[k], q, k),
None => Some(k.clone()),
})
.or_else(|| {
let image = y.get("type").and_then(Value::as_str) == Some(InputKind::Image.name());
let mut missing: Vec<&String> = y.keys().filter(|k| !x.contains_key(*k) && !(image && *k == "opacity")).collect();
missing.sort();
missing.first().map(|k| (*k).clone())
})
}
_ => None,
_ => first_difference(o, given, ""),
};
match changed.or_else(|| first_difference(o, given, "")) {
match changed {
None => Ok(()),
Some(field) => {
let field = crate::permissions::display_text(&field, crate::permissions::MAX_SHOWN_FIELD);
Err(out_err(at, format!("read-only field '{field}' changed")))
}
Some(field) => Err(read_only_changed(at, &field)),
}
}
/// The error for an entry at `at` that changes read-only `field`, which is shown as
/// [`crate::permissions::display_text`] shows a manifest string.
fn read_only_changed(at: &str, field: &str) -> Error {
let field = crate::permissions::display_text(field, crate::permissions::MAX_SHOWN_FIELD);
out_err(at, format!("read-only field '{field}' changed"))
}
/// The path of the first place `a` and `b` differ (`""`: they differ as a whole), `None` when they
/// are the same JSON with numbers compared by value.
fn first_difference(a: &Value, b: &Value, at: &str) -> Option<String> {
@@ -1328,7 +1369,9 @@ impl Plan {
/// input object, just below the first one listed after them (at the first input object's place
/// when the output keeps none; on top of `parent` when there were no inputs). Input objects missing
/// from the output are deleted. An object's effect records replace its own once `admit` lets them
/// in. Returns the resulting objects in output order (to select).
/// in. Type, images and symbol instances stay as they are, or take the changes of their
/// [`OutObject::edit`] once each value is checked. Returns the resulting objects in output order
/// (to select).
pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>, parent: Option<NodeId>, admit: AdmitEffects) -> Result<Vec<NodeId>> {
let wanted: HashSet<NodeId> = inputs.iter().copied().collect();
let mut originals: HashMap<NodeId, Node> = HashMap::new();
@@ -1353,12 +1396,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>,
out_err(&at, format!("{} is not the id of an input object", id.0))
}
})?;
// Type, images and symbol instances are only read: writing one would make it a path.
if input_kind(&n).is_some() && !o.kept {
return Err(out_err(&at, format!("{} is read-only", id.0)));
}
// Type, images and symbol instances change only through the fields a filter that
// may write them returns: writing one as a path would make it a path.
let kept = o.kept;
if !kept {
if input_kind(&n).is_some() && !kept {
let Some(edit) = &o.edit else { return Err(out_err(&at, format!("{} is read-only", id.0))) };
writes::apply(doc, &mut n, edit, &format!("{at} (id {})", id.0))?;
} else if o.edit.is_some() {
return Err(out_err(&at, format!("{} is not type, an image or a symbol instance", id.0)));
} else if !kept {
write(doc, &mut n, o, &at, admit)?;
}
if !run.is_empty() {
@@ -1415,5 +1461,7 @@ pub fn output_geometry(objects: Vec<OutObject>) -> PathData {
PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect())
}
mod writes;
#[cfg(test)]
mod tests;
+490 -1
View File
@@ -1066,7 +1066,8 @@ fn a_changed_field_is_named_escaped_and_short() {
}
/// A filter given read-only objects returns each one as `{"id": …}` or exactly as given (numbers by
/// value), and they stay as they are, new objects listed after one going just above it. Any change,
/// value; an image may leave out its `opacity`), and they stay as they are, new objects listed
/// after one going just above it. Any change,
/// an object left out or listed twice, and a new object of such a kind are refused before anything
/// changes.
#[test]
@@ -1087,6 +1088,14 @@ fn read_only_kind_field_and_omission_refuse() {
let mut echo = input.clone();
echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]);
assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok());
// An image without `opacity`, as plug-in API level 2 gave it, is the image as given.
let mut echo = input.clone();
for i in [4, 5] {
assert_eq!(echo["objects"][i]["type"], json!("image"));
echo["objects"][i].as_object_mut().unwrap().remove("opacity");
}
let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap();
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5);
// So is an id written as a float; a fractional one names no object.
let id = input["objects"][3]["id"].as_u64().unwrap();
let mut echo = input.clone();
@@ -1151,6 +1160,486 @@ fn read_only_kind_field_and_omission_refuse() {
assert_eq!(d, before);
}
/// [`mixed`] with a second symbol, "Moon", and its targets and input for a filter that reads and may
/// change every kind.
fn writable() -> (Document, Vec<NodeId>, Vec<u8>, ReadOnlySpans, [NodeId; 5]) {
let (mut d, _, layer, extra) = mixed();
let art = Arc::new(Node::path(d.alloc_id(), square(5.0), Appearance::default()));
d.symbols.push(vectorcraft_doc::Symbol { name: "Moon".into(), art, dynamic: false });
let targets = filter_targets_with(&d, &[layer], &InputKind::ALL);
let (bytes, read_only) = encode_input_with(&d, &targets, &InputKind::ALL, usize::MAX).unwrap();
(d, targets, bytes, read_only, extra)
}
/// Decodes `out` for [`writable`]'s input with `writes` and applies it to `d`.
fn write_out(
d: &mut Document,
targets: &[NodeId],
bytes: &[u8],
read_only: &ReadOnlySpans,
writes: &[InputKind],
out: &Value,
) -> Result<Vec<NodeId>> {
let out = decode_output_writing(out.to_string().as_bytes(), bytes, read_only, writes)?;
apply_output(d, targets, out.objects, None, &keep)
}
/// A filter that may write type, images and symbol instances changes type's runs and character
/// attributes, an image's transform and opacity, and the symbol and transform of an instance,
/// with entries that give only the fields they change. What it writes reads back the same. An
/// exact echo, `{"id": …}` alone and fields given as they were (numbers by value) change nothing.
#[test]
fn writable_kinds_take_type_runs_image_placement_and_instance_symbols() {
use vectorcraft_doc::{CharStyle, ParaStyle};
let (mut d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
let before = d.clone();
let all = &InputKind::ALL;
let echo = decode_output_writing(&bytes, &bytes, &read_only, all).unwrap();
assert!(echo.objects.iter().all(|o| o.edit.is_none()));
apply_output(&mut d, &targets, echo.objects, None, &keep).unwrap();
assert_eq!(d, before, "an exact echo changes nothing");
let ro = |id: NodeId| json!({"id": id.0});
let paths: Vec<Value> = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect();
let with = |entries: Vec<Value>| {
let objects = [paths.clone(), entries].concat();
json!({ "objects": objects })
};
let same = with(vec![
json!({"id": text.0, "transform": [1, 0, 0, 1, 5, 50], "name": "T"}),
json!({"id": embedded.0, "opacity": 1}),
ro(linked),
json!({"id": star.0, "symbolId": "Star"}),
ro(ghost),
]);
let out = decode_output_writing(same.to_string().as_bytes(), &bytes, &read_only, all).unwrap();
assert!(out.objects.iter().all(|o| o.edit.is_none()));
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5, "fields given as they were change nothing");
// The changes, each entry giving only what it changes.
let big = CharStyle { size: 24.0, ..CharStyle::default() };
let runs = json!([{"text": "Bye\n", "style": CharStyle::default()}, {"text": "now", "style": big}]);
let out = with(vec![
json!({"id": text.0, "name": "Renamed", "text": {"runs": runs}}),
json!({"id": embedded.0, "transform": [1, 0, 0, 1, 10, 20], "opacity": 0.5}),
ro(linked),
json!({"id": star.0, "symbolId": "Moon", "transform": [1, 0, 0, 1, 50, 0]}),
ro(ghost),
]);
let made = write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
assert_eq!(made.len(), targets.len());
let node = |id: NodeId| d.node(id).unwrap().clone();
let NodeKind::Text(t) = &node(text).kind else { panic!("type") };
assert_eq!((t.plain_text().as_str(), t.runs[1].style.size), ("Bye\nnow", 24.0));
assert_eq!(t.para_at(1).space_before, 6.0, "paragraphs keep their styles");
assert_eq!(t.para_at(0), &ParaStyle::default());
assert_eq!(node(text).name.as_deref(), Some("Renamed"));
let NodeKind::Image(im) = &node(embedded).kind else { panic!("image") };
assert_eq!((im.xf, node(embedded).opacity), (Affine::new([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), 0.5));
assert_eq!(node(star).kind, NodeKind::SymbolInstance { symbol: "Moon".into(), xf: Affine::translate((50.0, 0.0)) });
for id in [linked, ghost] {
assert_eq!(d.node(id), before.node(id), "objects returned by id stay as they were");
}
// Read again, the changed objects give what was written.
let read = |id: NodeId| encode_read_only(&d, d.node(id).unwrap()).unwrap();
assert_eq!(read(text)["text"]["runs"], runs);
assert_eq!((&read(embedded)["transform"], &read(embedded)["opacity"]), (&json!([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), &json!(0.5)));
assert_eq!((&read(star)["symbolId"], &read(star)["transform"]), (&json!("Moon"), &json!([1.0, 0.0, 0.0, 1.0, 50.0, 0.0])));
assert!(read(star).get("missing").is_none());
// An instance of a symbol the document lacks can point to one it has.
let mut d = before.clone();
let out = with(vec![ro(text), ro(embedded), ro(linked), ro(star), json!({"id": ghost.0, "symbolId": "Star"})]);
write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
assert!(matches!(&d.node(ghost).unwrap().kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Star"));
}
/// An entry that changes a field its kind can't change, a kind the manifest doesn't list in
/// `writes`, or gives a value out of range is refused naming the object and the field, before
/// anything changes.
#[test]
fn bad_writes_are_refused_naming_the_object_and_the_field() {
use vectorcraft_doc::CharStyle;
let (d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
let input: Value = serde_json::from_slice(&bytes).unwrap();
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
let style = serde_json::to_value(CharStyle::default()).unwrap();
let styled = |f: &dyn Fn(&mut Value)| {
let mut s = style.clone();
f(&mut s);
json!([{"text": "Hi\nthere", "style": s}])
};
let (t, e, l, s) = (text.0, embedded.0, linked.0, star.0);
let (ti, ei, si) = (at(text), at(embedded), at(star));
let cases: Vec<(NodeId, Value, &[InputKind], String)> = vec![
(text, json!({"text": {"kind": "area"}}), &InputKind::ALL, format!("objects[{ti}] (id {t}): read-only field 'text.kind' changed")),
(text, json!({"text": {"x": 1}}), &InputKind::ALL, format!("(id {t}): read-only field 'text.x' changed")),
(text, json!({"bounds": [0, 0, 1, 1]}), &InputKind::ALL, format!("(id {t}): read-only field 'bounds[0]' changed")),
(text, json!({"opacity": 0.5}), &InputKind::ALL, format!("(id {t}): read-only field 'opacity' changed")),
(text, json!({"text": {"runs": []}}), &InputKind::ALL, "text.runs: type needs at least one run".into()),
(
text,
json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}),
&InputKind::ALL,
"text.runs[0].style: unknown key 'fontSzie'".into(),
),
(
text,
json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}),
&InputKind::ALL,
"text.runs[0].style.size: `size` must be from 0.1 to 1296".into(),
),
(text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()),
(
text,
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(" "))}}),
&InputKind::ALL,
"font_family: must be 1-256 printable characters".into(),
),
(
text,
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(format!(" {}", "a".repeat(256))))}}),
&InputKind::ALL,
"font_family: must be 1-256 printable characters".into(),
),
(
text,
json!({"text": {"runs": styled(&|s| s["fill"] = json!({"type": "solid", "color": s["fill"]["color"], "tintt": 0.5}))}}),
&InputKind::ALL,
"text.runs[0].style.fill: unknown key 'tintt'".into(),
),
(
text,
json!({"text": {"runs": styled(&|s| s["stroke"] = json!({"type": "none", "pattern": "Dots"}))}}),
&InputKind::ALL,
"text.runs[0].style.stroke: unknown key 'pattern'".into(),
),
(
text,
json!({"text": {"runs": [{"text": "A\nB\nC", "style": style}], "paragraphs": input["objects"][at(text)]["text"]["paragraphs"]}}),
&InputKind::ALL,
"text.paragraphs: expected 3 paragraph styles, one per paragraph".into(),
),
(text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()),
(text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")),
(text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()),
(text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()),
(text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()),
(text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()),
(
text,
json!({"text": {"paragraphs": [{"hyphenation": {"wordLongerThen": 3}}, {}]}}),
&InputKind::ALL,
"text.paragraphs[0].hyphenation: unknown key 'wordLongerThen'".into(),
),
(
text,
json!({"text": {"paragraphs": [{"justification": {"wordSpacng": [80, 100, 133]}}, {}]}}),
&InputKind::ALL,
"text.paragraphs[0].justification: unknown key 'wordSpacng'".into(),
),
(
text,
json!({"text": {"paragraphs": [{}, {"tabs": [{"position": 36}, {"position": 72, "aling": "center"}]}]}}),
&InputKind::ALL,
"text.paragraphs[1].tabs[1]: unknown key 'aling'".into(),
),
(text, json!({"text": {"paragraphs": [{"list": {"levl": 2}}, {}]}}), &InputKind::ALL, "text.paragraphs[0].list: unknown key 'levl'".into()),
(
text,
json!({"text": {"runs": styled(&|s| s["stroke_dash"] = json!({"pattern": [2, 2], "ofset": 1}))}}),
&InputKind::ALL,
"text.runs[0].style.stroke_dash: unknown key 'ofset'".into(),
),
(
text,
json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}),
&InputKind::ALL,
"holds the character of an inline graphic".into(),
),
(text, json!({"text": {"paragraphs": [{}]}}), &InputKind::ALL, "text.paragraphs: expected 2 paragraph styles, one per paragraph".into()),
(text, json!({"transform": [1, 0, 0, 0, 0, 0]}), &InputKind::ALL, format!("objects[{ti}] (id {t}).transform: flattens the object")),
(text, json!({"transform": [1, 0, 0, 1, 1e9, 0]}), &InputKind::ALL, "transform: a number is out of range".into()),
(text, json!({"transform": [1, 0, null, 0, 1, 10, 20]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
(text, json!({"transform": [1, 0, 0, 1, 10]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
(text, json!({"transform": [1, 0, 0, 1]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
(embedded, json!({"pixelSize": [3, 1]}), &InputKind::ALL, format!("(id {e}): read-only field 'pixelSize[0]' changed")),
(embedded, json!({"opacity": 2}), &InputKind::ALL, format!("objects[{ei}] (id {e}).opacity: must be a number from 0 to 1")),
(embedded, json!({"opacity": "half"}), &InputKind::ALL, "opacity: must be a number from 0 to 1".into()),
(linked, json!({"linked": false}), &InputKind::ALL, format!("(id {l}): read-only field 'linked' changed")),
(embedded, json!({"opacity": 0.5}), &[InputKind::Type, InputKind::SymbolInstance], format!("(id {e}): read-only field 'opacity' changed")),
(
star,
json!({"symbolId": "Nowhere"}),
&InputKind::ALL,
format!("objects[{si}] (id {s}).symbolId: 'Nowhere' is not a symbol in this document"),
),
(star, json!({"symbolId": 7}), &InputKind::ALL, "symbolId: must be the name of a symbol".into()),
(star, json!({"overrides": {"a": 1}}), &InputKind::ALL, format!("(id {s}): read-only field 'overrides.a' changed")),
(ghost, json!({"missing": false}), &InputKind::ALL, "read-only field 'missing' changed".into()),
(star, json!({"symbolId": "Moon"}), &[InputKind::Type], format!("(id {s}): read-only field 'symbolId' changed")),
];
for (id, entry, writes, says) in cases {
let mut out = input.clone();
let mut e = entry.clone();
e["id"] = json!(id.0);
out["objects"][at(id)] = e;
let mut doc = d.clone();
let err = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
assert!(err.contains(&says), "{entry}: {says}: {err}");
assert_eq!(doc, d, "{entry}: nothing changed");
}
// Leaving a writable object out is still refused: it isn't deleted.
let mut out = input.clone();
out["objects"].as_array_mut().unwrap().remove(at(star));
let e = write_out(&mut d.clone(), &targets, &bytes, &read_only, &InputKind::ALL, &out).unwrap_err().to_string();
assert!(e.contains(&format!("objects (id {s}): a read-only object was left out")), "{e}");
}
/// The text a filter writes to one type object is held to [`MAX_INPUT_TEXT`] bytes and
/// [`MAX_INPUT_RUNS`] runs and paragraphs, as the text it is given; type given as `truncated`
/// keeps its text, though it can still move.
#[test]
fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() {
use vectorcraft_doc::{CharStyle, TextObject};
let (mut d, _, layer, [text, ..]) = mixed();
let long = Node::new(
d.alloc_id(),
NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), &"x".repeat(MAX_INPUT_TEXT + 1), CharStyle::default()))),
);
let long = d.insert(Some(layer), usize::MAX, long).unwrap();
let targets = filter_targets_with(&d, &[layer], &[InputKind::Type]);
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
let input: Value = serde_json::from_slice(&bytes).unwrap();
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
assert_eq!(input["objects"][at(long)]["truncated"], json!(true));
let style = serde_json::to_value(CharStyle::default()).unwrap();
let run = |s: String| json!({"text": s, "style": style});
let writes = &[InputKind::Type];
for (id, text_v, says) in [
(text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")),
(text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
(text, json!({"runs": [run("\n".repeat(MAX_INPUT_RUNS))]}), format!("{} paragraphs (limit {MAX_INPUT_RUNS})", MAX_INPUT_RUNS + 1)),
(text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
(long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()),
] {
let mut out = input.clone();
out["objects"][at(id)] = json!({"id": id.0, "text": text_v});
let mut doc = d.clone();
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
assert!(e.contains(&says), "{says}: {e}");
assert_eq!(doc, d);
}
// At the limit the text is written; truncated type still moves.
let mut out = input.clone();
out["objects"][at(text)] = json!({"id": text.0, "text": {"runs": [run("x".repeat(MAX_INPUT_TEXT))]}});
out["objects"][at(long)] = json!({"id": long.0, "transform": [1, 0, 0, 1, 3, 4]});
write_out(&mut d, &targets, &bytes, &read_only, writes, &out).unwrap();
assert!(matches!(&d.node(text).unwrap().kind, NodeKind::Text(t) if t.plain_text().len() == MAX_INPUT_TEXT));
assert!(
matches!(&d.node(long).unwrap().kind, NodeKind::Text(t) if t.xf == Affine::translate((3.0, 4.0)) && t.plain_text().len() == MAX_INPUT_TEXT + 1)
);
}
/// An inline graphic in type stays as it was, in its place among the inline graphics: the runs
/// around it can change, and adding, removing or changing one is refused.
#[test]
fn inline_graphics_in_written_type_stay_as_they_were() {
use vectorcraft_doc::{CharStyle, InlineArt, TextObject, TextRun};
let (mut d, _, layer, _) = mixed();
let mut t = TextObject::point(Point::new(0.0, 0.0), "A", CharStyle::default());
t.runs = vec![
TextRun::new("A", CharStyle::default()),
TextRun::inline(InlineArt::new("Star"), CharStyle::default()),
TextRun::new("B", CharStyle::default()),
];
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
let targets = vec![id];
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
let input: Value = serde_json::from_slice(&bytes).unwrap();
let runs = input["objects"][0]["text"]["runs"].clone();
let writes = &[InputKind::Type];
let with = |runs: Value| json!({"objects": [{"id": id.0, "text": {"runs": runs}}]});
let mut changed = runs.clone();
changed[0]["text"] = json!("Before ");
changed[2]["text"] = json!(" after");
let mut doc = d.clone();
write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(changed)).unwrap();
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
assert_eq!(t.plain_text(), "Before \u{FFFC} after");
assert_eq!(t.runs[1].inline.as_ref().map(|a| a.symbol.as_str()), Some("Star"));
let mut moved = runs.clone();
moved[1]["inline"]["symbol"] = json!("Moon");
let without = json!([runs[0], runs[2]]);
let doubled = json!([runs[0], runs[1], runs[1], runs[2]]);
for bad in [moved, without, doubled] {
let mut doc = d.clone();
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(bad.clone())).unwrap_err().to_string();
assert!(e.contains("inline graphics can't be added, removed, reordered or changed"), "{bad}: {e}");
assert_eq!(doc, d);
}
}
/// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs
/// stays the same, and otherwise the styles follow the paragraphs' text: a paragraph whose text
/// stays keeps its style, also when changes are made at two places, a paragraph added at the start
/// takes the style of the next one and one added later the style of the one before it, and joining
/// two paragraphs keeps the first one's style.
#[test]
fn written_runs_without_paragraphs_keep_each_paragraph_s_style() {
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
let (mut d, _, layer, _) = mixed();
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB\nC", CharStyle::default());
let styled = |justify| ParaStyle { justify, ..ParaStyle::default() };
t.set_paragraph_styles(vec![styled(Justify::Left), styled(Justify::Center), styled(Justify::Right)]);
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
let targets = vec![id];
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
let justified = |text: &str| {
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
let mut doc = d.clone();
write_out(&mut doc, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
assert_eq!(t.plain_text(), text);
(0..t.paragraph_count()).map(|i| t.para_at(i).justify).collect::<Vec<_>>()
};
assert_eq!(justified("X\nA\nB\nC"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right]);
assert_eq!(justified("A\nBé\nC"), [Justify::Left, Justify::Center, Justify::Right]);
assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]);
assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]);
assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
// Two separate changes: B and C keep their styles.
assert_eq!(justified("X\nA\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
assert_eq!(justified("A\nX\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
// A changed paragraph takes the style of the one it replaces; the one added after it, that style.
assert_eq!(justified("A\nB2\nB3\nC"), [Justify::Left, Justify::Center, Justify::Center, Justify::Right]);
assert_eq!(justified("A2\nC"), [Justify::Left, Justify::Right]);
}
/// A paragraph that a change adds next to a numbered one takes its style without the number, and
/// the numbered paragraph keeps it.
#[test]
fn written_runs_give_an_added_paragraph_no_list_number() {
use vectorcraft_doc::text::ParaList;
use vectorcraft_doc::{CharStyle, ParaStyle, TextObject};
let (mut d, _, layer, _) = mixed();
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
let numbered = ParaStyle { list: Some(ParaList { start: Some(5), ..ParaList::default() }), ..ParaStyle::default() };
t.set_paragraph_styles(vec![ParaStyle::default(), numbered]);
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
let targets = vec![id];
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": "X\nA\nB\nY", "style": CharStyle::default()}]}}]});
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
let starts: Vec<_> = (0..t.paragraph_count()).map(|i| t.para_at(i).list.map(|l| l.start)).collect();
assert_eq!(starts, [None, None, Some(Some(5)), Some(None)]);
}
/// Past 262,144 pairs of old and new paragraphs to compare, the paragraphs are paired in order.
#[test]
fn written_runs_pair_paragraphs_in_order_past_the_compare_limit() {
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
let (mut d, _, layer, _) = mixed();
let paras: Vec<String> = (0..600).map(|i| format!("p{i}")).collect();
let mut t = TextObject::point(Point::new(0.0, 0.0), &paras.join("\n"), CharStyle::default());
let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() };
t.set_paragraph_styles((0..600).map(styled).collect());
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
let targets = vec![id];
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
// 600 old paragraphs times 602 new ones: none starts or ends both texts.
let text = format!("X\n{}\nY", paras.join("\n"));
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
assert_eq!(t.paragraph_count(), 602);
let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect();
let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect();
assert_eq!(got, want);
}
/// Every number in the character and paragraph styles a filter writes is checked against the range
/// the style commands keep it to, in a style of the filter's own and in one the type already has,
/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the
/// object and the field, and the document stays as it was. A set of the document's, given by
/// name, takes the document's characters.
#[test]
fn written_style_numbers_are_checked_even_in_a_style_the_type_has() {
use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject};
let (mut d, _, layer, _) = mixed();
d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() });
let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() };
let bad_chars: [(&str, CharStyle, &str); 5] = [
("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"),
("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"),
("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"),
("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"),
("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"),
];
let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() };
let bad_paras: [(&str, ParaStyle, &str); 4] = [
("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"),
("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"),
(
"hyphenation",
ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() },
"paragraphs[0].hyphenation.after_first",
),
("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"),
];
// `own`: the type already has the bad style, and the filter changes only its other run or
// paragraph; otherwise the bad style is the filter's own.
let run = |id: NodeId, own: bool, bad: &CharStyle| {
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
if own {
t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())];
}
let mut doc = d.clone();
let n = Node::new(id, NodeKind::Text(Box::new(t)));
let id = doc.insert(Some(layer), usize::MAX, n).unwrap();
(doc, id)
};
let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| {
let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
let mut entry = entry;
entry["id"] = json!(id.0);
let mut changed = doc.clone();
let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string();
assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}");
assert_eq!(&changed, doc, "{what}: nothing changed");
};
let fresh = d.clone().alloc_id();
for (what, bad, says) in &bad_chars {
let (doc, id) = run(fresh, false, bad);
let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]);
check(&doc, id, json!({"text": {"runs": runs}}), says, what);
let (doc, id) = run(fresh, true, bad);
let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]);
check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has"));
}
let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() };
for (what, bad, says) in &bad_paras {
let (doc, id) = run(fresh, false, &CharStyle::default());
check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what);
let mut doc = doc;
if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) {
t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]);
}
check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has"));
}
// A set the document has, by name, takes the document's characters.
let (mut doc, id) = run(fresh, false, &CharStyle::default());
let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() });
let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]});
write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap();
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、']));
}
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
#[test]
+526
View File
@@ -0,0 +1,526 @@
//! What a filter whose manifest lists `writes` may change about the type, images and symbol
//! instances it was given: each one's name and transform; type's runs, with their character
//! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows.
//! Every other field stays read-only, and every value is checked before anything changes.
use std::collections::HashSet;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR};
use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun};
use vectorcraft_geom::Affine;
use super::{
MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err,
read_only_changed,
};
use crate::{Error, InputKind, Result};
/// The longest font family name a filter may set, in characters.
const MAX_FAMILY: usize = 256;
/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object.
const MIN_DETERMINANT: f64 = 1e-12;
/// The most pairs of an old and a new paragraph, past those both texts start and end with, that a
/// change of the paragraph count compares by their text ([`moved_para_styles`]).
const MAX_MATCHED_PAIRS: usize = 1 << 18;
/// The fields of an object of `kind` a filter that lists the kind in `writes` may change.
fn writable(kind: InputKind) -> &'static [&'static str] {
match kind {
InputKind::Type => &["name", "transform", "text"],
InputKind::Image => &["name", "transform", "opacity"],
InputKind::SymbolInstance => &["name", "transform", "symbolId"],
}
}
/// The changes entry `o` of a filter's output makes to object `given` of `kind` (as the input gave
/// it), `None` when it changes nothing. Fields it leaves out keep their values; a field it gives
/// that isn't [`writable`] must be as given. Changed type text counts toward `text`, the bytes of
/// text written over the whole output. The changes are keyed `name`, `transform`, `opacity`,
/// `symbolId`, `runs` and `paragraphs`; their values are checked when they are applied ([`apply`]).
pub(super) fn changes(o: &Map<String, Value>, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result<Option<Map<String, Value>>> {
let mut keys: Vec<&String> = o.keys().filter(|k| *k != "id").collect();
keys.sort();
let mut out = Map::new();
for k in keys {
let v = &o[k];
let was = given.get(k);
if !writable(kind).contains(&k.as_str()) {
if let Some(field) = was.map_or_else(|| Some(k.clone()), |w| first_difference(v, w, k)) {
return Err(read_only_changed(at, &field));
}
continue;
}
match (k.as_str(), was) {
("text", Some(was)) => text_changes(k, v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?,
("name", None) if v.is_null() => {}
(_, Some(was)) if first_difference(v, was, "").is_none() => {}
_ => {
out.insert(k.clone(), v.clone());
}
}
}
Ok((!out.is_empty()).then_some(out))
}
/// The `runs` and `paragraphs` of type text `v`, the output's field `key`, that differ from `was`
/// (the text the input gave), into `out`; its other fields must be as given, and type given as
/// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed
/// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to
/// [`MAX_INPUT_TEXT_TOTAL`], and to [`MAX_INPUT_RUNS`] paragraphs. With changed runs, `paragraphs`
/// given as they were go into `out` too, to be checked against the new paragraphs.
fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map<String, Value>) -> Result<()> {
let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?;
let mut keys: Vec<&String> = t.keys().collect();
keys.sort();
for k in keys {
let field = format!("{key}.{k}");
let given = was.get(k);
let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some());
if !matches!(k.as_str(), "runs" | "paragraphs") {
if differs {
let shown = given.and_then(|g| first_difference(&t[k], g, &field)).unwrap_or_else(|| field.clone());
return Err(read_only_changed(at, &shown));
}
continue;
}
if !differs {
continue;
}
if truncated {
return Err(out_err(&format!("{at}.{field}"), "the text of type given as `truncated` can't be changed"));
}
let list = t[k].as_array().filter(|l| l.len() <= MAX_INPUT_RUNS);
let list = list.ok_or_else(|| out_err(&format!("{at}.{field}"), format!("must be a list of at most {MAX_INPUT_RUNS} entries")))?;
if k == "runs" {
if list.is_empty() {
return Err(out_err(&format!("{at}.{field}"), "type needs at least one run"));
}
let bytes = list.iter().fold(0usize, |n, r| n.saturating_add(r.get("text").and_then(Value::as_str).map_or(0, str::len)));
if bytes > MAX_INPUT_TEXT {
return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})")));
}
// Each paragraph gets a paragraph style; the text holds at most as many paragraphs as runs.
let breaks = |r: &Value| r.get("text").and_then(Value::as_str).map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
let paragraphs = list.iter().fold(1usize, |n, r| n.saturating_add(breaks(r)));
if paragraphs > MAX_INPUT_RUNS {
return Err(out_err(&format!("{at}.{field}"), format!("{paragraphs} paragraphs (limit {MAX_INPUT_RUNS})")));
}
*total = total.saturating_add(bytes);
if *total > MAX_INPUT_TEXT_TOTAL {
return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output")));
}
}
out.insert(k.clone(), t[k].clone());
}
// Paragraph styles given as they were still need one per paragraph of the new runs.
if out.contains_key("runs")
&& !out.contains_key("paragraphs")
&& let Some(p) = t.get("paragraphs")
{
out.insert("paragraphs".into(), p.clone());
}
Ok(())
}
/// Every attribute name `T` reads, including those its JSON leaves out at their defaults: the field
/// names serde's derive hands `deserialize_struct`.
fn attr_names<T: DeserializeOwned>() -> &'static [&'static str] {
use serde::de::{Error as _, Visitor, value::Error};
struct Names<'a>(&'a mut &'static [&'static str]);
impl<'de> serde::Deserializer<'de> for Names<'_> {
type Error = Error;
fn deserialize_any<V: Visitor<'de>>(self, _: V) -> std::result::Result<V::Value, Error> {
Err(Error::custom("not a struct"))
}
fn deserialize_struct<V: Visitor<'de>>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result<V::Value, Error> {
*self.0 = fields;
Err(Error::custom("field names only"))
}
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit
unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any
}
}
let mut fields: &'static [&'static str] = &[];
// Always an error: the probe only records the names.
let _ = T::deserialize(Names(&mut fields));
fields
}
/// `v`, the field `key` of the entry at `parent`, as a `T` whose attributes are all ones `T` reads:
/// a value that isn't an object is an error at `parent`, and an unknown key, as an ill-typed value,
/// an error at `parent.key`.
fn strict<T: DeserializeOwned>(v: &Value, parent: &str, key: &str) -> Result<T> {
let o = v.as_object().ok_or_else(|| out_err(parent, format!("`{key}` must be an object")))?;
let at = format!("{parent}.{key}");
let names = attr_names::<T>();
if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) {
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
return Err(out_err(&at, format!("unknown key '{k}'")));
}
serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e))
}
/// The field `key` of `v`, the style at `at`, holds only attributes `T` reads: an object, or each
/// object of a list. An unknown key is an error at `at.key` (or `at.key[i]`); other values are left
/// to the style's own checks.
fn known_keys<T: DeserializeOwned>(v: &Value, at: &str, key: &str) -> Result<()> {
let names = attr_names::<T>();
let check = |o: &Map<String, Value>, at: &str| match o.keys().find(|k| !names.contains(&k.as_str())) {
Some(k) => {
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
Err(out_err(at, format!("unknown key '{k}'")))
}
None => Ok(()),
};
match v.get(key) {
Some(Value::Object(o)) => check(o, &format!("{at}.{key}")),
Some(Value::Array(list)) => list.iter().enumerate().try_for_each(|(i, e)| match e {
Value::Object(o) => check(o, &format!("{at}.{key}[{i}]")),
_ => Ok(()),
}),
_ => Ok(()),
}
}
/// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't
/// flatten the object.
fn decode_transform(v: &Value, at: &str) -> Result<Affine> {
let c: Option<Vec<f64>> = v.as_array().and_then(|a| a.iter().map(Value::as_f64).collect());
let c: [f64; 6] = c.and_then(|c| c.try_into().ok()).ok_or_else(|| out_err(at, "must be a list of 6 numbers"))?;
if !c.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) {
return Err(out_err(at, format!("a number is out of range (limit ±{MAX_COORD})")));
}
let xf = Affine::new(c);
if xf.determinant().abs() < MIN_DETERMINANT {
return Err(out_err(at, "flattens the object to a line or a point"));
}
Ok(xf)
}
/// The transform object `n` is given with: type's and an instance's own, an image's (for a
/// distorted image, the placement nearest its corners at its middle).
fn given_transform(n: &Node) -> Option<Affine> {
match &n.kind {
NodeKind::Text(t) => Some(t.xf),
NodeKind::Image(im) => Some(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)),
NodeKind::SymbolInstance { xf, .. } => Some(*xf),
_ => None,
}
}
/// Applies `changes` ([`changes`]) to `n`, an input object of `doc`; `at` names it in errors. Each
/// value is checked first, and an error leaves `n` to be dropped.
pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map<String, Value>, at: &str) -> Result<()> {
if let Some(v) = changes.get("transform") {
let at = format!("{at}.transform");
let new = decode_transform(v, &at)?;
let old = given_transform(n).filter(|xf| xf.determinant().abs() >= MIN_DETERMINANT);
let old = old.ok_or_else(|| out_err(&at, "an object flattened to a line or a point can't be placed again"))?;
// Everything the object carries moves with it: a distorted image's corners, its gradients.
n.transform(new * old.inverse(), false);
let distorted = n.is_distorted_image();
match &mut n.kind {
NodeKind::Text(t) => t.xf = new,
NodeKind::SymbolInstance { xf, .. } => *xf = new,
NodeKind::Image(im) if !distorted => im.xf = new,
_ => {}
}
}
if let Some(v) = changes.get("opacity") {
let op = v.as_f64().filter(|o| (0.0..=1.0).contains(o));
n.opacity = op.ok_or_else(|| out_err(&format!("{at}.opacity"), "must be a number from 0 to 1"))? as f32;
}
if let Some(v) = changes.get("symbolId") {
let at = format!("{at}.symbolId");
let name = v.as_str().ok_or_else(|| out_err(&at, "must be the name of a symbol"))?;
if !doc.symbols.iter().any(|s| s.name == name) {
let shown = crate::permissions::display_text(name, crate::permissions::MAX_SHOWN_FIELD);
return Err(out_err(&at, format!("'{shown}' is not a symbol in this document")));
}
let other = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol != name);
if let NodeKind::SymbolInstance { symbol, .. } = &mut n.kind {
*symbol = name.to_string();
}
// An edited part's path names an object of the old symbol's art, as Replace Symbol finds.
if other && !n.extras().symbol_overrides.is_empty() {
n.extras_mut().symbol_overrides.clear();
}
}
if changes.contains_key("runs") || changes.contains_key("paragraphs") {
let story = doc.story_of(n.id).len();
let NodeKind::Text(t) = &mut n.kind else { return Err(read_only_changed(at, "text")) };
set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?;
}
if let Some(v) = changes.get("name") {
n.name = Some(decode_name(v, at)?).filter(|s| !s.trim().is_empty());
}
Ok(())
}
/// Gives type `t` the runs `runs` and paragraph styles `paragraphs` a filter returned (`threaded`:
/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an
/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they
/// were, in the same order, and the characters of threaded type or type with ruby stay as they
/// were. Every number of every run's style is in the range the character style commands keep it
/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font
/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph
/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays
/// the same, and otherwise the styles follow the paragraphs' text ([`moved_para_styles`]).
fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> {
if let Some(runs) = runs {
let at = format!("{at}.text.runs");
let list = runs.as_array().map(Vec::as_slice).unwrap_or_default();
// The type's own styles, as JSON text, to look each run's style up once.
let own: HashSet<String> = t.runs.iter().filter_map(|r| serde_json::to_string(&r.style).ok()).collect();
let mut new = Vec::with_capacity(list.len());
for (i, v) in list.iter().enumerate() {
let at = format!("{at}[{i}]");
let o = v.as_object().ok_or_else(|| out_err(&at, "a run must be {\"text\", \"style\", \"inline\"?}"))?;
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "text" | "style" | "inline")) {
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
return Err(out_err(&at, format!("unknown key '{k}'")));
}
let key = "text";
let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?;
let style_v = o.get("style").unwrap_or(&Value::Null);
let mut style: CharStyle = strict(style_v, &at, "style")?;
known_keys::<vectorcraft_doc::Dash>(style_v, &format!("{at}.style"), "stroke_dash")?;
let inline = match o.get("inline") {
None | Some(Value::Null) => None,
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?),
};
if inline.is_none() {
if text.contains(INLINE_CHAR) {
return Err(out_err(&at, "`text` holds the character of an inline graphic"));
}
// Every number goes to the layout, so it is checked even in a style the type has.
style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?;
for key in ["fill", "stroke"] {
if let Some(p) = style_v.get(key) {
check_paint_keys(p, &format!("{at}.style.{key}"))?;
}
}
if !serde_json::to_string(&style).is_ok_and(|s| own.contains(&s)) {
check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?;
}
}
new.push(TextRun { text: text.to_string(), style, inline });
}
// Inline graphics are compared as saved (their measured bounds aren't), and keep those.
let saved = |r: &&TextRun| serde_json::to_value(r).ok();
let old_inline: Vec<&TextRun> = t.runs.iter().filter(|r| r.inline.is_some()).collect();
let new_inline: Vec<&TextRun> = new.iter().filter(|r| r.inline.is_some()).collect();
if old_inline.len() != new_inline.len() || old_inline.iter().zip(&new_inline).any(|(a, b)| saved(a) != saved(b)) {
return Err(out_err(&at, "inline graphics can't be added, removed, reordered or changed"));
}
let mut kept = old_inline.into_iter().cloned().collect::<Vec<_>>().into_iter();
for r in new.iter_mut().filter(|r| r.inline.is_some()) {
if let Some(old) = kept.next() {
*r = old;
}
}
let plain: String = new.iter().map(|r| r.text.as_str()).collect();
let old = t.plain_text();
let mut moved = None;
if plain != old {
if threaded {
return Err(out_err(&at, "the characters of threaded type can't be changed"));
}
if !t.ruby.is_empty() {
return Err(out_err(&at, "the characters of type with ruby can't be changed"));
}
let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count();
if paragraphs.is_none() && breaks(&plain) != breaks(&old) {
// Paragraphs added or joined: the styles follow the paragraphs' text. With as many
// paragraphs as before, each keeps its style.
moved = Some(moved_para_styles(&t.paragraph_styles(), &old, &plain));
}
}
t.runs = new;
if let Some(styles) = moved {
t.set_paragraph_styles(styles);
}
}
match paragraphs {
Some(v) => {
let text = format!("{at}.text");
let list = v.as_array().map(Vec::as_slice).unwrap_or_default();
let count = t.paragraph_count();
if list.len() != count {
return Err(out_err(&format!("{text}.paragraphs"), format!("expected {count} paragraph styles, one per paragraph")));
}
let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &text, &format!("paragraphs[{i}]"))).collect::<Result<_>>()?;
t.set_paragraph_styles(styles);
}
None => t.normalize_paras(),
}
// The layout is measured again before the type is drawn.
t.cached_bounds = None;
t.cached_baselines.clear();
t.cached_ink = None;
Ok(())
}
/// The paragraph styles of text `new` that replaced `old`, whose paragraphs had `styles` (one per
/// paragraph). The paragraphs, split at `\n`, are matched as a longest common subsequence of their
/// texts after the paragraphs both start and end with are set aside; when the paragraphs left in
/// the old text times those left in the new pass [`MAX_MATCHED_PAIRS`], they are paired in order
/// instead. A
/// matched paragraph keeps its style. Between two matched paragraphs, the changed ones take the
/// styles of the old paragraphs there in order, and the last of those past their count; paragraphs
/// added where there were none take the style of the paragraph before them, or of the next one at
/// the start. A style copied to a paragraph that was not there loses its list number
/// ([`vectorcraft_doc::text::ParaList::start`]).
fn moved_para_styles(styles: &[ParaStyle], old: &str, new: &str) -> Vec<ParaStyle> {
let a: Vec<&str> = old.split('\n').collect();
let b: Vec<&str> = new.split('\n').collect();
let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
let (a_rest, b_rest) = (a.get(pre..).unwrap_or_default(), b.get(pre..).unwrap_or_default());
let suf = a_rest.iter().rev().zip(b_rest.iter().rev()).take_while(|(x, y)| x == y).count();
// `matched[j]`: the old paragraph that new paragraph `j` is, if any.
let mut matched: Vec<Option<usize>> = vec![None; b.len()];
for (j, m) in matched.iter_mut().enumerate().take(pre) {
*m = Some(j);
}
for k in 0..suf {
if let Some(m) = matched.get_mut(b.len() - 1 - k) {
*m = Some(a.len() - 1 - k);
}
}
let (am, bm) = (a_rest.get(..a_rest.len() - suf).unwrap_or_default(), b_rest.get(..b_rest.len() - suf).unwrap_or_default());
if !am.is_empty() && !bm.is_empty() && am.len().saturating_mul(bm.len()) <= MAX_MATCHED_PAIRS {
let mut ids = std::collections::HashMap::new();
let mut id = |s: &str| {
let next = ids.len();
*ids.entry(s.to_string()).or_insert(next)
};
let ai: Vec<usize> = am.iter().map(|s| id(s)).collect();
let bi: Vec<usize> = bm.iter().map(|s| id(s)).collect();
// `len[i * w + j]`: the length of the longest common subsequence of `ai[i..]` and `bi[j..]`.
let w = bi.len() + 1;
let mut len = vec![0u32; (ai.len() + 1) * w];
for i in (0..ai.len()).rev() {
for j in (0..bi.len()).rev() {
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
let v = if ai.get(i) == bi.get(j) { at(i + 1, j + 1) + 1 } else { at(i + 1, j).max(at(i, j + 1)) };
if let Some(c) = len.get_mut(i * w + j) {
*c = v;
}
}
}
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
let (mut i, mut j) = (0, 0);
while i < ai.len() && j < bi.len() {
if ai.get(i) == bi.get(j) {
if let Some(m) = matched.get_mut(pre + j) {
*m = Some(pre + i);
}
(i, j) = (i + 1, j + 1);
} else if at(i + 1, j) >= at(i, j + 1) {
i += 1;
} else {
j += 1;
}
}
}
let style = |i: usize, numbered: bool| {
let mut s = styles.get(i).or(styles.last()).cloned().unwrap_or_default();
if !numbered && let Some(l) = s.list.as_mut() {
l.start = None;
}
s
};
let mut out = Vec::with_capacity(b.len());
let (mut next_old, mut j) = (0, 0);
while j < b.len() {
if let Some(&Some(i)) = matched.get(j) {
out.push(style(i, true));
(next_old, j) = (i + 1, j + 1);
continue;
}
// New paragraphs `j..end` stand where old paragraphs `next_old..old_end` were.
let end = (j..b.len()).find(|&k| matched.get(k).is_some_and(Option::is_some)).unwrap_or(b.len());
let old_end = matched.get(end).copied().flatten().unwrap_or(a.len());
for g in 0..end - j {
out.push(if next_old < old_end {
style((next_old + g).min(old_end - 1), next_old + g < old_end)
} else {
style(next_old.checked_sub(1).unwrap_or(old_end), false)
});
}
j = end;
}
out
}
/// An attribute of the style at `at` out of its range, naming the attribute.
fn range_err(at: &str, e: &AttrRangeError) -> Error {
out_err(&format!("{at}.{}", e.key), &e.message)
}
/// Paragraph style `v` from a filter's output, the entry `key` of the text at `parent`: each
/// attribute one a paragraph reads, each number in the range the paragraph style commands keep it
/// to ([`ParaStyle::check_ranges`], the Justification options as given), and a custom Kinsoku set
/// one of `doc`'s, by name, whose characters it takes.
fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result<ParaStyle> {
let mut st: ParaStyle = strict(v, parent, key)?;
let at = format!("{parent}.{key}");
known_keys::<vectorcraft_doc::HyphenationOptions>(v, &at, "hyphenation")?;
known_keys::<JustificationOptions>(v, &at, "justification")?;
known_keys::<vectorcraft_doc::TabStop>(v, &at, "tabs")?;
known_keys::<vectorcraft_doc::text::ParaList>(v, &at, "list")?;
let justification = match v.get("justification") {
None | Some(Value::Null) => None,
Some(j) => Some(serde_json::from_value::<JustificationOptions>(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?),
};
st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(&at, &e))?;
if let Some(set) = &st.kinsoku_set {
let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| {
let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD);
out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'"))
})?;
st.kinsoku_set = Some(std::sync::Arc::new(found.clone()));
}
Ok(st)
}
/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before):
/// its font family is 1 to [`MAX_FAMILY`] printable characters, counted as given, and its fill and
/// stroke are admitted as an object's paints are. Its numbers and its paints' keys are checked for
/// every run ([`set_text`]).
fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> {
let family = s.font_family.trim();
if family.is_empty() || s.font_family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) {
return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters")));
}
let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| {
let at = format!("{at}.{key}");
let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?;
admit_paint(doc, decode_paint(&v, &at)?, was, &at)
};
s.fill = paint(&s.fill, was.map(|w| &w.fill), "fill")?;
s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?;
Ok(())
}
/// Checks that paint `v` of a style, at `at`, has no key besides `type` and those its `type`
/// reads; a key of another paint, or an unknown one, is an error naming it.
fn check_paint_keys(v: &Value, at: &str) -> Result<()> {
let Some(o) = v.as_object() else { return Ok(()) };
let known: &[&str] = match o.get("type").and_then(Value::as_str) {
Some("solid") => &["color", "swatch", "tint"],
Some("gradient") => attr_names::<vectorcraft_color::GradientPaint>(),
Some("pattern") => &["pattern", "xf"],
_ => &[],
};
if let Some(k) = o.keys().find(|k| *k != "type" && !known.contains(&k.as_str())) {
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
return Err(out_err(at, format!("unknown key '{k}'")));
}
Ok(())
}
+5 -1
View File
@@ -15,7 +15,8 @@ use crate::{Error, Kind, Result};
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]).
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]) and a manifest's
/// `context` ([`CONTEXT_API`]).
pub const API_LEVEL: u32 = 3;
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
@@ -25,6 +26,9 @@ pub const PROGRESS_API: u32 = 2;
/// The API level that adds a filter's `inputs` ([`crate::InputKind`]).
pub const INPUTS_API: u32 = 2;
/// The API level that adds a filter's `writes`: the kinds among its `inputs` it may change.
pub const WRITES_API: u32 = 3;
/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key
/// is ignored.
pub const MENU_API: u32 = 2;
+1 -3
View File
@@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool {
/// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its
/// symbol is being edited from?
pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool {
let view_item = a.is_ruler_guide()
|| (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. })
|| (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. });
let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides);
!a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id)
}
+12 -9
View File
@@ -338,18 +338,19 @@ impl Operand {
/// object: `[new] File|Folder(…)`, `new File|Folder`, `File.openDialog(…)`, `File.saveDialog(…)`,
/// `Folder.selectDialog(…)`, `Folder.<place>` ([`catalog::FOLDER_PLACES`]) or a variable holding
/// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a
/// File or Folder object.
/// File or Folder object, `Some(true)` when it counts as a Folder object whatever the path names.
///
/// Only `new Folder(…)`, `new Folder` and `Folder.<place>` are Folder objects whatever the path
/// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)`
/// gives a File or Folder object for what the user picks, `Folder.current` is the one place a
/// script can assign, and a variable another variable was assigned to may hold a File object.
fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand {
/// Only `new Folder(…)`, `new Folder`, `Folder.<place>` and such a variable are Folder objects
/// whatever the path names. `Folder(…)` gives a File object when the path names a file,
/// `Folder.selectDialog(…)` gives a File or Folder object for what the user picks, and
/// `Folder.current` is the one place a script can assign. A variable another variable is assigned
/// may hold a File object, so a grouped value passes `Some(false)` for any variable.
fn file_step(self, t: &Sig, file: bool, alias: Option<bool>) -> Operand {
match self {
Operand::Start if t.word("new") => Operand::New,
Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER },
Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER },
Operand::Start if alias => Operand::Done(Held::File { folder: false }),
Operand::Start if alias.is_some() => Operand::Done(Held::File { folder: alias == Some(true) }),
Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder },
Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false },
Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder },
@@ -1378,7 +1379,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) {
let after = self.depth();
let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text);
let alias = self.alias(t);
let alias = self.alias(t).then_some(false);
let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return };
if after < g.level {
// The `)` of the innermost pair: the operand, when complete, is the pair's value and the
@@ -1436,7 +1437,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn paren_step(&mut self, t: &Sig<'s>, before: usize) {
let after = self.depth();
let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text);
let alias = self.alias(t);
// A variable in grouping parentheses is the object it holds now, as it is outside them
// ([`Analyzer::held_file`]).
let alias = self.alias(t).then(|| self.folder(t.text));
if let Some(p) = self.parens.last_mut() {
if before == p.level {
p.operand = match std::mem::replace(&mut p.operand, Operand::Other) {
+19
View File
@@ -619,6 +619,25 @@ fn file_only_calls_on_a_folder_do_nothing() {
assert_eq!(lines("file.dialog"), [8]);
}
/// A variable holding a Folder object is the same object in grouping parentheses, so `(d).write(s)`
/// and `(d).length = 0` do nothing, as `d.write(s)` and `d.length = 0` do. A variable that may hold
/// a File object still counts in them.
#[test]
fn a_folder_in_parentheses_is_still_a_folder() {
let r = report(concat!(
"var d = new Folder(p);\n",
"(d).write(s); ((d)).copy(q); (d).open('r'); (d).length = 0;\n",
"var f = new File(p);\n",
"(f).write(s);\n",
"var g = Folder(p); (g).open('r');\n",
));
let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default();
let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect();
assert_eq!(outside, [("filesWritten", &[4][..])]);
assert_eq!(lines("file.write"), [4]);
assert_eq!(lines("file.read"), [5]);
}
/// A File object assigned to a function's own variable, its parameter or a `catch` block's
/// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter
/// starts without what the outer variable of the same name was assigned.
+263 -15
View File
@@ -15,19 +15,23 @@
//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another
//! document, or a change to the first segment that leaves no undo step (a live preview, or one that
//! was canceled) forgets the first segment. The circles are looked for again whenever either
//! segment's shape differs from the one they were found on.
//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at
//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the
//! segments the circle touches get an anchor point at each touch, which splits them without changing
//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none.
//!
//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`;
//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the
//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the
//! two points it touches; `color` is the color of the circle, the cross, those lines and the note
//! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment
//! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger,
//! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked
//! within the selection tolerance, as a click on a path picks it, and that is also the least reach
//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default the
//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on.
//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default
//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and
//! `snapWithoutGuides` is on.
use kurbo::{CubicBez, Shape};
use kurbo::{CubicBez, ParamCurveNearest, Shape};
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{BezPath, ParamCurve, Point};
@@ -52,6 +56,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here";
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
const RED: [u8; 3] = [0xe0, 0x3c, 0x3c];
const GREY: [u8; 3] = [0x80, 0x80, 0x80];
/// The label of the `addPoints` option in the tool's options.
pub const ADD_POINTS: &str = "Add Points to Existing Paths";
/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in
/// effect, and its size.
const DOT_PX: f64 = 10.0;
const DOT_SIZE: f32 = 4.0;
/// The colors the `color` option takes, by option value, with the color the circle, its center
/// cross, its radii and the note are drawn in. Red is the first.
pub const COLORS: &[(&str, [u8; 3])] = &[
@@ -67,7 +77,7 @@ pub const SNAP_PX: f64 = 3.0;
/// The snapping tolerance the `snapTolerance` option takes (screen pixels).
pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0);
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["center", "radii", "snapWithoutGuides"];
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"];
/// A segment under the pointer: where on it, and the segment itself.
#[derive(Clone, Debug, PartialEq)]
@@ -90,6 +100,9 @@ struct Press {
at: Point,
/// Whether Shift was held when the click's circle was last looked for.
shift: bool,
/// The tool's `radius` when the button went down: Shift uses it for the whole press, whatever
/// `tool.setOption` writes meanwhile.
shift_radius: f64,
/// How far the pointer was from the press last time, and the radius the drag set (none until
/// the pointer moves far enough).
reach: f64,
@@ -98,6 +111,11 @@ struct Press {
pub struct TangentCircleTool {
radius: f64,
/// Whether drawing a circle adds anchor points where it touches the segments.
add_points: bool,
/// The keys held at the last pointer event, and whether the pointer is over the canvas.
mods: Mods,
over: bool,
/// Whether the preview shows the center cross and the radii.
center: bool,
radii: bool,
@@ -127,6 +145,9 @@ impl Default for TangentCircleTool {
fn default() -> Self {
Self {
radius: RADIUS,
add_points: false,
mods: Mods::default(),
over: false,
center: true,
radii: true,
color: 0,
@@ -186,6 +207,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool {
/// The segments a circle may touch when `second` is picked: it and the segments on either side of
/// it, without `first`. None when `second` is the first segment again.
fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect()
}
/// [`second_set`] with each segment's index on the second pick's subpath.
fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> {
if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) {
return vec![];
}
@@ -202,7 +228,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
indices.sort_unstable();
indices.dedup();
let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k;
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect()
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect()
}
/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either
/// end, where the segment already has an anchor point.
fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option<f64> {
if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol {
return None;
}
let t = curve.nearest(p, 1e-12).t;
(t > 0.0 && t < 1.0).then_some(t)
}
/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment
/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath
/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the
/// anchor added before it does not move it along.
fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec<Value> {
let mut at: Vec<(NodeId, usize, usize, f64)> = vec![];
if let Some(t) = split_at(&first.curve, c.first, tol) {
at.push((first.id, first.subpath, first.segment, t));
}
let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq));
if let Some((k, curve)) = nearest
&& let Some(t) = split_at(curve, c.second, tol)
{
at.push((pick.id, pick.subpath, *k, t));
}
at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2)));
at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect()
}
/// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot
@@ -239,6 +294,14 @@ fn round_step(least: f64) -> f64 {
/// distance from the origin, or too large, in floating point), or when the circle would reach past
/// the canvas ([`crate::circle::circle_of`]), which the command refuses.
fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p))
}
/// The command [`draw`] runs.
const CIRCLE: &str = "shape.circleThroughPoints";
/// The params of the [`CIRCLE`] command that [`draw`] runs.
fn circle_params(c: &SegmentCircle, tol: f64) -> Option<Value> {
let (at, r) = (c.circle.center, c.circle.radius);
let points: Vec<Point> = [90.0f64, 210.0, 330.0]
.iter()
@@ -252,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
return None;
}
let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect();
Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points })))
Some(json!({ "points": points }))
}
fn segment_path(c: &CubicBez) -> BezPath {
@@ -338,8 +401,8 @@ impl TangentCircleTool {
// A change without an undo step since the press: a changed first segment is forgotten (the
// press then draws nothing), and the circle follows the segments it may touch as they are now.
self.forget_if_changed(cx);
let radius = self.radius;
let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return };
let radius = press.shift_radius;
// A pressed segment that is gone leaves nothing to touch.
let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] };
let moved = second != press.second;
@@ -388,6 +451,8 @@ impl Tool for TangentCircleTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
self.pointer = ev.pos;
self.mods = ev.mods;
self.over = true;
match ev.kind {
PointerKind::Move => {
self.hover = pick_at(cx, ev.pos, self.reach(cx));
@@ -410,7 +475,7 @@ impl Tool for TangentCircleTool {
self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX));
self.looked = true;
self.hover = None;
self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None });
self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, shift_radius: self.radius, reach: 0.0, radius: None });
vec![]
}
PointerKind::Drag => {
@@ -421,15 +486,34 @@ impl Tool for TangentCircleTool {
// The release's own position and keys set the radius of a drag.
self.drag_to(cx, ev);
self.picking = false;
if self.press.take().is_none() {
return vec![];
}
let Some(press) = self.press.take() else { return vec![] };
// No circle, or one the three points cannot draw: the first segment stays picked,
// for another try. It also stays when the command fails: only a drawn circle tells
// the tool (`notify`) to forget it.
let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] };
let Some(c) = self.found.take() else { return vec![] };
let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] };
self.looked = false;
vec![action, Action::Notify(DRAWN.into())]
// Alt at the release turns `addPoints` the other way.
let steps = match &self.first {
Some(first) if self.add_points != ev.mods.alt => {
let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] };
anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX))
}
_ => vec![],
};
if steps.is_empty() {
return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())];
}
let mut commands = steps;
// A path that was not selected becomes the selection when it gets an anchor; the
// selection is put back before the circle, which Draw Behind places behind it.
if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) {
let ids: Vec<u64> = cx.selection.objects.iter().map(|id| id.0).collect();
commands.push(json!({ "command": "select.set", "params": { "ids": ids } }));
}
commands.push(json!({ "command": CIRCLE, "params": params }));
// One undo step for the anchors and the circle, and none of them when a step fails.
vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())]
}
// The canvas sends a double-click after the second click's `Up`, which drew the circle.
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
@@ -480,6 +564,7 @@ impl Tool for TangentCircleTool {
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
self.over = false;
if self.press.is_none() {
self.found = None;
self.looked = false;
@@ -522,6 +607,11 @@ impl Tool for TangentCircleTool {
// A label, which the canvas shows in the interface language.
out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color });
}
// `addPoints` in effect, with Alt as it is now.
if (self.over || self.press.is_some()) && self.add_points != self.mods.alt {
let off = cx.tol(DOT_PX);
out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE });
}
out
}
@@ -532,6 +622,7 @@ impl Tool for TangentCircleTool {
fn options(&self) -> Value {
json!({
"radius": self.radius,
"addPoints": self.add_points,
"center": self.center,
"radii": self.radii,
"color": COLORS.get(self.color).map_or("red", |(name, _)| *name),
@@ -547,6 +638,7 @@ impl Tool for TangentCircleTool {
}
match key {
"radius" => self.radius = v.as_f64().unwrap_or(self.radius),
"addPoints" => self.add_points = v.as_bool().unwrap_or(self.add_points),
"center" => self.center = v.as_bool().unwrap_or(self.center),
"radii" => self.radii = v.as_bool().unwrap_or(self.radii),
"color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color),
@@ -707,6 +799,24 @@ mod tests {
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}");
}
#[test]
fn a_press_keeps_the_radius_it_started_with() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
t.set_option("radius", &json!(20));
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0));
// A radius written during the press does not reach the circle, however Shift changes.
t.set_option("radius", &json!(5));
t.pointer(&cx, &ev(PointerKind::Drag, 200.0, 139.0));
t.pointer(&cx, &shifted(PointerKind::Drag, 200.0, 139.0));
let released = up(&mut t, &cx, &shifted(PointerKind::Up, 200.0, 139.0));
assert!(close(drawn(&released), (180.0, 100.0, 40.0, 40.0)), "{released:?}");
}
#[test]
fn the_preview_options_set_its_cross_radii_and_color() {
let d = doc();
@@ -1038,6 +1148,144 @@ mod tests {
assert!(matches!(segments[..], [n] if n < 100), "{segments:?}");
}
/// The steps of the `command.batch` an action list runs: (command, params) each.
fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> {
let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") };
assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN));
p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect()
}
/// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment.
fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) {
let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap());
let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize];
(id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap()))
}
fn alt(mut e: PointerEvent) -> PointerEvent {
e.mods.alt = true;
e
}
#[test]
fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y), cx.pick_tol()).map(|p| p.id.0).unwrap();
let (top, below) = (line_at(100.0), line_at(140.0));
let mut t = TangentCircleTool::default();
t.set_option("addPoints", &json!(true));
assert_eq!(t.options()["addPoints"], json!(true));
// The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter
// along each line, then the circle, in one batch.
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
assert_eq!(steps.len(), 4, "{steps:?}");
assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}");
let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect();
anchors.sort_by_key(|a| a.0);
let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))];
want.sort_by_key(|a| a.0);
assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}");
// The lines were not selected, so the selection (none) is put back before the circle.
assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}");
let (cmd, params) = &steps[3];
let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]);
assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}");
assert!(t.first.is_none(), "ready for the next circle");
// With both lines selected, the anchors leave the selection as it is: no step puts it back.
let mut both = Selection::default();
both.add(NodeId(top));
both.add(NodeId(below));
let selected = self::cx(&d, &both, &p);
t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0));
let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0)));
assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}");
// Alt at the release turns it off for that circle, and with the option off turns it on.
for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] {
t.set_option("addPoints", &json!(on));
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0)));
let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) };
let released = up(&mut t, &cx, &release);
if adds {
assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}");
} else {
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}");
}
}
}
#[test]
fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
t.set_option("addPoints", &json!(true));
t.set_option("radius", &json!(10));
// The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310)
// on its second: the second segment's anchor comes first, so the first one's index holds.
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0));
t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0));
let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)));
assert_eq!(steps.len(), 4, "{steps:?}");
let l = pick_at(&cx, Point::new(300.0, 350.0), cx.pick_tol()).map(|p| p.id.0);
let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect();
let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))];
assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}");
assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE));
// A circle touching both lines at their right ends: no anchor is added on top of an anchor,
// so only the circle is drawn, as without the option.
t.set_option("radius", &json!(36));
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0));
let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0));
assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}");
}
#[test]
fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
assert_eq!(t.options()["addPoints"], json!(false), "off to start");
let dot =
|t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE));
t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0));
assert!(!dot(&t));
// Alt turns it on while held, and back off with the option on.
t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0)));
assert!(dot(&t));
t.set_option("addPoints", &json!(true));
assert!(!dot(&t));
t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0));
assert!(dot(&t));
let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else {
panic!("no dot")
};
assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}");
// The pointer off the canvas: no dot left behind.
t.hover_ended(&cx);
assert!(!dot(&t));
for bad in [json!(1), json!("true"), Value::Null] {
assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}");
t.set_option("addPoints", &bad);
assert_eq!(t.options()["addPoints"], json!(true), "{bad}");
}
assert_eq!(t.check_option("addPoints", &json!(false)), Ok(()));
}
#[test]
fn a_circle_that_would_reach_past_the_canvas_is_not_offered() {
// Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives
+43 -6
View File
@@ -2,6 +2,7 @@
//! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The
//! paths around the area stay as they are, and nothing needs to be selected.
use vectorcraft_geom::kurbo::ParamCurveDeriv;
use vectorcraft_geom::path::segment_bounds;
use vectorcraft_geom::{ParamCurve, PathSeg};
@@ -171,13 +172,39 @@ fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks
Some(shape)
}
/// How far (pt) the middle of a piece of an outline may lie from a mask's outline and still count
/// as on the mask's edge, which [`clip_to`] keeps. It covers rounding only, so a piece just outside
/// the mask is still left out.
const ON_MASK: f64 = 1e-6;
/// How far (pt) to each side of a piece [`shows_through`] looks for the mask's filled area: past
/// [`ON_MASK`], and within a filled strip of the mask as narrow as this.
const MASK_SIDE: f64 = 1e-4;
/// Does the piece of an outline whose middle is `p`, running in direction `dir` there, show
/// through `mask` filled with `rule`? A piece off the mask's outline shows when the filled area
/// holds `p`. A piece on the outline ([`ON_MASK`]) shows when the filled area lies on one side of
/// it ([`MASK_SIDE`]), so every side of a square clipped by the same square shows, and an outline
/// of the mask that bounds no filled area (two copies of one outline under even-odd) hides it.
fn shows_through(mask: &PathData, rule: FillRule, p: Point, dir: vectorcraft_geom::Vec2) -> bool {
if !mask.nearest(p).is_some_and(|(.., d)| d <= ON_MASK) {
return path_contains(mask, rule, p);
}
let len = dir.hypot();
if !(len > 0.0 && len.is_finite()) {
return false;
}
let side = dir.turn_90() * (MASK_SIDE / len);
path_contains(mask, rule, p + side) || path_contains(mask, rule, p - side)
}
/// `shape` cut to `mask` (filled with `rule`). With `filled` (the path's fill draws), its closed
/// subpaths are cut to their overlap with the mask, whose edge then bounds the fill. Its other
/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask,
/// so a hidden part of an outline does not close an area. A subpath with more segments or
/// crossings than [`po::addons::pathtools::crossings_on`] takes is left out. None when nothing of
/// it is inside.
fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option<po::Shape> {
/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask or
/// on its edge ([`shows_through`]), so a hidden part of an outline does not close an area. A
/// subpath with more segments or crossings than [`po::addons::pathtools::crossings_on`] takes is
/// left out. None when nothing of it is inside.
pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option<po::Shape> {
let (b, mb) = (shape.path.bounds()?, mask.bounds()?);
if !meet(&b, &mb) {
return None;
@@ -195,7 +222,17 @@ fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> O
let (cut, at) = po::addons::pathtools::insert_at(sp, &places);
subs.extend(cut.cut_at(&at).into_iter().filter(|piece| {
let n = piece.segment_count();
n > 0 && path_contains(mask, rule, piece.segment(n / 2).eval(0.5))
n > 0 && {
let seg = piece.segment(n / 2);
// Where the tangent vanishes (a cusp at the middle), the curve runs along its second
// derivative there, and a straight segment with that degenerate form along its chord.
let d1 = seg.deriv();
let dir = [d1.eval(0.5).to_vec2(), d1.deriv().eval(0.5).to_vec2(), seg.p3 - seg.p0]
.into_iter()
.find(|v| v.hypot2() > 0.0)
.unwrap_or_default();
shows_through(mask, rule, seg.eval(0.5), dir)
}
}));
}
if subs.is_empty() {
+26
View File
@@ -3796,6 +3796,32 @@ fn fill_area_press_does_not_search_a_hover_position_it_passed() {
assert_eq!(super::fill_area::hover_searches_started() - started, 1, "only the search that was running");
}
/// An outline without a fill, cut to a clipping mask, keeps the pieces on the mask's edge: a square
/// clipped by the same square keeps all four sides. A square just outside the mask, and a square on
/// an outline of the mask that bounds no filled area (two copies of the square under even-odd),
/// keep nothing.
#[test]
fn fill_area_clip_keeps_outline_pieces_on_the_mask_edge() {
let unit = Rect::new(0.0, 0.0, 100.0, 100.0);
let clip =
|shape: PathData, mask: &PathData, rule: FillRule| super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule);
let kept = clip(shapes::rectangle(unit), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge");
assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>(), 4, "{:?}", kept.path);
let outside = shapes::rectangle(Rect::new(-0.005, -0.005, 100.005, 100.005));
assert!(clip(outside, &shapes::rectangle(unit), FillRule::NonZero).is_none());
let mut twice = shapes::rectangle(unit);
let mut back = shapes::rectangle(unit).subpaths;
back[0].anchors.reverse();
twice.subpaths.extend(back);
assert!(clip(shapes::rectangle(unit), &twice, FillRule::EvenOdd).is_none());
// A top side drawn as a cubic whose tangent vanishes at its middle shows as well.
let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner };
let (o, x, xy, y) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0));
let cusp = SubPath::new(vec![a(o, o, x), a(x, o, x), a(xy, xy, xy), a(y, y, y)], true);
let kept = clip(PathData::single(cusp), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge");
assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>(), 4, "{:?}", kept.path);
}
#[test]
fn create_builds_the_three_tools() {
for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] {
+7 -4
View File
@@ -224,6 +224,12 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered
if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p }
}
/// Whether a circle preview of radius `r` is drawn dashed. The canvas draws a dashed outline dash by
/// dash along its whole length, so a circle longer than [`DASHED_PX`] on screen is drawn solid.
pub(crate) fn preview_dashed(cx: &ToolContext, r: f64) -> bool {
std::f64::consts::TAU * r <= cx.tol(DASHED_PX)
}
/// Are the points two or more different points through which no circle is drawn: three on one
/// line, or a circle that would reach past the canvas?
fn too_large(points: &[Point], centered: bool, standard_anchors: bool) -> bool {
@@ -573,10 +579,7 @@ impl Tool for CircleTool {
let on_outline = if self.centered { points.get(1..).unwrap_or(&[]) } else { &points[..] };
shapes::circle_with_anchors_at(c, r, on_outline).to_bezpath()
};
// The canvas draws a dashed outline dash by dash along its whole length: a circle longer
// than DASHED_PX on screen is drawn solid instead.
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
o.push(Overlay::Path { path, color, width: 1.0, dashed });
o.push(Overlay::Path { path, color, width: 1.0, dashed: preview_dashed(cx, r) });
let opts = self.options;
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
if opts.radii {
+5
View File
@@ -1882,6 +1882,11 @@ impl Tool for GestureTool {
fn wants_samples(&self) -> bool {
matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser")
}
/// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel
/// with a Variation above 0.
fn reads_wheel(&self, _cx: &ToolContext) -> bool {
self.tip_modes().contains(&Variation::StylusWheel)
}
/// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again
/// after a zoom change, reach the whole drag over several frames.
fn overlays_pending(&self) -> bool {
+23
View File
@@ -4129,3 +4129,26 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() {
assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil"));
assert_eq!(last[1], Action::Commit);
}
#[test]
fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
for id in ["pencil", "paintbrush", "blobBrush", "eraser"] {
assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults");
}
for value in ["angle", "roundness", "size"] {
let mut t = GestureTool::new("eraser");
t.set_option(&format!("{value}Mode"), &json!("stylusWheel"));
assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation");
t.set_option(&format!("{value}Variation"), &json!(4));
assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel");
t.set_option(&format!("{value}Mode"), &json!("pressure"));
assert!(!t.reads_wheel(&cx), "{value} on Pressure");
}
let mut t = GestureTool::new("blobBrush");
t.set_option("sizeMode", &json!("stylusWheel"));
t.set_option("sizeVariation", &json!(4));
assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel");
}
+6
View File
@@ -319,6 +319,12 @@ pub trait Tool: Send {
fn wants_samples(&self) -> bool {
false
}
/// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip
/// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read
/// the wheel opens it only while this is so.
fn reads_wheel(&self, _cx: &ToolContext) -> bool {
false
}
/// Is the tool waiting for work it runs on another thread (the planar map of a large selection
/// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It
/// highlights nothing under the pointer until a map is done. While this holds, the desktop app
+1 -1
View File
@@ -108,7 +108,7 @@ const ROWS: &[Row] = &[
(&[crate::addons::extend_path::ID], None, &["mode"]),
(&[crate::addons::corner_tool::ID], None, &["radius", "kind"]),
(&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]),
(&[crate::addons::tangent_circle::ID], None, &["radius", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
(&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
(&[crate::addons::smart_pen::ID], None, &["next"]),
// The kind first: a new kind resets the values after it.
(&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]),
+2 -2
View File
@@ -999,7 +999,7 @@ impl Tool for ShapeTool {
let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() };
o.extend(self.guides.iter().cloned());
// The points Shift-clicks placed, and after two of them the circle through them and the
// pointer, dashed.
// pointer, dashed (solid when it is too long on screen, as the Circle tool draws it).
for p in &self.through {
o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 });
}
@@ -1007,7 +1007,7 @@ impl Tool for ShapeTool {
&& let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h)
{
let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath();
o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true });
o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: crate::circle::preview_dashed(cx, r) });
}
if let Some((p, text)) = &self.measure {
o.push(Overlay::Measure { p: *p, text: text.clone() });
+31
View File
@@ -667,6 +667,37 @@ fn the_circle_preview_passes_through_the_snapped_pointer() {
assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}");
}
/// A circle through the Shift-clicked points more than 50,000 screen points around is previewed
/// solid, as the Circle tool previews it: points nearly on one line give a radius of about
/// 1,250,000 pt.
#[test]
fn a_huge_circle_through_shift_clicked_points_is_previewed_solid() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let shift = Mods { shift: true, ..Default::default() };
let mut t = ShapeTool::new("ellipse");
for (x, y) in [(0.0, 0.0), (1000.0, 0.0)] {
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift));
}
let paths = |t: &ShapeTool| {
t.overlays(&cx)
.into_iter()
.filter_map(|o| match o {
Overlay::Path { dashed, .. } => Some(dashed),
_ => None,
})
.collect::<Vec<_>>()
};
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 0.1));
assert_eq!(paths(&t), vec![false]);
// At 100% a circle 100 pt across is dashed.
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 300.0));
assert_eq!(paths(&t), vec![true]);
}
/// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click
/// starts a new circle.
#[test]
+62
View File
@@ -438,6 +438,20 @@ impl Tool for BrushPaintTool {
fn wants_samples(&self) -> bool {
self.inner.wants_samples()
}
/// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus
/// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values
/// differ, or an Art brush whose width is on it with two different widths.
fn reads_wheel(&self, cx: &ToolContext) -> bool {
use vectorcraft_brush::{BrushKind, Variation};
let wheel = |mode: Variation| mode == Variation::StylusWheel;
let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false };
match brush.kind {
BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0),
BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b),
BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1,
BrushKind::Pattern(_) | BrushKind::Bristle(_) => false,
}
}
fn busy(&self) -> bool {
self.inner.busy()
}
@@ -758,4 +772,52 @@ mod tests {
let a = drag(&d, &mut BrushPaintTool::default());
assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}");
}
#[test]
fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() {
use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation};
let wheel = Variation::StylusWheel;
let calligraphic =
|modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() });
let scatter = |size| {
BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() })
};
let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() });
let library = [
Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) },
Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) },
Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) },
Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) },
Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) },
Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) },
Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) },
Brush { name: "Flat".into(), kind: art(None, 200.0) },
];
let (mut d, _) = doc_with_rect();
d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap());
let (s, p) = (Selection::default(), paint());
let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p));
let mut t = BrushPaintTool::default();
assert!(!reads(&d, &t), "no brush");
let brushes = [
("Plain", false),
("Nib", true),
("Still nib", false),
("Dots", true),
("Even dots", false),
("Taper", true),
("Even taper", false),
("Flat", false),
("Deleted", false),
];
for (name, varies) in brushes {
d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name));
assert_eq!(reads(&d, &t), varies, "the current brush {name}");
}
t.set_option("brush", &json!("Plain"));
assert!(!reads(&d, &t), "the tool's own brush comes first");
t.set_option("brush", &json!("Nib"));
d.unknown.remove(vectorcraft_brush::CURRENT_KEY);
assert!(reads(&d, &t), "and reads the wheel");
}
}
+95 -7
View File
@@ -86,6 +86,9 @@ struct Drag {
/// when the Alt state at the release changes what it transforms.
pointer: Point,
shift: bool,
/// The pointer's own movement since the press, before snapping: a snapped press can turn a
/// level drag diagonal, so Scale's Shift-drag uses this to pick an axis (#6324).
moved: Vec2,
last: Affine,
/// The document revision at the press: a press whose document or selection changes before it
/// becomes a drag is dropped, so its reference point is never applied to other objects.
@@ -100,6 +103,16 @@ impl Drag {
}
}
/// The pointer drag [`TransformTool::solve`] turns into a transform.
struct SolveDrag {
start: Point,
p: Point,
/// The pointer's own movement since the press, before snapping (#6324).
moved: Vec2,
shift: bool,
bounds: Rect,
}
/// The first point of a Reflect axis set by a click, waiting for the second point, with the
/// selection and the document revision it was set for.
#[derive(Clone, Debug)]
@@ -222,7 +235,7 @@ impl TransformTool {
/// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the
/// line the pointer draws on the page.
pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) {
let (m, a, b) = self.solve(angle, o, start, p, shift, bounds);
let (m, a, b) = self.solve(angle, o, SolveDrag { start, p, moved: p - start, shift, bounds });
(m, self.label(a, b))
}
@@ -253,7 +266,8 @@ impl TransformTool {
/// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height
/// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as
/// `object.shear` takes it (Shear).
fn solve(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, f64, f64) {
fn solve(&self, angle: f64, o: Point, d: SolveDrag) -> (Affine, f64, f64) {
let SolveDrag { start, p, moved, shift, bounds } = d;
let frame = OrientedBox { angle, rect: Rect::ZERO };
let local = |v: Vec2| frame.to_doc().inverse() * v.to_point();
match self.kind {
@@ -276,7 +290,18 @@ impl TransformTool {
let d1 = local(p - o).to_vec2();
let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 };
let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y));
if shift {
// Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal
// one uniformly (#6324). The pointer's own movement decides, in the box's axes; a
// snapped press can otherwise turn a level drag diagonal. A drag that starts level
// with the reference point on that axis has nothing to scale it by, so it stays uniform.
let moved_local = local(moved).to_vec2();
let axis_angle = moved_local.y.abs().atan2(moved_local.x.abs()).to_degrees();
let along = moved_local.hypot() > 1e-9;
if shift && along && axis_angle <= 22.5 && d0.x.abs() > 1e-6 {
sy = 1.0;
} else if shift && along && axis_angle >= 67.5 && d0.y.abs() > 1e-6 {
sx = 1.0;
} else if shift {
let l2 = d0.hypot2();
let k = if l2 > 1e-12 { d1.dot(d0) / l2 } else { 1.0 };
sx = k;
@@ -380,6 +405,7 @@ impl Tool for TransformTool {
anchors,
pointer: p,
shift: false,
moved: Vec2::ZERO,
last: Affine::IDENTITY,
revision: cx.revision,
});
@@ -406,10 +432,15 @@ impl Tool for TransformTool {
Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) });
out.push(Action::Begin(self.kind.label().into()));
}
let moved = p - d.start;
let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p));
self.hover = guides;
let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds);
(d.last, d.pointer, d.shift) = (m, p, ev.mods.shift);
let (m, a, b) = self.solve(
d.angle_for(ev.mods.alt, ev.backquote),
d.origin,
SolveDrag { start: d.pick, p, moved, shift: ev.mods.shift, bounds: d.bounds },
);
(d.last, d.pointer, d.shift, d.moved) = (m, p, ev.mods.shift, moved);
self.drag = Some(d);
self.measure = Some((p, self.label(a, b)));
self.readout = Some(self.readout_of(m, a, b, d.bounds));
@@ -423,7 +454,12 @@ impl Tool for TransformTool {
// or moves only pattern tiles, and with anchors selected, whether it acts
// along the box or the page.
let m = if d.anchors {
self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0
self.solve(
d.angle_for(ev.mods.alt, ev.backquote),
d.origin,
SolveDrag { start: d.pick, p: d.pointer, moved: d.moved, shift: d.shift, bounds: d.bounds },
)
.0
} else {
d.last
};
@@ -445,7 +481,11 @@ impl Tool for TransformTool {
}
self.drop_axis();
let copy = ev.mods.alt;
let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds);
let (m, _, _) = self.solve(
d.angle_for(copy, ev.backquote),
first,
SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds },
);
vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit]
} else {
// A click sets the reference point; with Alt, it opens the dialog too. With the
@@ -741,6 +781,54 @@ mod tests {
assert!((c[0] - c[3]).abs() < 1e-9 && c[0] > 1.0);
}
/// A Shift-drag along one axis scales along that axis alone, and a diagonal one scales
/// uniformly (#6324): the drag's own direction decides, within 22.5° of an axis.
#[test]
fn scale_shift_follows_the_drag_direction() {
let t = TransformTool::new(TransformKind::Scale);
let o = Point::new(100.0, 100.0);
let scales = |p: Point| {
let c = t.matrix_for(o, Point::new(150.0, 140.0), p, true, Rect::ZERO).0.as_coeffs();
(c[0], c[3])
};
// Sideways, a little off the level: width only.
let (sx, sy) = scales(Point::new(200.0, 145.0));
assert!((sx - 2.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9, "{sx} {sy}");
// Up or down: height only.
let (sx, sy) = scales(Point::new(148.0, 180.0));
assert!((sx - 1.0).abs() < 1e-9 && (sy - 2.0).abs() < 1e-9, "{sx} {sy}");
// Diagonal: both, by the same factor.
let (sx, sy) = scales(Point::new(200.0, 180.0));
assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}");
// A drag that starts straight above (beside) the reference point has no width (height) to
// scale, so a sideways (up or down) Shift-drag from there scales uniformly, as before.
let from = |start: Point, p: Point| {
let c = t.matrix_for(o, start, p, true, Rect::ZERO).0.as_coeffs();
(c[0], c[3])
};
let (sx, sy) = from(Point::new(100.0, 150.0), Point::new(150.0, 160.0));
assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}");
let (sx, sy) = from(Point::new(150.0, 100.0), Point::new(160.0, 150.0));
assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}");
}
/// The axis of a Shift-drag comes from the pointer's own movement: a press near a corner
/// snaps to it, and a level drag from there still scales the width alone.
#[test]
fn scale_shift_axis_follows_the_pointer_not_the_snapped_press() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Default::default() };
let mut t = TransformTool::new(TransformKind::Scale);
t.pointer(&cx, &ev(PointerKind::Down, 198.0, 203.0).with_mods(shift));
let drag = t.pointer(&cx, &ev(PointerKind::Drag, 205.0, 203.0).with_mods(shift));
let c = matrix(drag.last().expect("a preview")).as_coeffs();
assert!((c[0] - 1.1).abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9, "the width alone: {c:?}");
}
#[test]
fn alt_click_opens_dialog_and_alt_release_copies() {
let (d, id) = doc_with_rect();
+1
View File
@@ -307,6 +307,7 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec<Param> {
let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2);
return vec![
Param::new("radius", tl!("Radius"), kind).length(lengths),
Param::new("addPoints", tl!(tangent_circle_tool::ADD_POINTS), ParamKind::bool(false)),
Param::new("center", tl!("Circle Center"), ParamKind::bool(true)),
Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)),
Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))),
+11 -3
View File
@@ -84,11 +84,18 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() {
assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight"));
ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]);
assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc"));
// The Tangent Circle tool's radius for Shift.
// The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start).
app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap();
assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("radius")), Some(36.0));
ok(&mut app, &[("radius", FieldValue::Number(12.5))]);
let shown = held(&app, |d| {
let f = d.expect("the held dialog").fields();
(f.number("radius"), f.bool("addPoints"))
});
assert_eq!(shown, (Some(36.0), Some(false)));
let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app));
assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row");
ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]);
assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5));
assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true));
assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err());
assert_eq!(KIND, "pathToolOptions");
}
@@ -150,6 +157,7 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() {
rows,
[
("radius", "Radius"),
("addPoints", "Add Points to Existing Paths"),
("center", "Circle Center"),
("radii", "Circle Radii Lines"),
("color", "Color"),
+11
View File
@@ -120,6 +120,7 @@ impl VectorcraftApp {
last_ms: 0.0,
moved: false,
from_worker: false,
worker_parts: false,
reused: None,
waits_for_still: cfg!(target_arch = "wasm32"),
still: None,
@@ -150,6 +151,7 @@ impl VectorcraftApp {
carry_target: None,
last_drag: None,
escaped_press: false,
host_caps_lock: None,
committed_preview: false,
panes: Default::default(),
windows: crate::doc_windows::Windows::new(known),
@@ -230,6 +232,7 @@ impl VectorcraftApp {
shortcuts_dialog: None,
shortcut_overrides: Default::default(),
told: Default::default(),
missing_font_edit_token: None,
held: Default::default(),
edit_scopes: Default::default(),
command_dialog: Default::default(),
@@ -443,6 +446,11 @@ impl VectorcraftApp {
let now = self.now();
self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0);
self.sync_views();
// With no document open too, so closing the last one stops the host reading the wheel. A
// held press, whose previews change the document each frame, keeps what it was told.
if self.canvas.grab.is_none() {
crate::stylus::sync_wheel_use(self);
}
// A document that moved between the main window and a floating OS window, or opened, takes
// the density of the display that shows it.
self.settle_screen_ppi_if_changed();
@@ -542,6 +550,9 @@ impl VectorcraftApp {
if let Some(wait) = crate::panels::actions::tick_playback(self, now) {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
}
// A `prefs.reset` run in this frame outside `Self::run` (a script's, say): the pass that follows draws the
// reset rows.
prefs_dialog::apply_prefs_resets(self);
}
/// The canvas panel's body: the document tabs, then the canvas (a pane for each document while
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff. Show more