diff --git a/Cargo.lock b/Cargo.lock index 14d5119325..0417aba6f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -123,10 +123,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -247,6 +258,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e465454e78fda6f7cd9dab7eb47518ca28c59b1bc392ca865af61452741dd3" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arboard" version = "3.7.0" @@ -606,6 +628,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -718,6 +758,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -808,6 +854,15 @@ dependencies = [ "winx", ] +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "cc" version = "1.9.0" @@ -902,8 +957,18 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", - "inout", + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.6", ] [[package]] @@ -935,6 +1000,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cmpv2" version = "0.2.0" @@ -953,7 +1024,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -1029,6 +1100,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1113,6 +1190,12 @@ dependencies = [ "libm", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1216,12 +1299,12 @@ dependencies = [ "craft-ui", "egui", "getrandom 0.3.4", - "hmac", + "hmac 0.12.1", "log", "png 0.17.16", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "web-time", ] @@ -1447,7 +1530,7 @@ dependencies = [ "ruzstd", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "skrifa 0.47.0", "tar", "thiserror 2.0.21", @@ -2154,7 +2237,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -2317,6 +2400,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -2335,7 +2436,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -2378,11 +2479,23 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "dirs" version = "7.0.0" @@ -3597,13 +3710,31 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + [[package]] name = "hmac" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", ] [[package]] @@ -3645,6 +3776,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -4101,6 +4241,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "inventory" version = "0.3.25" @@ -4458,6 +4608,15 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -4721,7 +4880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -4952,12 +5111,75 @@ dependencies = [ "memchr", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -6684,6 +6906,25 @@ dependencies = [ "tiny-skia 0.11.4", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.4", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -6823,7 +7064,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -6834,7 +7075,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -6894,12 +7146,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -6968,7 +7220,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -7007,7 +7259,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -8277,6 +8529,7 @@ dependencies = [ name = "vectorcraft-engine" version = "0.24.1" dependencies = [ + "apple-native-keyring-store", "cfb", "chrono", "craft-cdr", @@ -8290,12 +8543,15 @@ dependencies = [ "crc32fast", "encoding_rs", "flate2", + "getrandom 0.4.3", "hayro-ccitt", "heic-rs", + "hmac 0.12.1", "image", "jxl-color", "jxl-grid", "jxl-oxide", + "keyring-core", "kurbo 0.13.1", "log", "proptest", @@ -8305,6 +8561,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "sha2 0.10.9", "skrifa 0.47.0", "thiserror 2.0.21", "tiff", @@ -8331,6 +8588,8 @@ dependencies = [ "vectorcraft-tools", "vectorcraft-trace", "wat", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", "zune-core", "zune-jpegxl", ] @@ -8479,7 +8738,7 @@ dependencies = [ name = "vectorcraft-pdf" version = "0.24.1" dependencies = [ - "aes", + "aes 0.8.4", "chrono", "craft", "craft-image-codecs", @@ -8497,7 +8756,7 @@ dependencies = [ "objc2-core-graphics", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "siphasher", "skrifa 0.47.0", "smallvec", @@ -8522,7 +8781,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", @@ -9464,6 +9723,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -9821,7 +10093,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "sha1", "signature", @@ -10041,6 +10313,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 06be570630..47813f192e 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -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() } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 7c23fe71ba..db055d3246 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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}; diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index d4dc0e8cb0..b4940d192d 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) { } /// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones -/// installed from now on there. +/// installed from now on there. The key of the grants kept there is in the system's key store. pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { if let Some(dir) = store_dir("Plug-ins") { + vectorcraft_engine::store::grant_keys::use_os_grant_keys(); session.attach_plugin_store(dir); } } diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 745a5046f5..b8e6b88ee1 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -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 //! (). Pointer @@ -24,9 +25,12 @@ //! `rotation` in degrees 0..359 clockwise //! (). //! 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> = const { Cell::new(None) }; +} + /// The pen source [`msg_hook`] writes, once [`start`] has made it. static FEED: OnceLock = 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) -> 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) -> 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 +/// (); the posted pointer +/// messages are left to [`msg_hook`]. +fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> 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] diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs new file mode 100644 index 0000000000..31da32a1ff --- /dev/null +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -0,0 +1,1595 @@ +//! Windows: an airbrush pen's finger wheel. `POINTER_PEN_INFO` has no field for it +//! (), so +//! [`crate::windows_stylus`] keeps reading the pressure, end, tilt and rotation from pointer +//! messages, and this module reads only the wheel from the tablet driver's Wintab interface, as +//! its tangential pressure (`pkTangentPressure`), when the driver installs one. The Wintab +//! reference describes the context, packet and message calls used here +//! (), and the +//! Windows Ink comparison says the wheel comes only through Wintab +//! (). +//! +//! - Nothing here runs until the active tool draws with a brush or tip that varies with the +//! finger wheel (Stylus Wheel), as the app says through [`set_wheel_used`]: until then pen +//! messages load no library, install no hook and open no context, and when the tool stops +//! using the wheel the context closes ([`unused_context`]). +//! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen +//! comes over a window while the wheel is used. Without it, without one of its exports, or when +//! a call fails, the pens read no wheel and draw as before; the user sees no error. +//! - The context is opened from the driver's default context for the window that owns the pen's +//! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor +//! and makes no press. When the pen comes over another top-level window, such as a separate +//! document window, the context closes and opens again for that window, and the readings start +//! afresh ([`next_context`]). Each `WT_PACKET` for that window and context is read with `WTPacket` into +//! a buffer larger than any packet, and decoded from the fields the context asked for +//! ([`decode`]). +//! - Only a cursor the driver reports as an airbrush (`(CSR_TYPE & 0x0F06) == 0x0902`, from the +//! Wintab basics page: ) +//! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, +//! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 +//! ([`Axis::wheel`]); a value outside it reads as none. +//! - A pointer message of a pen takes the wheel of the airbrush whose latest packet came within +//! [`MAX_SKEW_MS`] of the message, and none when two are that recent or none is +//! ([`Readings::wheel_for`]). The first pen to read a wheel that way after the readings start +//! afresh takes the readings: other pens read none until they start afresh, and that pen keeps +//! reading the one airbrush read, however long ago its last packet came, since a pen held still +//! sends none. As on +//! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the +//! readings start afresh when a cursor +//! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns +//! to its other end, a press of the pen is canceled, the pen leaves the window or detection +//! range, or the context closes. These rules are VectorCraft's own. +//! +//! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's +//! information changes (`WT_INFOCHANGE`) unless the driver closed it too, and dropped when its +//! window no longer exists; a later pen message opens it again. The driver sends those two notices +//! to the window procedure, where a sent message does not pass winit's message hook, so the +//! context's window gets a window procedure in front of its own that notes them ([`Notices`]). +//! When that procedure cannot be put in front, no context is opened for the window +//! ([`hooked_open`]). An open that leaves no context is tried again for the same window by a pen +//! message [`RETRY_MS`] or more later ([`next_context`]). A hook on the messages Windows sends to +//! the thread's windows passes a pen's `WM_POINTERLEAVE` to [`crate::windows_stylus`], and closes +//! the context when another app becomes the active one (`WM_ACTIVATEAPP`). No pen message opens a +//! context while this app is not active, so the context does not sit in front of another app's in +//! the driver's overlap order. A packet that `WTPacket` cannot read starts the readings afresh +//! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed +//! (`TPS_QUEUE_ERR`, [`Readings::packet`]). +#![cfg_attr(not(windows), allow(dead_code))] + +/// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. +const WT_DEFBASE: u32 = 0x7FF0; +/// `WT_PACKET`, `WT_CTXCLOSE`, `WT_PROXIMITY`, `WT_INFOCHANGE` and `WT_CSRCHANGE` at that base. +const WT_PACKET: u32 = WT_DEFBASE; +const WT_CTXCLOSE: u32 = WT_DEFBASE + 2; +const WT_PROXIMITY: u32 = WT_DEFBASE + 5; +const WT_INFOCHANGE: u32 = WT_DEFBASE + 6; +const WT_CSRCHANGE: u32 = WT_DEFBASE + 7; + +/// `CXO_SYSTEM`, `CXO_PEN`, `CXO_MESSAGES` and `CXO_CSRMESSAGES` (`wintab.h`), in `lcOptions`. +const CXO_SYSTEM: u32 = 0x0001; +const CXO_PEN: u32 = 0x0002; +const CXO_MESSAGES: u32 = 0x0004; +const CXO_CSRMESSAGES: u32 = 0x0008; + +/// The packet fields (`PK_*`, `pktdef.h`) in the order a packet holds them, each with its size in +/// bytes: `pkContext` is a handle, `pkOrientation` and `pkRotation` three 32-bit values each, and +/// the others one 32-bit value. +const PK_CONTEXT: u32 = 0x0001; +const PK_STATUS: u32 = 0x0002; +const PK_TIME: u32 = 0x0004; +const PK_CHANGED: u32 = 0x0008; +const PK_SERIAL_NUMBER: u32 = 0x0010; +const PK_CURSOR: u32 = 0x0020; +const PK_BUTTONS: u32 = 0x0040; +const PK_X: u32 = 0x0080; +const PK_Y: u32 = 0x0100; +const PK_Z: u32 = 0x0200; +const PK_NORMAL_PRESSURE: u32 = 0x0400; +const PK_TANGENT_PRESSURE: u32 = 0x0800; +const PK_ORIENTATION: u32 = 0x1000; +const PK_ROTATION: u32 = 0x2000; +const FIELDS: [(u32, usize); 14] = [ + (PK_CONTEXT, std::mem::size_of::()), + (PK_STATUS, 4), + (PK_TIME, 4), + (PK_CHANGED, 4), + (PK_SERIAL_NUMBER, 4), + (PK_CURSOR, 4), + (PK_BUTTONS, 4), + (PK_X, 4), + (PK_Y, 4), + (PK_Z, 4), + (PK_NORMAL_PRESSURE, 4), + (PK_TANGENT_PRESSURE, 4), + (PK_ORIENTATION, 12), + (PK_ROTATION, 12), +]; + +/// The fields the context asks for (`lcPktData`), all absolute: the status, the cursor, the +/// position and the tangential pressure. +const PACKET_DATA: u32 = PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The changes that make a packet (`lcMoveMask`): a move, or a turn of the wheel in place. +const MOVE_MASK: u32 = PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The bytes `WTPacket` writes into: more than a packet of every field. +const PACKET_BUFFER: usize = 256; + +/// `TPS_PROXIMITY` and `TPS_QUEUE_ERR` (`wintab.h`), in `pkStatus`: the cursor is out of the +/// context, and the queue overflowed. +const TPS_PROXIMITY: u32 = 0x0001; +const TPS_QUEUE_ERR: u32 = 0x0002; + +/// The `LOGCONTEXTW` (`wintab.h`) as 32-bit words: a 40-character name, then `lcOptions`, +/// `lcStatus`, `lcLocks`, `lcMsgBase`, `lcDevice`, `lcPktRate`, `lcPktData`, `lcPktMode`, +/// `lcMoveMask`, `lcBtnDnMask` and `lcBtnUpMask`, and 22 words of extents and sensitivities. +const LOGCONTEXT_WORDS: usize = 53; +const _: () = assert!(LOGCONTEXT_WORDS * 4 == 212, "sizeof(LOGCONTEXTW)"); +const LC_OPTIONS: usize = 20; +const LC_MSG_BASE: usize = 23; +const LC_PKT_DATA: usize = 26; +const LC_PKT_MODE: usize = 27; +const LC_MOVE_MASK: usize = 28; +const LC_BTN_DN_MASK: usize = 29; +const LC_BTN_UP_MASK: usize = 30; + +/// `WTInfoW` categories and indexes (`wintab.h`): the interface's device count, the default +/// context, a device's first cursor, cursor count and tangential-pressure range, and a cursor's +/// packet fields and type. +const WTI_INTERFACE: u32 = 1; +const IFC_NDEVICES: u32 = 4; +const WTI_DEFCONTEXT: u32 = 3; +const WTI_DEVICES: u32 = 100; +const DVC_NCSRTYPES: u32 = 3; +const DVC_FIRSTCSR: u32 = 4; +const DVC_TPRESSURE: u32 = 16; +const WTI_CURSORS: u32 = 200; +const CSR_PKTDATA: u32 = 3; +const CSR_TYPE: u32 = 20; +/// Cursor and device numbers stay below the next category's base. +const MAX_INDEX: u32 = 100; +/// At most this many devices are looked through for a cursor's device. +const MAX_DEVICES: u32 = 16; + +/// A packet and a pointer message at most this far apart, in the message clock's milliseconds, +/// belong together. +const MAX_SKEW_MS: u32 = 200; +/// At most this many cursors' readings are kept. +const MAX_READINGS: usize = 4; +/// At most this many pens' ends are kept. +const MAX_PENS: usize = 16; + +/// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, +/// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on +/// a move or a turn of the wheel, and no button events. +fn configure(words: &mut [u32; LOGCONTEXT_WORDS]) { + words[LC_OPTIONS] = (words[LC_OPTIONS] | CXO_MESSAGES | CXO_CSRMESSAGES) & !(CXO_SYSTEM | CXO_PEN); + words[LC_MSG_BASE] = WT_DEFBASE; + words[LC_PKT_DATA] = PACKET_DATA; + words[LC_PKT_MODE] = 0; + words[LC_MOVE_MASK] = MOVE_MASK; + words[LC_BTN_DN_MASK] = 0; + words[LC_BTN_UP_MASK] = 0; +} + +/// The size in bytes of a packet holding the fields of `mask`. +fn packet_size(mask: u32) -> usize { + FIELDS.iter().filter(|(f, _)| mask & f != 0).map(|(_, n)| n).sum() +} + +/// The 32-bit field `field` of a packet holding the fields of `mask`, or `None` when the mask +/// leaves it out, it is not a 32-bit field, or `bytes` is too short. +fn field(bytes: &[u8], mask: u32, field: u32) -> Option { + if mask & field == 0 || bytes.len() < packet_size(mask) { + return None; + } + let mut at = 0; + for &(f, n) in &FIELDS { + if f == field { + let word = bytes.get(at..at + 4).filter(|_| n == 4)?; + return Some(u32::from_ne_bytes(word.try_into().ok()?)); + } + if mask & f != 0 { + at += n; + } + } + None +} + +/// What a packet says about the wheel. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Packet { + status: u32, + cursor: u32, + tangent: u32, +} + +/// The status, cursor and tangential pressure of a packet holding the fields of `mask`. +fn decode(bytes: &[u8], mask: u32) -> Option { + Some(Packet { status: field(bytes, mask, PK_STATUS)?, cursor: field(bytes, mask, PK_CURSOR)?, tangent: field(bytes, mask, PK_TANGENT_PRESSURE)? }) +} + +/// A device's tangential-pressure range (`AXIS`'s `axMin` and `axMax`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + min: i32, + max: i32, +} + +impl Axis { + /// The wheel, 0..1, for the absolute value `raw`: 0 at `axMin`, 1 at `axMax`. `pktdef.h` gives + /// an absolute tangential pressure as unsigned; with a range below 0 it is read as signed. A + /// value outside the range reads as none. + fn wheel(self, raw: u32) -> Option { + let (min, max) = (i64::from(self.min), i64::from(self.max)); + if min >= max { + return None; + } + let v = if min < 0 { i64::from(raw as i32) } else { i64::from(raw) }; + (min..=max).contains(&v).then(|| ((v - min) as f64 / (max - min) as f64) as f32) + } +} + +/// Whether a cursor of this `CSR_TYPE` is an airbrush. +fn is_airbrush(csr_type: u32) -> bool { + csr_type & 0x0F06 == 0x0902 +} + +/// The wheel range of a cursor of `csr_type` whose packets carry the fields of `csr_pktdata`, on a +/// device whose `DVC_TPRESSURE` reads as `axis` (`axMin`, `axMax`, `axUnits`, `axResolution`): +/// `None` unless it is an airbrush with a tangential pressure and the range is not empty. +fn wheel_axis(csr_type: u32, csr_pktdata: u32, axis: Option<[u32; 4]>) -> Option { + let [min, max, ..] = axis?; + let axis = Axis { min: min as i32, max: max as i32 }; + (is_airbrush(csr_type) && csr_pktdata & PK_TANGENT_PRESSURE != 0 && axis.min < axis.max).then_some(axis) +} + +/// The device of `cursor`, from each device's first cursor and cursor count (`DVC_FIRSTCSR`, +/// `DVC_NCSRTYPES`), or `None` when no device or more than one has it. +fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { + let mut found = devices.iter().enumerate().filter(|(_, (first, n))| first.checked_add(*n).is_some_and(|end| (*first..end).contains(&cursor))); + let (d, _) = found.next()?; + found.next().is_none().then_some(d) +} + +/// What the driver said about a cursor's wheel range. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lookup { + /// The range, or `None` for a cursor the driver describes without a wheel. + Known(Option), + /// A `WTInfoW` call failed at this message time. + Failed { at: u32 }, +} + +/// Each cursor's wheel range, as the driver reported it, until the driver's information changes. +#[derive(Clone, Debug, Default)] +struct Cursors(Vec<(u32, Lookup)>); + +impl Cursors { + /// The wheel range of `cursor` for a packet at the message time `time`, asking the driver with + /// `query` the first time, or again once [`retry_due`] after a query that failed (`Err`). + /// Until then a cursor whose query failed reads no wheel. + fn axis(&mut self, cursor: u32, time: u32, query: impl FnOnce() -> Result, ()>) -> Option { + if let Some(i) = self.0.iter().position(|(c, _)| *c == cursor) { + match self.0[i].1 { + Lookup::Known(axis) => return axis, + Lookup::Failed { at } if !retry_due(at, time) => return None, + Lookup::Failed { .. } => { + self.0.remove(i); + } + } + } + let lookup = match query() { + Ok(axis) => Lookup::Known(axis), + Err(()) => Lookup::Failed { at: time }, + }; + if self.0.len() >= MAX_READINGS * 4 { + self.0.remove(0); + } + self.0.push((cursor, lookup)); + match lookup { + Lookup::Known(axis) => axis, + Lookup::Failed { .. } => None, + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + +/// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. +fn near(a: u32, b: u32) -> bool { + (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS +} + +/// The latest packet of a cursor near the context. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Reading { + cursor: u32, + /// The cursor's wheel range, `None` for a cursor without a wheel. + axis: Option, + raw: u32, + /// The message time of the packet. + time: u32, + /// The cursor has reported a value other than 0 since the readings started afresh. + moved: bool, +} + +/// The latest packet of each cursor near the context, until the readings start afresh. +#[derive(Clone, Debug, Default)] +struct Readings { + list: Vec, + /// The pointer id of each pen whose pointer messages were read since the readings started + /// afresh, with the end its last message read (`true` for the eraser end), at most + /// [`MAX_PENS`] of them. + ends: Vec<(u32, bool)>, + /// The pointer id of the pen whose message first read the wheel since the readings started + /// afresh; another pen's messages read none. + pen: Option, + /// The cursor whose wheel that pen read; the pen reads no other cursor's wheel until the + /// readings start afresh. + cursor: Option, +} + +impl Readings { + /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of + /// a cursor out of the context drops that cursor's reading. A packet sent after the context's + /// queue overflowed starts every reading afresh, until the next packet. + fn packet(&mut self, p: Packet, axis: Option, time: u32) { + if p.status & TPS_QUEUE_ERR != 0 { + self.forget(); + return; + } + let at = self.list.iter().position(|r| r.cursor == p.cursor); + if p.status & TPS_PROXIMITY != 0 { + if let Some(i) = at { + self.list.remove(i); + } + return; + } + let moved = at.is_some_and(|i| self.list[i].moved && self.list[i].axis == axis) || p.tangent != 0; + let reading = Reading { cursor: p.cursor, axis, raw: p.tangent, time, moved }; + match at { + Some(i) => self.list[i] = reading, + None => { + if self.list.len() >= MAX_READINGS { + self.list.remove(0); + } + self.list.push(reading); + } + } + } + + /// A `WT_PACKET` read at the message time `time`: the packet with its cursor's wheel range, or + /// `None` when `WTPacket` failed or the packet could not be decoded. Then no reading is known to + /// be current, and the readings start afresh until the next packet. + fn read(&mut self, read: Option<(Packet, Option)>, time: u32) { + match read { + Some((p, axis)) => self.packet(p, axis, time), + None => self.forget(), + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet + /// could not be read, the context's queue overflowed, or the context closed. + fn forget(&mut self) { + self.list.clear(); + self.ends.clear(); + self.pen = None; + self.cursor = None; + } + + /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took + /// the readings, or `pen` when none has. + fn owner_or(&self, pen: u32) -> u32 { + self.pen.unwrap_or(pen) + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time + /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose + /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the + /// readings, the latest packet of the cursor whose wheel it read, however long ago it came (a + /// pen held still sends none) and whatever other cursors were read since. `None` when no cursor, + /// or more than one, is that recent, or the cursor has read only 0 since the readings started + /// afresh, or another pen's message read a wheel first since then. The same pen's turn to its + /// other end starts them afresh first; another pen's message with another end does not. + fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { + if self.pen.is_some_and(|p| p != pen) { + return None; + } + if self.ends.iter().any(|&(p, e)| p == pen && e != eraser) { + self.forget(); + } + match self.ends.iter_mut().find(|(p, _)| *p == pen) { + Some(end) => end.1 = eraser, + None => { + if self.ends.len() >= MAX_PENS { + self.ends.remove(0); + } + self.ends.push((pen, eraser)); + } + } + let r = if self.pen == Some(pen) { + let cursor = self.cursor?; + self.list.iter().find(|r| r.cursor == cursor)? + } else { + let mut near_time = self.list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; + } + r + }; + if !r.moved { + return None; + } + let wheel = r.axis?.wheel(r.raw)?; + self.pen = Some(pen); + self.cursor = Some(r.cursor); + Some(wheel) + } +} + +/// What a pen message does to the open context before it is opened for the pen's window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Current { + /// Nothing is open, or the context is the pen window's. + Keep, + /// The context's window is gone: drop the handle without a call on it. + Drop, + /// The context is another window's: close it with `WTClose`. + Close, +} + +/// After an open that left no context, the same window is tried again by the first pen message at +/// least this many milliseconds of the message clock later. +const RETRY_MS: u32 = 2000; + +/// The context step for a pen message to a window owned by `owner` at the message time `time`: +/// what happens to the open context, whose window is `current` with whether that window still +/// exists, and whether a context is opened for `owner`. The context follows the window the pen +/// draws in. While no context is open, the window and time of the last open tried (`tried`) keep +/// pen messages to that window from trying again until [`RETRY_MS`] have passed; another window, +/// or the driver closing or changing the context, tries at once. +/// A pen message to a window of an app that is not the active one (`active` false) opens none, so +/// the context never sits in front of the active app's own in the driver's overlap order. +fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32, active: bool) -> (Current, bool) { + let step = match current { + Some((_, false)) => Current::Drop, + Some((w, true)) if w == owner => return (Current::Keep, false), + Some(_) => Current::Close, + None => Current::Keep, + }; + let due = match tried { + Some((w, at)) if w == owner => retry_due(at, time), + _ => true, + }; + (step, active && (due || step != Current::Keep)) +} + +/// The context step for a pen message while the active tool reads no wheel ([`Wheel::Unused`]): +/// an open context closes, or is dropped when its window is gone (`current` as for +/// [`next_context`]), and none opens. +fn unused_context(current: Option<(usize, bool)>) -> Current { + match current { + Some((_, false)) => Current::Drop, + Some(_) => Current::Close, + None => Current::Keep, + } +} + +/// Whether the active tool draws with a brush or tip that varies with the finger wheel, as the +/// app last said ([`set_wheel_used`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Wheel { + /// No pen message loads `Wintab32.dll`, installs the thread's hook or opens a context, and a + /// context still open closes. + #[default] + Unused, + /// Pen messages open the context as [`next_context`] says. + Used, +} + +/// Whether a pen message calls the driver at all: while the wheel is used, or to close a context +/// still open after it stopped being used. +fn calls_driver(wheel: Wheel, open: bool) -> bool { + wheel == Wheel::Used || open +} + +/// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or +/// more later, on the message clock, which wraps. +fn retry_due(at: u32, time: u32) -> bool { + time.wrapping_sub(at) >= RETRY_MS +} + +/// At most this many contexts' closing notices wait for [`Notices::take`]. +const MAX_NOTICES: usize = 8; + +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`), and another app becoming +/// the active one (`WM_ACTIVATEAPP`), since they were last taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// call of its own, so they are noted here and acted on at the next Wintab or pen message. +#[derive(Clone, Debug, Default, PartialEq)] +struct Notices { + /// The contexts the driver closed or is about to close. + closed: Vec, + /// The driver's information changed. + info_changed: bool, + /// The readings were to start afresh while they were in use ([`Notices::forget_later`]). + forget: bool, + /// Another app became the active one. + deactivated: bool, +} + +/// What the driver's notices do to the open context. Both can come in one batch. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Notice { + /// The driver closed it: drop the handle without `WTClose`, and open a context again at the + /// next pen message. + closed: bool, + /// The driver's information changed: close it if it is still open, forget each cursor's wheel + /// range, and open a context again at the next pen message. + info_changed: bool, + /// Start the readings afresh. + forget: bool, + /// Another app became the active one: close the context, and open one again at the next pen + /// message once this app is active again. + deactivated: bool, +} + +impl Notices { + /// Notes `message` if it is a closing, information-change or deactivation notice. + fn note(&mut self, message: Message) { + match message { + Message::Closed { ctx } if !self.closed.contains(&ctx) => { + if self.closed.len() >= MAX_NOTICES { + self.closed.remove(0); + } + self.closed.push(ctx); + } + Message::InfoChange => self.info_changed = true, + Message::Deactivated => self.deactivated = true, + _ => {} + } + } + + /// The reader closed `ctx` itself: its closing notice is not the driver's, and a context opened + /// later with the same handle value stays open. + fn closed_by_reader(&mut self, ctx: usize) { + self.closed.retain(|&c| c != ctx); + } + + /// The readings are to start afresh, at a time they are in use, for example when the pen leaves + /// the window during a driver call: the next [`Notices::take`] says so. + fn forget_later(&mut self) { + self.forget = true; + } + + /// Takes the notices: what they do to the open context `current`. + fn take(&mut self, current: Option) -> Notice { + let notices = std::mem::take(self); + Notice { + closed: current.is_some_and(|c| notices.closed.contains(&c)), + info_changed: notices.info_changed, + forget: notices.forget, + deactivated: notices.deactivated, + } + } +} + +/// Opens a context with `open` only when `hook` put the window procedure that notes the driver's +/// notices in front of the window's own and, asked after every other driver call, this app is +/// still the active one (`active`); otherwise opens none, and the window is tried again as +/// [`next_context`] says. +fn hooked_open(hook: impl FnOnce() -> bool, active: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() && active() { open() } else { None } +} + +/// What a message does to the readings and the context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Message { + /// A packet with this serial number is waiting for the context `lparam` names. + Packet { + serial: u32, + ctx: usize, + }, + /// The readings start afresh for the context it names. + Forget { + ctx: usize, + }, + /// The context it names has closed. + Closed { + ctx: usize, + }, + /// The driver's information changed: the context closes and opens again. + InfoChange, + /// Another app became the active one: the context closes. + Deactivated, + Other, +} + +/// `WM_ACTIVATEAPP` (`winuser.h`): sent to the app's top-level windows when another app's window +/// is activated (`wParam` false) or one of the app's own is (true) +/// (). +const WM_ACTIVATEAPP: u32 = 0x001C; + +/// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` +/// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. +fn message(message: u32, wparam: usize, lparam: isize) -> Message { + match message { + WM_ACTIVATEAPP if wparam == 0 => Message::Deactivated, + WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, + WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, + WT_PROXIMITY => Message::Forget { ctx: wparam }, + WT_CTXCLOSE => Message::Closed { ctx: wparam }, + WT_INFOCHANGE => Message::InfoChange, + _ => Message::Other, + } +} + +#[cfg(windows)] +pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win { + use std::cell::{Cell, RefCell}; + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::System::Threading::GetCurrentThreadId; + use windows::Win32::UI::WindowsAndMessaging::{ + CWPSTRUCT, CallNextHookEx, CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetForegroundWindow, GetPropW, + GetWindowLongPtrW, GetWindowThreadProcessId, IsWindow, MSG, RemovePropW, SetPropW, SetWindowLongPtrW, SetWindowsHookExW, WH_CALLWNDPROC, + WM_NCDESTROY, WNDPROC, + }; + use windows::core::{PCWSTR, s, w}; + + use super::{ + Axis, CSR_PKTDATA, CSR_TYPE, Current, Cursors, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, + MAX_INDEX, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, PK_TANGENT_PRESSURE, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, + WTI_INTERFACE, Wheel, calls_driver, configure, decode, device_of, hooked_open, is_airbrush, message, next_context, retry_due, unused_context, + wheel_axis, + }; + + /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). + type WtInfo = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32; + type WtOpen = unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> *mut c_void; + type WtClose = unsafe extern "system" fn(*mut c_void) -> i32; + type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + + #[derive(Clone, Copy)] + struct Api { + info: WtInfo, + open: WtOpen, + close: WtClose, + packet: WtPacket, + } + + /// The bytes a packet is read into. + #[repr(C, align(8))] + struct PacketBuffer([u8; PACKET_BUFFER]); + + /// An open context and the window that owns it. + struct Context { + handle: *mut c_void, + hwnd: *mut c_void, + } + + #[derive(Default)] + struct State { + context: Option, + /// The window an open was last tried for, and the message time it was tried at + /// ([`next_context`]). + tried: Option<(*mut c_void, u32)>, + cursors: Cursors, + readings: Readings, + } + + thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends + /// while [`STATE`] is borrowed for a driver call. + static NOTICES: RefCell = RefCell::new(Notices::default()); + /// Whether the active tool uses the wheel ([`set_wheel_used`]), kept apart from [`STATE`] so + /// the app can say so while [`STATE`] is borrowed. + static WHEEL: Cell = const { Cell::new(Wheel::Unused) }; + } + + /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. + const PREV_PROC: PCWSTR = w!("VectorCraft.Wintab.PrevProc"); + + /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. + fn note(what: Message) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange | Message::Deactivated) { + return; + } + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.note(what); + } + }); + } + + /// The window procedure put in front of the context window's own: the driver sends + /// `WT_CTXCLOSE` and `WT_INFOCHANGE` (), + /// and a sent message reaches the window procedure without passing winit's message hook. It + /// notes them and passes every message on. + unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + note(message(msg, wparam.0, lparam.0)); + // SAFETY: `GetPropW` takes any handle value and a NUL-terminated name. + let prev = unsafe { GetPropW(hwnd, PREV_PROC) }.0; + if msg == WM_NCDESTROY { + // SAFETY: as above; the window is being destroyed. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } + if prev.is_null() { + // SAFETY: the default procedure takes any message of a window of this thread. + return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; + } + // SAFETY: the property holds the window procedure `subclass` replaced, which stays valid + // while the window exists. + let prev = unsafe { std::mem::transmute::<*mut c_void, WNDPROC>(prev) }; + // SAFETY: `prev` is the window's own procedure, called with the message it was sent. + unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } + } + + /// Another app became the active one: closes the context now, unless the reader is in a call of + /// its own, when the noted [`Message::Deactivated`] closes it at the next Wintab or pen message. + /// No pen messages come while another app is active, so waiting for one would leave the context + /// in front of that app's own. + fn deactivate() { + let Some(api) = api() else { return }; + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.take_notices(api); + } + }); + } + + /// Whether this app is the active one: the foreground window belongs to this thread, which + /// runs every window of the app. + fn is_active() -> bool { + // SAFETY: `GetForegroundWindow` takes no arguments. + let foreground = unsafe { GetForegroundWindow() }; + // SAFETY: `GetWindowThreadProcessId` takes any handle value, and no process id is asked for. + !foreground.0.is_null() && unsafe { GetWindowThreadProcessId(foreground, None) } == unsafe { GetCurrentThreadId() } + } + + /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's + /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a + /// top-level window of the app, ) + /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` + /// () go to + /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows + /// they are sent to (). + unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + // SAFETY: for `HC_ACTION` (0), `lParam` points to the message's `CWPSTRUCT`, which + // lives for the call; `as_ref` gives `None` for a null pointer. + if let Some(cwp) = unsafe { (lparam.0 as *const CWPSTRUCT).as_ref() } { + if message(cwp.message, cwp.wParam.0, cwp.lParam.0) == Message::Deactivated { + note(Message::Deactivated); + deactivate(); + } + crate::windows_stylus::sent_message(cwp.message, cwp.wParam.0); + } + } + // SAFETY: every hook procedure passes the call on, with what it was given. + unsafe { CallNextHookEx(None, code, wparam, lparam) } + } + + /// Installs [`call_wnd_proc`] for this thread, for a pen message at the message time `time`, + /// unless it is installed, and returns whether it is. It stays for the life of the thread. After + /// a failed install, a pen message tries again once [`retry_due`]. + fn hook_thread(time: u32) -> bool { + thread_local! { + /// Installed, or the message time of the last failed install. + static HOOK: std::cell::Cell>> = const { std::cell::Cell::new(Err(None)) }; + } + match HOOK.get() { + Ok(()) => return true, + Err(Some(at)) if !retry_due(at, time) => return false, + Err(_) => {} + } + // SAFETY: a hook of this thread, whose procedure is in this executable, so no module + // handle is passed. + let hooked = unsafe { SetWindowsHookExW(WH_CALLWNDPROC, Some(call_wnd_proc), None, GetCurrentThreadId()) }.is_ok(); + HOOK.set(if hooked { Ok(()) } else { Err(Some(time)) }); + hooked + } + + /// Closes the context for a deactivation noted while the reader was in a call of its own + /// ([`deactivate`]), once that call has ended. + fn settle() { + if NOTICES.with(|n| n.try_borrow().is_ok_and(|n| n.deactivated)) { + deactivate(); + } + } + + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns + /// whether it is there. The window's property holds the procedure it replaced, and goes with the + /// window. + fn subclass(hwnd: *mut c_void) -> bool { + let hwnd = HWND(hwnd); + // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. + if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { + return true; + } + // SAFETY: as above. + let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; + if prev == 0 { + return false; + } + // SAFETY: the window is this thread's (winit's), and the property's value is a procedure + // address, not memory the system frees. + if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { + return false; + } + type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; + // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. + if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { + // SAFETY: as for `SetPropW`. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + return false; + } + true + } + + /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. + fn api() -> Option { + static API: OnceLock> = OnceLock::new(); + *API.get_or_init(|| { + // SAFETY: Wintab32.dll is loaded from the system directory only, and stays loaded for + // the process, so the function pointers below stay valid. + let module = unsafe { LoadLibraryExW(w!("Wintab32.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?; + // SAFETY: the names are NUL-terminated, and the module is loaded. + let (info, open, close, packet) = unsafe { + ( + GetProcAddress(module, s!("WTInfoW"))?, + GetProcAddress(module, s!("WTOpenW"))?, + GetProcAddress(module, s!("WTClose"))?, + GetProcAddress(module, s!("WTPacket"))?, + ) + }; + type Proc = unsafe extern "system" fn() -> isize; + // SAFETY: the exports have these signatures (`wintab.h`). + unsafe { + Some(Api { + info: std::mem::transmute::(info), + open: std::mem::transmute::(open), + close: std::mem::transmute::(close), + packet: std::mem::transmute::(packet), + }) + } + }) + } + + /// `WTInfoW`'s answer for `category` and `index`, when it is exactly `N` 32-bit words. + fn info(api: Api, category: u32, index: u32) -> Option<[u32; N]> { + // SAFETY: a null buffer asks for the size only. + let size = unsafe { (api.info)(category, index, std::ptr::null_mut()) } as usize; + if N > 128 || size != N * 4 { + return None; + } + // Room for more than asked, should the driver write more than it said. + let mut buf = [0u32; 128]; + // SAFETY: `buf` holds 512 bytes, more than the size the driver gave. + let wrote = unsafe { (api.info)(category, index, buf.as_mut_ptr().cast()) } as usize; + let mut out = [0u32; N]; + out.copy_from_slice(buf.get(..N)?); + (wrote == N * 4).then_some(out) + } + + /// The wheel range of `cursor`: `Ok(None)` for a cursor the driver describes without one, and + /// `Err` when a `WTInfoW` call it needs fails. + fn cursor_axis(api: Api, cursor: u32) -> Result, ()> { + if cursor >= MAX_INDEX { + return Ok(None); + } + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE).ok_or(())?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA).ok_or(())?; + if !is_airbrush(csr_type) || csr_pktdata & PK_TANGENT_PRESSURE == 0 { + return Ok(None); + } + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES).ok_or(())?; + let mut devices = vec![]; + for d in 0..count.min(MAX_DEVICES) { + let [first] = info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR).ok_or(())?; + let [n] = info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES).ok_or(())?; + devices.push((first, n)); + } + let Some(device) = device_of(cursor, &devices).and_then(|d| u32::try_from(d).ok()) else { return Ok(None) }; + let range = info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE).ok_or(())?; + Ok(wheel_axis(csr_type, csr_pktdata, Some(range))) + } + + /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. + fn context_open() -> bool { + STATE.with(|s| !s.try_borrow().is_ok_and(|s| s.context.is_none())) + } + + fn is_window(hwnd: *mut c_void) -> bool { + // SAFETY: `IsWindow` takes any handle value and reads no caller memory. + unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() + } + + impl State { + fn close(&mut self, api: Api) { + if let Some(c) = self.context.take() { + // SAFETY: the handle came from `WTOpenW` and has not been closed. + unsafe { (api.close)(c.handle) }; + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.closed_by_reader(c.handle as usize); + } + }); + } + self.readings.forget(); + } + + /// Acts on the driver's notices since the last look ([`Notices::take`]). + fn take_notices(&mut self, api: Api) { + let current = self.context.as_ref().map(|c| c.handle as usize); + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::default(), |mut n| n.take(current))); + if notice.closed { + self.context = None; + self.tried = None; + self.readings.forget(); + } + if notice.info_changed { + self.close(api); + self.tried = None; + self.cursors.clear(); + } + if notice.forget { + self.readings.forget(); + } + if notice.deactivated { + self.close(api); + self.tried = None; + } + } + + /// Moves the context to the window that owns `hwnd`, for a pen message at the message time + /// `time` ([`next_context`]), or closes it when the active tool does not use the wheel + /// (`wheel`, [`unused_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32, wheel: Wheel) { + // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. + let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; + let owner = if owner.is_null() { hwnd } else { owner }; + let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); + let tried = self.tried.map(|(w, at)| (w as usize, at)); + let (step, open) = match wheel { + Wheel::Used => next_context(current, tried, owner as usize, time, is_active()), + Wheel::Unused => (unused_context(current), false), + }; + match step { + Current::Keep => {} + Current::Drop => { + self.context = None; + self.readings.forget(); + } + Current::Close => self.close(api), + } + if !open { + return; + } + self.tried = Some((owner, time)); + let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; + configure(&mut words); + // Whether the app is active is asked again here, after the close and `WTInfoW` above. + let handle = hooked_open( + || subclass(owner), + is_active, + || { + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for + // the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + (!handle.is_null()).then_some(handle) + }, + ); + if let Some(handle) = handle { + self.context = Some(Context { handle, hwnd: owner }); + } + } + + fn ours(&self, hwnd: *mut c_void, ctx: usize) -> Option<*mut c_void> { + self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) + } + + fn axis(&mut self, api: Api, cursor: u32, time: u32) -> Option { + self.cursors.axis(cursor, time, || cursor_axis(api, cursor)) + } + } + + /// winit's message hook for the Wintab messages: reads each packet of the context and starts + /// the readings afresh on a cursor's change or proximity. A closing or information-change + /// notice that comes through the queue is noted as [`wnd_proc`] notes a sent one. It never + /// consumes the message. + pub fn msg_hook(msg: &MSG) { + let what = message(msg.message, msg.wParam.0, msg.lParam.0); + if what == Message::Other { + return; + } + if !calls_driver(WHEEL.get(), context_open()) { + return; + } + let Some(api) = api() else { return }; + note(what); + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.take_notices(api); + match what { + Message::Packet { serial, ctx } => { + let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; + let mut buf = PacketBuffer([0; PACKET_BUFFER]); + // SAFETY: the handle is the open context's, and `buf` holds more bytes than a + // packet of every field. + let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor, msg.time))); + s.readings.read(read, msg.time); + } + Message::Forget { ctx } => { + if s.ours(msg.hwnd.0, ctx).is_some() { + s.readings.forget(); + } + } + Message::Closed { .. } | Message::InfoChange | Message::Deactivated | Message::Other => {} + } + }); + settle(); + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message + /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when + /// none is open. While the active tool does not use the wheel ([`set_wheel_used`]), it reads + /// none and calls the driver only to close a context still open ([`calls_driver`]). The first + /// call that opens a context installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// installed, no context opens and the pens read no wheel. + pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { + let used = WHEEL.get(); + if !calls_driver(used, context_open()) { + return None; + } + let api = api()?; + if used == Wheel::Used && !hook_thread(time) { + return None; + } + let wheel = STATE.with(|s| { + let mut s = s.try_borrow_mut().ok()?; + s.take_notices(api); + s.open_for(api, hwnd.0, time, used); + s.readings.wheel_for(time, pen, eraser) + }); + settle(); + wheel.filter(|_| used == Wheel::Used) + } + + /// The app says whether the active tool draws with a brush or tip that varies with the finger + /// wheel (`used`). Until it says so, pen messages read no wheel and leave the driver alone; when + /// it stops, the context closes now, or at the next pen message while the reader is in a call + /// of its own. + pub fn set_wheel_used(used: bool) { + let wheel = if used { Wheel::Used } else { Wheel::Unused }; + if WHEEL.replace(wheel) == wheel { + return; + } + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.tried = None; + if wheel == Wheel::Unused + && s.context.is_some() + && let Some(api) = api() + { + // A context the driver closed is dropped without `WTClose`. + s.take_notices(api); + s.close(api); + } + }); + settle(); + } + + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer + /// id `pen` ([`Readings::owner_or`]). + pub fn wheel_pen(pen: u32) -> u32 { + STATE.with(|s| s.try_borrow().map_or(pen, |s| s.readings.owner_or(pen))) + } + + /// Start the readings afresh: the pen left the window or detection range, or a press was + /// canceled. While the readings are in use, as in a driver call, they start afresh at the next + /// Wintab or pen message ([`Notices::forget_later`]). + pub fn forget() { + STATE.with(|s| match s.try_borrow_mut() { + Ok(mut s) => s.readings.forget(), + Err(_) => NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.forget_later(); + } + }), + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pointer id of the pen in the tests that use one pen. + const PEN: u32 = 1; + + impl Readings { + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + self.wheel_for(time, PEN, eraser) + } + } + + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler + /// when it has none, and the wider fields hold filler bytes. + fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { + let mut out = vec![]; + for &(f, n) in &FIELDS { + if mask & f == 0 { + continue; + } + let v = values.iter().find(|(k, _)| *k == f).map_or(0xAAAA_AAAA, |&(_, v)| v); + if n == 4 { + out.extend(v.to_ne_bytes()); + } else { + out.extend(std::iter::repeat_n(0xEE, n)); + } + } + out + } + + #[test] + fn the_context_asks_for_the_wheel_without_the_system_cursor() { + let mut words = [0u32; LOGCONTEXT_WORDS]; + words[LC_OPTIONS] = CXO_SYSTEM | CXO_PEN | 0x8000; + words[LC_MSG_BASE] = 0x1234; + words[LC_BTN_DN_MASK] = !0; + words[LC_BTN_UP_MASK] = !0; + words[LC_PKT_MODE] = PK_TANGENT_PRESSURE; + words[31] = 77; + configure(&mut words); + assert_eq!(words[LC_OPTIONS], CXO_MESSAGES | CXO_CSRMESSAGES | 0x8000, "the driver's other options stay"); + assert_eq!(words[LC_MSG_BASE], WT_DEFBASE); + assert_eq!(words[LC_PKT_DATA], PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE); + assert_eq!(words[LC_PKT_MODE], 0, "absolute"); + assert_eq!(words[LC_MOVE_MASK] & PK_TANGENT_PRESSURE, PK_TANGENT_PRESSURE, "a turn in place makes a packet"); + assert_eq!((words[LC_BTN_DN_MASK], words[LC_BTN_UP_MASK]), (0, 0)); + assert_eq!(words[31], 77, "the extents stay the driver's"); + } + + #[test] + fn packets_are_read_in_the_order_of_their_fields() { + let want = Packet { status: 0, cursor: 3, tangent: 600 }; + let p = bytes(PACKET_DATA, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), 20); + assert_eq!(decode(&p, PACKET_DATA), Some(want)); + // Every field before the tangential pressure, the context handle and the orientation + // after it. + let all = FIELDS.iter().fold(0, |m, (f, _)| m | f); + let p = bytes(all, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), packet_size(all)); + assert_eq!(packet_size(all), std::mem::size_of::() + 4 * 11 + 24); + assert_eq!(decode(&p, all), Some(want)); + assert_eq!(decode(&p[..p.len() - 1], all), None, "a short packet"); + assert_eq!(decode(&p, PK_STATUS | PK_CURSOR), None, "no tangential pressure"); + assert_eq!(field(&p, all, PK_ORIENTATION), None, "not a 32-bit field"); + assert!(packet_size(all) <= PACKET_BUFFER); + } + + #[test] + fn only_an_airbrush_with_a_range_reads_a_wheel() { + let range = |min: i32, max: i32| Some([min as u32, max as u32, 0, 0]); + let airbrush = 0x0902; + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 1023)), Some(Axis { min: 0, max: 1023 })); + assert_eq!(wheel_axis(0x090A, PK_TANGENT_PRESSURE, range(-1023, 1023)), Some(Axis { min: -1023, max: 1023 }), "its other end"); + assert_eq!(wheel_axis(0x0802, PACKET_DATA, range(0, 1023)), None, "a general stylus"); + assert_eq!(wheel_axis(0x0804, PACKET_DATA, range(0, 1023)), None, "an Art Pen"); + assert_eq!(wheel_axis(airbrush, PK_X | PK_Y, range(0, 1023)), None, "no tangential pressure"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, None), None, "no range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 0)), None, "an empty range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(1023, 0)), None, "a falling range"); + } + + #[test] + fn the_wheel_is_its_place_in_the_range() { + let axis = Axis { min: 0, max: 1000 }; + assert_eq!(axis.wheel(0), Some(0.0)); + assert_eq!(axis.wheel(250), Some(0.25)); + assert_eq!(axis.wheel(1000), Some(1.0)); + assert_eq!(axis.wheel(1001), None, "past the end"); + assert_eq!(axis.wheel(u32::MAX), None); + let signed = Axis { min: -1000, max: 1000 }; + assert_eq!(signed.wheel(-1000i32 as u32), Some(0.0)); + assert_eq!(signed.wheel(0), Some(0.5)); + assert_eq!(signed.wheel(500), Some(0.75)); + assert_eq!(signed.wheel(i32::MIN as u32), None); + let wide = Axis { min: i32::MIN, max: i32::MAX }; + assert_eq!(wide.wheel(i32::MAX as u32), Some(1.0), "no overflow"); + assert_eq!(Axis { min: 5, max: 5 }.wheel(5), None); + } + + #[test] + fn a_cursor_belongs_to_one_device() { + let devices = [(0, 3), (3, 3)]; + assert_eq!(device_of(1, &devices), Some(0)); + assert_eq!(device_of(4, &devices), Some(1)); + assert_eq!(device_of(6, &devices), None); + assert_eq!(device_of(1, &[(0, 3), (1, 1)]), None, "two devices claim it"); + assert_eq!(device_of(u32::MAX, &[(u32::MAX - 1, 5)]), None, "a range past the end"); + assert_eq!(device_of(0, &[]), None); + } + + const AXIS: Option = Some(Axis { min: 0, max: 1000 }); + + fn packet(cursor: u32, tangent: u32) -> Packet { + Packet { status: 0, cursor, tangent } + } + + #[test] + fn a_pen_message_takes_the_wheel_of_the_recent_airbrush() { + let mut r = Readings::default(); + assert_eq!(r.wheel_at(1000, false), None, "no packet"); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1010, false), Some(0.25)); + assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); + assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.forget(); + r.packet(packet(1, 1000), AXIS, u32::MAX - 5); + r.packet(packet(2, 500), None, u32::MAX); + assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); + r.packet(packet(1, 1000), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); + r.forget(); + r.packet(packet(2, 500), None, 100); + assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); + r.packet(packet(1, 2000), AXIS, 300); + assert_eq!(r.wheel_at(500, false), None, "a value past the range"); + } + + #[test] + fn a_pen_keeps_the_airbrush_whose_wheel_it_read() { + let mut r = Readings::default(); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1000, false), Some(0.25)); + // Another tablet's airbrush moves while the pen is held still. + r.packet(packet(2, 750), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(0.25), "its own cursor's wheel, not the other's"); + assert_eq!(r.wheel_at(9000, false), Some(0.25), "however old both packets are"); + r.packet(packet(1, 500), AXIS, 6000); + assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 500) }, AXIS, 6100); + r.packet(packet(2, 750), AXIS, 6105); + assert_eq!(r.wheel_at(6110, false), None, "its own cursor left; the other's is not taken"); + r.forget(); + r.packet(packet(2, 750), AXIS, 7000); + assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); + } + + #[test] + fn zero_is_no_wheel_until_the_pen_reports_another_value() { + let mut r = Readings::default(); + r.packet(packet(1, 0), AXIS, 100); + assert_eq!(r.wheel_at(100, false), None); + r.packet(packet(1, 300), AXIS, 110); + r.packet(packet(1, 0), AXIS, 120); + assert_eq!(r.wheel_at(120, false), Some(0.0), "a real 0 after another value"); + r.forget(); + r.packet(packet(1, 0), AXIS, 130); + assert_eq!(r.wheel_at(130, false), None, "afresh after the pen came near"); + } + + #[test] + fn the_readings_start_afresh_for_the_other_end_and_out_of_the_context() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_at(100, false), Some(0.3)); + assert_eq!(r.wheel_at(100, true), None, "the other end"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, true), Some(0.3)); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 300) }, AXIS, 120); + assert_eq!(r.wheel_at(120, true), None, "out of the context"); + r.packet(packet(1, 300), AXIS, 130); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(1, 300) }, AXIS, 140); + assert_eq!(r.wheel_at(140, true), None, "the queue overflowed"); + // The eraser end leaves; the tip's first message after it keeps the tip's packet. + r.forget(); + r.packet(packet(1, 300), AXIS, 150); + assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + r.forget(); + for c in 0..10 { + r.packet(packet(c, 300), AXIS, 1000 * c); + } + assert_eq!(r.list.len(), MAX_READINGS, "bounded"); + assert_eq!(r.wheel_at(9000, false), Some(0.3)); + } + + /// [`next_context`] while this app is the active one. + fn step(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32) -> (Current, bool) { + next_context(current, tried, owner, time, true) + } + + #[test] + fn the_context_follows_the_window_the_pen_draws_in() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(step(None, None, main, t), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t), (Current::Keep, false), "the same window keeps it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t + 60_000), (Current::Keep, false), "however long it is open"); + assert_eq!(step(Some((main, true)), Some((main, t)), doc, t), (Current::Close, true), "another document window"); + assert_eq!(step(Some((doc, true)), Some((doc, t)), main, t), (Current::Close, true), "and back"); + assert_eq!(step(Some((main, false)), Some((main, t)), doc, t), (Current::Drop, true), "a window that is gone"); + assert_eq!(step(Some((main, false)), Some((main, t)), main, t), (Current::Drop, true), "its handle reused"); + assert_eq!(step(None, Some((main, t)), main, t + 1), (Current::Keep, false), "an open that failed is not tried at once"); + assert_eq!(step(None, Some((main, t)), doc, t + 1), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn a_window_whose_open_failed_is_tried_again_later() { + let main = 0x10; + let t = 1000; + for dt in [0, 1, 500, RETRY_MS - 1] { + assert_eq!(step(None, Some((main, t)), main, t + dt), (Current::Keep, false), "{dt} ms later"); + } + assert_eq!(step(None, Some((main, t)), main, t + RETRY_MS), (Current::Keep, true), "after the retry interval"); + assert_eq!(step(None, Some((main, t)), main, t + 60_000), (Current::Keep, true), "or long after"); + // The message clock wraps after about 49.7 days. + let late = u32::MAX - 100; + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(50)), (Current::Keep, false), "across the wrap"); + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(RETRY_MS)), (Current::Keep, true), "and due across it"); + } + + #[test] + fn a_failed_step_is_retried_after_the_interval() { + assert!(!retry_due(1000, 1000), "at once"); + assert!(!retry_due(1000, 1000 + RETRY_MS - 1)); + assert!(retry_due(1000, 1000 + RETRY_MS), "after the interval"); + assert!(retry_due(u32::MAX - 10, (u32::MAX - 10).wrapping_add(RETRY_MS)), "across the clock's wrap"); + assert!(!retry_due(u32::MAX - 10, 5), "and not early across it"); + } + + #[test] + fn no_context_opens_while_another_app_is_active() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(next_context(None, None, main, t, false), (Current::Keep, false), "a pen hovering over an inactive window"); + assert_eq!(next_context(None, Some((main, t)), main, t + RETRY_MS, false), (Current::Keep, false), "not even when a retry is due"); + assert_eq!(next_context(Some((main, true)), None, doc, t, false), (Current::Close, false), "another window's context closes"); + assert_eq!(next_context(Some((main, false)), None, main, t, false), (Current::Drop, false), "a gone window's is dropped"); + assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); + } + + #[test] + fn the_driver_is_left_alone_until_the_wheel_is_used() { + assert!(!calls_driver(Wheel::Unused, false), "no brush or tip on Stylus Wheel"); + assert!(calls_driver(Wheel::Used, false), "one is: the context opens"); + assert!(calls_driver(Wheel::Unused, true), "none any more: the open context closes"); + assert_eq!(Wheel::default(), Wheel::Unused, "at start-up"); + let main = 0x10; + assert_eq!(unused_context(None), Current::Keep, "nothing open"); + assert_eq!(unused_context(Some((main, true))), Current::Close, "the pen window's context closes"); + assert_eq!(unused_context(Some((main, false))), Current::Drop, "a gone window's is dropped"); + } + + #[test] + fn another_app_becoming_active_closes_the_context() { + assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); + assert_eq!(message(WM_ACTIVATEAPP, 1, 0), Message::Other, "this app becoming active"); + let ours = 0x5000; + let mut n = Notices::default(); + n.note(Message::Deactivated); + assert_eq!(n.take(Some(ours)), Notice { deactivated: true, ..Notice::default() }); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.note(Message::Deactivated); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, deactivated: true, ..Notice::default() }, "beside the driver's close"); + } + + #[test] + fn a_packet_that_cannot_be_read_starts_the_readings_afresh() { + let mut r = Readings::default(); + r.read(Some((packet(1, 750), AXIS)), 100); + assert_eq!(r.wheel_at(100, false), Some(0.75)); + r.read(None, 110); + assert_eq!(r.wheel_at(110, false), None, "the last reading is not kept after a failed read"); + r.read(Some((packet(1, 500), AXIS)), 120); + assert_eq!(r.wheel_at(120, false), Some(0.5), "the next packet reads again"); + } + + #[test] + fn the_drivers_notices_drop_or_reopen_the_context() { + let (ours, other) = (0x5000, 0x6000); + let keep = Notice::default(); + let closed = Notice { closed: true, ..Notice::default() }; + let reopen = Notice { info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + assert_eq!(n.take(Some(ours)), keep, "no notice"); + n.note(Message::Closed { ctx: other }); + assert_eq!(n.take(Some(ours)), keep, "another context closed"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), keep, "taken once"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(None), keep, "nothing open"); + assert_eq!(n, Notices::default(), "and the notice is gone"); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), reopen); + n.note(Message::InfoChange); + assert_eq!(n.take(None), reopen, "cursor ranges are read again even with nothing open"); + // The reader closes its context, and the driver's notice of that arrives during the call; + // a context opened next under the same handle value stays open. + n.note(Message::Closed { ctx: ours }); + n.closed_by_reader(ours); + assert_eq!(n.take(Some(ours)), keep); + for ctx in 0..20 { + n.note(Message::Closed { ctx }); + n.note(Message::Closed { ctx }); + } + assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); + assert_eq!(n.take(Some(19)), closed, "the latest kept"); + n.note(Message::Packet { serial: 1, ctx: ours }); + n.note(Message::Forget { ctx: ours }); + n.note(Message::Other); + assert_eq!(n, Notices::default(), "other messages are not notices"); + } + + #[test] + fn a_close_and_an_information_change_in_one_batch_both_count() { + let ours = 0x5000; + let both = Notice { closed: true, info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + n.note(Message::Closed { ctx: ours }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), both, "the closed handle is dropped, not closed again"); + n.note(Message::InfoChange); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), both, "in either order"); + n.note(Message::Closed { ctx: 0x6000 }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice { info_changed: true, ..Notice::default() }, "another context's close"); + } + + #[test] + fn a_leave_while_the_readings_are_in_use_starts_them_afresh_next() { + let ours = 0x5000; + let mut n = Notices::default(); + n.forget_later(); + assert_eq!(n.take(Some(ours)), Notice { forget: true, ..Notice::default() }, "the next look starts the readings afresh"); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.forget_later(); + assert_eq!(n.take(None), Notice { forget: true, ..Notice::default() }, "with nothing open too"); + n.forget_later(); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, forget: true, ..Notice::default() }, "beside a close"); + } + + #[test] + fn a_context_opens_only_behind_the_window_procedure() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || true, open), Some(7)); + assert_eq!(opens.get(), 1); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| false, || true, open), None, "no context without the procedure"); + assert_eq!(opens.get(), 1, "and the driver is not asked for one"); + assert_eq!(hooked_open(|| true, || true, || None::), None, "an open that fails"); + } + + #[test] + fn no_context_opens_when_another_app_became_active_before_the_open() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || false, open), None); + assert_eq!(opens.get(), 0, "the driver is not asked for one"); + } + + #[test] + fn another_pens_end_does_not_start_the_readings_afresh() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, true), None, "an eraser end before any packet"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(120, false), Some(0.3), "another pen's tip still reads the packet"); + assert_eq!(r.wheel_at(130, true), None, "the same pen turned over starts them afresh"); + // Pen 1's tip, then pen 2's, then pen 1's eraser, before either reads a wheel. + r.forget(); + assert_eq!(r.wheel_at(200, false), None, "no packet yet"); + assert_eq!(r.wheel_for(210, other, false), None); + r.packet(packet(1, 300), AXIS, 220); + assert_eq!(r.wheel_at(230, true), None, "pen 1's turn is seen past pen 2's message"); + for pen in 10..40 { + r.wheel_for(5000, pen, false); + } + assert_eq!(r.ends.len(), MAX_PENS, "bounded"); + } + + #[test] + fn a_failed_cursor_lookup_is_asked_again_later() { + let asks = std::cell::Cell::new(0); + let failing = || { + asks.set(asks.get() + 1); + Err(()) + }; + let mut c = Cursors::default(); + assert_eq!(c.axis(1, 1000, failing), None); + assert_eq!(c.axis(1, 1000 + RETRY_MS - 1, || Ok(AXIS)), None, "not asked again before the interval"); + assert_eq!(asks.get(), 1); + assert_eq!(c.axis(1, 1000 + RETRY_MS, || Ok(AXIS)), AXIS, "asked again after it"); + assert_eq!(c.axis(1, 9000, || Ok(None)), AXIS, "a range the driver gave is kept"); + assert_eq!(c.axis(2, 9000, || Ok(None)), None, "a cursor without a wheel"); + assert_eq!(c.axis(2, 9000 + RETRY_MS, || Ok(AXIS)), None, "is not asked again"); + c.clear(); + assert_eq!(c.axis(2, 9000, || Ok(AXIS)), AXIS, "until the driver's information changes"); + for cursor in 10..40 { + c.axis(cursor, 9000, || Ok(None)); + } + assert_eq!(c.0.len(), MAX_READINGS * 4, "bounded"); + } + + #[test] + fn the_readings_belong_to_the_pen_that_took_them_first() { + let other = 2; + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_for(5000, other, false), None, "a pen message long after the packet does not take them"); + assert_eq!(r.wheel_for(150, other, false), Some(0.3), "one near the packet does"); + assert_eq!(r.wheel_at(5010, false), None, "another pen with no packets of its own"); + assert_eq!(r.wheel_for(5020, other, false), Some(0.3), "and the pen that took them still reads them"); + r.forget(); + assert_eq!(r.wheel_at(5030, false), None, "no packet since the readings started afresh"); + r.packet(packet(1, 400), AXIS, 5040); + assert_eq!(r.wheel_at(5040, false), Some(0.4), "then another pen takes them"); + } + + #[test] + fn a_pen_takes_the_readings_only_when_it_reads_a_wheel() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, false), None, "no packet yet"); + assert_eq!(r.owner_or(PEN), PEN, "and no pen took the readings"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, false), Some(0.3), "the pen with the reading"); + assert_eq!(r.owner_or(other), PEN, "the pen whose leaving starts the readings afresh"); + r.forget(); + assert_eq!(r.owner_or(other), other); + } + + #[test] + fn a_queue_overflow_starts_every_reading_afresh() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + r.packet(packet(2, 500), None, 110); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(2, 500) }, None, 120); + assert!(r.list.is_empty(), "the queue is the context's, not the cursor's"); + assert_eq!(r.wheel_at(5000, false), None, "the airbrush's old wheel is not taken"); + r.packet(packet(1, 400), AXIS, 5000); + assert_eq!(r.wheel_at(5000, false), Some(0.4), "the next packet reads again"); + r.packet(packet(2, 500), None, 5010); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(2, 500) }, None, 5020); + assert_eq!(r.list.len(), 1, "a cursor that leaves drops only its own reading"); + } + + #[test] + fn wintab_messages_name_their_context() { + assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); + assert_eq!(message(WT_CSRCHANGE, 42, 0x5000), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_PROXIMITY, 0x5000, 1), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_CTXCLOSE, 0x5000, 0), Message::Closed { ctx: 0x5000 }); + assert_eq!(message(WT_INFOCHANGE, 0, 0), Message::InfoChange); + // WM_POINTERUPDATE and the context-open message. + assert_eq!(message(0x0245, 0, 0), Message::Other); + assert_eq!(message(WT_DEFBASE + 1, 0, 0), Message::Other); + } +} diff --git a/assets/icons/dc-cap-butt.svg b/assets/icons/dc-cap-butt.svg index bf39a170a6..dee85e09a0 100644 --- a/assets/icons/dc-cap-butt.svg +++ b/assets/icons/dc-cap-butt.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-cap-round.svg b/assets/icons/dc-cap-round.svg index 06af9d07ea..bcf2e976c4 100644 --- a/assets/icons/dc-cap-round.svg +++ b/assets/icons/dc-cap-round.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-cap-square.svg b/assets/icons/dc-cap-square.svg index 4a82a10d9a..5fcb2e3c5d 100644 --- a/assets/icons/dc-cap-square.svg +++ b/assets/icons/dc-cap-square.svg @@ -1 +1 @@ - + diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 31500d1ac5..ca8db5ae30 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -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]; diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 909fedd04d..b5c993a865 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -406,8 +406,10 @@ impl Document { /// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A /// line at any other angle becomes a guide path with that line, on the guide's layer, named /// as the guide was; `sel` then holds the path as a selected object instead of the guide. - /// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. - pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) { + /// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. Returns the ids + /// of the guide paths it adds, in the order it adds them. + pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) -> Vec { + let mut paths = vec![]; for id in sel.guides.clone() { let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue }; let (a, b) = match self.transformed_guide(&g, xf) { @@ -431,7 +433,9 @@ impl Document { } self.retain_guides(sel, |g| g.id != Some(id)); sel.objects.push(path); + paths.push(path); } + paths } /// The ruler guide node `g` names, if this document has it. diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..cadfb6b7a6 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -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] { 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> { + 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> { + 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 { diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index ab347529e6..d1322de74f 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -5,9 +5,10 @@ //! stay attached and deleted objects leave nothing stale behind. use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Homography, Rect}; +use vectorcraft_geom::{Homography, Point, Rect}; -use crate::{Node, NodeKind}; +use crate::symbols::SYMBOL_SQUARE; +use crate::{Node, NodeKind, SymbolBoxes}; /// The plane an object in perspective lies on. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -58,6 +59,33 @@ impl Node { } } + /// The corners of the box a symbol instance or type is drawn in, on the page (top left, top + /// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or + /// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both + /// through the projection of type or an instance in perspective. Joined by straight lines, + /// they outline the box as drawn. When the projection sends a corner to infinity the corners + /// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other + /// objects and for type without bounds. + pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> { + let flat = match &self.kind { + NodeKind::SymbolInstance { symbol, xf } => { + let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric); + [(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y)) + } + NodeKind::Text(t) => { + let b = t.bounds()?; + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y)) + } + _ => return None, + }; + let Some(h) = self.projection() else { return Some(flat) }; + let [a, b, c, d] = flat.map(|p| h.apply(p)); + Some(match (a, b, c, d) { + (Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d], + _ => flat, + }) + } + /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An /// invertible `a` that the projection cannot follow removes it, and the art is drawn flat. pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 25a2451968..073a0f2efd 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; mod area; +mod attr_ranges; mod char_style; mod composite; mod file_fonts; @@ -18,6 +19,9 @@ mod tabs_lists; mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; +pub use attr_ranges::{ + AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE, +}; use char_style::yes; pub use char_style::{ CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME, diff --git a/crates/doc/src/text/attr_ranges.rs b/crates/doc/src/text/attr_ranges.rs new file mode 100644 index 0000000000..bce0098ac2 --- /dev/null +++ b/crates/doc/src/text/attr_ranges.rs @@ -0,0 +1,215 @@ +//! The ranges the character and paragraph style commands keep each numeric attribute to, checked +//! in one place: the style commands check the attributes a call changes, and type a plug-in +//! returns has every attribute checked. + +use std::fmt; +use std::ops::RangeInclusive; + +use super::{CharStyle, JustificationOptions, ParaStyle, TabStop}; + +/// Font size ([`CharStyle::size`]), in points. +pub const FONT_SIZE: RangeInclusive = 0.1..=1296.0; +/// Leading ([`CharStyle::leading`]) other than Auto, in points. +pub const LEADING: RangeInclusive = 0.1..=5000.0; +/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent. +pub const CHAR_SCALE: RangeInclusive = 1.0..=10000.0; +/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`], +/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em. +pub const CHAR_SPACING: RangeInclusive = -1000.0..=10000.0; +/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points. +pub const MAX_BASELINE_SHIFT: f64 = 1296.0; +/// Character rotation ([`CharStyle::rotation`]), in degrees. +pub const CHAR_ROTATION: RangeInclusive = -360.0..=360.0; +/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]). +pub const CHAR_MITER_LIMIT: RangeInclusive = 1.0..=500.0; +/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points. +pub const MAX_PARA_DISTANCE: f64 = 1296.0; + +/// An attribute outside the range the style commands keep it to. +#[derive(Clone, Debug, PartialEq)] +pub struct AttrRangeError { + /// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`). + pub key: String, + /// What is wrong, naming the attribute. + pub message: String, +} + +impl fmt::Display for AttrRangeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for AttrRangeError {} + +fn out(key: &str, message: String) -> AttrRangeError { + AttrRangeError { key: key.to_string(), message } +} + +/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside). +fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> { + if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) } +} + +impl CharStyle { + /// Checks each numeric attribute `check` names, by its JSON key, against the range the + /// character style commands keep it to: size, leading, scales, tracking, kerning, baseline + /// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert + /// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the + /// variable font axes. The first attribute out of its range is the error. + pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> { + for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] { + if check(key) { + within(key, value, *range.start(), *range.end())?; + } + } + if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) { + let (lo, hi) = (LEADING.start(), LEADING.end()); + return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto"))); + } + let shift = MAX_BASELINE_SHIFT; + for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] { + if check(key) { + within(key, value, -shift, shift)?; + } + } + let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))]; + for (key, value) in spacing { + if check(key) + && let Some(value) = value + { + within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?; + } + } + if check("rotation") { + within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?; + } + for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] { + if check(key) { + within(key, value, 0.0, super::MAX_AKI)?; + } + } + if check("tsume") { + within("tsume", self.tsume, 0.0, super::MAX_TSUME)?; + } + let hi = super::MAX_DIACRITIC_POSITION; + for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] { + if check(key) { + within(key, value, -hi, hi)?; + } + } + let lines = super::WARICHU_LINES; + if check("warichuLines") && !lines.contains(&self.warichu_lines) { + return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); + } + let scale = super::WARICHU_SCALE; + for (key, value, lo, hi) in + [("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())] + { + if check(key) { + within(key, value, lo, hi)?; + } + } + if check("stroke_width") { + within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?; + } + if check("stroke_miter_limit") { + within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?; + } + if check("stroke_dash") + && let Some(dash) = &self.stroke_dash + { + for value in &dash.pattern { + within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?; + } + within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?; + } + if check("small_caps") + && let Some(value) = self.small_caps + { + within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?; + } + if check("fontAxes") + && let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite()) + { + return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number"))); + } + Ok(()) + } +} + +impl ParaStyle { + /// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its + /// field, against the range the paragraph style commands keep it to: the indents and the space + /// before and after, each Hyphenation option, each Justification option in `justification` + /// (the options as given, since reading a paragraph style brings them into range) with + /// Minimum, Desired and Maximum in order, and the number of tab stops with the position and + /// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the + /// error. + pub fn check_ranges( + &self, + justification: Option<&JustificationOptions>, + kept_tabs: &[TabStop], + check: impl Fn(&str, Option<&str>) -> bool, + ) -> Result<(), AttrRangeError> { + for (key, value) in [ + ("left_indent", self.left_indent), + ("right_indent", self.right_indent), + ("first_line_indent", self.first_line_indent), + ("space_before", self.space_before), + ("space_after", self.space_after), + ] { + if check(key, None) { + within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?; + } + } + let h = &self.hyphenation; + for (field, value, lo, hi) in [ + ("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0), + ("after_first", f64::from(h.after_first), 1.0, 15.0), + ("before_last", f64::from(h.before_last), 1.0, 15.0), + ("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0), + ("zone", h.zone, 0.0, MAX_PARA_DISTANCE), + ] { + if check("hyphenation", Some(field)) { + within(&format!("hyphenation.{field}"), value, lo, hi)?; + } + } + if let Some(j) = justification { + for (field, values, (lo, hi)) in [ + ("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING), + ("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING), + ("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING), + ] { + if !check("justification", Some(field)) { + continue; + } + let name = format!("justification.{field}"); + for value in values { + within(&name, value, lo, hi)?; + } + if !(values[0] <= values[1] && values[1] <= values[2]) { + return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); + } + } + if check("justification", Some("auto_leading")) { + let (lo, hi) = JustificationOptions::AUTO_LEADING; + within("justification.auto_leading", j.auto_leading, lo, hi)?; + } + } + if check("tabs", None) { + let max = TabStop::MAX_STOPS; + if self.tabs.len() > max.max(kept_tabs.len()) { + return Err(out("tabs", format!("at most {max} tab stops"))); + } + for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { + within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; + let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); + if stop.leader.chars().count() > max { + return Err(out("tabs.leader", format!("{label} must be at most {max} characters"))); + } + } + } + Ok(()) + } +} diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index b3cff3aa47..9371947565 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() { assert_eq!(serde_json::from_str::(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center); } +/// The default character and paragraph styles are in range, and each number outside its range, +/// one that is not a number included, is the error naming its attribute; an attribute the check +/// is not asked about is not checked. +#[test] +fn style_ranges_name_the_attribute_out_of_range() { + let all = |_: &str| true; + assert_eq!(CharStyle::default().check_ranges(all), Ok(())); + let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key); + let d = CharStyle::default(); + assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into())); + assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into())); + assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into())); + assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into())); + assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into())); + assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into())); + assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into())); + assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into())); + let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect(); + assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into())); + let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false }); + assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into())); + assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(())); + + let all = |_: &str, _: Option<&str>| true; + let p = ParaStyle::default(); + assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(())); + let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key); + assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into())); + let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }; + assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into())); + let far = TabStop { position: -1.0, ..stop.clone() }; + assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into())); + assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop"); + let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() }; + assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into())); + let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() }; + assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into())); +} + #[test] fn file_fonts_draw_type_only_while_its_text_is_the_files() { use super::file_fonts::*; diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..071d3c3b64 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec { "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})), diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b8067e91c..555610f206 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -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, diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index fed9df7811..d97c16b554 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -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 { + 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 { match catalog_index().get(id) { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 7e6028b045..6732c973f4 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -80,11 +80,28 @@ rustix = { workspace = true, features = ["std", "process"] } # (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" +# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below). +windows-native-keyring-store = "1.1" # The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } rayon = { version = "1.12", optional = true } +# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the +# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on +# Linux. All MIT OR Apache-2.0. +hmac = "0.12.1" +sha2 = { version = "0.10", default-features = false } +getrandom = "0.4" +keyring-core = "1.1" + +# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same +# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0. +[target.'cfg(target_os = "macos")'.dependencies] +apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] } + +[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies] +zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] } [dev-dependencies] # JPEG XL files for the `.jxl` open and place tests. diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 6c16893aba..135c9d964e 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index c474cfae85..12754ce6b6 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -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::>(); + 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 { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 5ab9da102c..426f374a5c 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Fill Area", [], None, - "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", + "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", has_doc, sb_copy_region ), diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 063c25f4b2..a7827e135b 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", always, contrast ), @@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re .transpose() }; let drawing; - // Selected objects that share a color but draw it differently have no one answer. - if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) { + // Selected objects that share a color but draw it differently have no one answer. While the + // active tool paints with the proxy's color, the selection does not draw it. + if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) { let item = s.appearance_item(); // Every painted object inside a selected group counts, as the proxy's color comes from all, // except hidden ones and those inside a hidden group, which draw nothing. The first shown diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 54e7a3bbf4..42ee145c94 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co /// from. → a note for each profile, and whether `d` changed. pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec, bool) { // Without a choice nothing can fail. - apply_open_policies_choosing(d, None).unwrap_or_default() + apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default() } /// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening @@ -879,10 +879,14 @@ impl ProfileQuestion { /// mismatch choice takes the place of the policy of the document's color mode, and a missing /// choice tags the document after the policies ran. A choice for the other kind of question, or /// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile -/// to assign is not a profile of that model. -pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec, bool)> { - let working = cms::working_settings(); - let question = ProfileQuestion::of(d, &working); +/// to assign is not a profile of that model. `working` is the settings snapshot the question is +/// built from and the policies are read from. +pub(crate) fn apply_open_policies_choosing( + d: &mut vectorcraft_doc::Document, + choice: Option<&ProfileChoice>, + working: &ColorSettings, +) -> Result<(Vec, bool)> { + let question = ProfileQuestion::of(d, working); let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue())); // A mismatch answer stands in for the policy of the document's color mode. let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) { @@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { } Ok(json!({"name": name, "spot": spot})) } + +#[cfg(test)] +mod tests { + use super::*; + + /// The policies come from the settings snapshot the question was built from, not from the + /// working settings as they are when the policies run. + #[test] + fn open_policies_use_the_snapshot_they_are_given() { + let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string()); + let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() }; + let mut d = vectorcraft_doc::Document::new(100.0, 100.0); + tagged(&mut d); + let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap(); + assert!(changed, "the Off policy of the snapshot takes the profile off"); + assert_eq!(d.color_profiles.rgb, None); + assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}"); + } +} diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index f29e2e3745..25d7d38321 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -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 { 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() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0c03b1ea11..5e756623f0 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 23b7a1c13f..b308f874ab 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -256,6 +256,11 @@ struct RasterOptions { dither: Option, dither_amount: Option, transparency: Option, + /// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by + /// [`RasterOptions::transparency_dither`] (other formats do not check it). + transparency_dither: Option, + /// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is. + transparency_dither_amount: Option, matte: Option, lossless: Option, lzw: Option, @@ -295,6 +300,26 @@ impl RasterOptions { } } + /// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not + /// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error. + fn transparency_dither(&self) -> Result<(Dither, u8)> { + const IDS: &str = "none, diffusion, pattern or noise"; + let method = match &self.transparency_dither { + None | Some(Value::Null) => PaletteOptions::default().transparency_dither, + Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?, + Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))), + }; + let amount = match &self.transparency_dither_amount { + None | Some(Value::Null) => 100, + Some(v) => v + .as_u64() + .filter(|n| *n <= 100) + .and_then(|n| u8::try_from(n).ok()) + .ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?, + }; + Ok((method, amount)) + } + /// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set. fn pixel_size(&self) -> Result> { let checked = |key: &str, n: f64| { @@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { { return Err(bad(C, format!("quality {q}: WebP quality is 0–100"))); } + if matches!(format, RasterFormat::Gif | RasterFormat::Png8) { + (settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?; + } check_options(format, &settings)?; // Use Artboards: one file per chosen artboard (default all); else the one chosen. let chosen = match use_artboards { diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 0272bab874..2d6e459ece 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -195,6 +195,20 @@ const TRANSPARENCY: FormatOption = FormatOption { description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)", }; +const TRANSPARENCY_DITHER: FormatOption = FormatOption { + name: "transparencyDither", + ty: "string", + default: "\"none\"", + description: "with transparency, how partly transparent pixels are split between the transparent entry and their color: none (cut at half opacity), diffusion, pattern (8×8 ordered) or noise", +}; + +const TRANSPARENCY_DITHER_AMOUNT: FormatOption = FormatOption { + name: "transparencyDitherAmount", + ty: "integer", + default: "100", + description: "the diffusion transparency dither's strength 0–100 (0 cuts at half opacity; more than 100 is refused)", +}; + const MATTE: FormatOption = FormatOption { name: "matte", ty: "string", @@ -235,6 +249,8 @@ const PALETTE_OPTIONS: &[FormatOption] = &[ DITHER, DITHER_AMOUNT, TRANSPARENCY, + TRANSPARENCY_DITHER, + TRANSPARENCY_DITHER_AMOUNT, MATTE, ]; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 250fc98f9b..2b3613984a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -884,14 +884,16 @@ impl ReadFile { if self.rest.is_none() { return Ok(()); } + // One snapshot of the working settings serves the reply and the policies. + let working = vectorcraft_color::cms::working_settings(); // The question the answer was given to, for the reply's `profileChoice`. - let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working); let answered = match (&self.choice, &question) { (Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })), _ => None, }; // A failure leaves the file waiting, unchanged. - let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?; + let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?; let Some(rest) = self.rest.take() else { return Ok(()) }; self.answered = answered; self.loaded.warnings.extend(notes); diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index e54aababec..d27166e5da 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() { } } +/// The shares of opaque pixels in the left and right halves of a 40×30 image file. +fn opaque_halves(file: &[u8]) -> [f64; 2] { + let img = craft_image_codecs::decode(file).unwrap(); + assert_eq!(img.dimensions(), (40, 30)); + let alpha: Vec = img.to_rgba8().chunks(4).map(|p| p[3]).collect(); + [0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0) +} + +/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`. +#[test] +fn palette_exports_take_the_transparency_dither() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 25})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 75})).unwrap(); + for format in ["gif", "png8"] { + let mut file = |extra: Value| { + let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra); + b64(&s.execute("document.export", &p).unwrap()) + }; + // By default the pixels under half opacity are transparent and the others opaque. + let none = file(json!({})); + assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}"); + assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}"); + assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}"); + for method in ["diffusion", "pattern", "noise"] { + let dithered = file(json!({"transparencyDither": method})); + let [left, right] = opaque_halves(&dithered); + assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file"); + // Without transparency the dither does nothing. + let opaque = file(json!({"transparencyDither": method, "transparency": false})); + assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}"); + } + let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40}))); + assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}"); + // null is the same as leaving a key out. + assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}"); + for bad in [ + json!({"transparencyDither": "spray"}), + json!({"transparencyDither": 3}), + json!({"transparencyDitherAmount": 101}), + json!({"transparencyDitherAmount": -1}), + json!({"transparencyDitherAmount": "50"}), + json!({"transparencyDitherAmount": 50.5}), + ] { + assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}"); + } + let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string(); + assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}"); + let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string(); + assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}"); + let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string(); + assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}"); + } + // Formats without a palette do not read the keys: their values are not checked, and the + // warnings name them. + for format in ["png", "jpg", "tiff"] { + for keys in [ + json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}), + json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}), + ] { + let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone())); + let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string(); + assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}"); + } + } +} + #[test] fn palette_formats_reach_export_as_and_screens() { let mut s = session(); @@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() { let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone(); assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false))); assert_eq!(f("gif")["write"], true); - for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] { + for k in + ["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"] + { assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}"); } assert_eq!(format_for_name("a.png").unwrap().id, "png"); diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 68c681b0a5..527957f234 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -172,8 +172,9 @@ fn apply_transform_moving_guides( if c[..4] == [1.0, 0.0, 0.0, 1.0] { interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?); } + let mut ids = ids; if xf != Affine::IDENTITY { - crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?; + ids.extend(crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?); } ids } else if none || (!copy && xf == Affine::IDENTITY) { @@ -181,7 +182,7 @@ fn apply_transform_moving_guides( } else { let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None }; s.edit(label, |d, sel| { - let targets = match &kept { + let mut targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the // loop below transforms only the copies. Some(k) => { @@ -231,7 +232,9 @@ fn apply_transform_moving_guides( d.edit_ruler_guide(i, |g| *g = g.moved(delta)); } } else if with_guides && !is_translation { - d.transform_ruler_guides(sel, xf); + // The guide paths are made already transformed, so they join the reply after the + // loop above. + targets.extend(d.transform_ruler_guides(sel, xf)); } Ok(targets) })? diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 13f7051223..77cdfdcb7d 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector // ---------- text ---------- /// Largest indent or paragraph spacing (points; Illustrator's limit). -const MAX_PARA: f64 = 1296.0; +const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE; /// `text.setFormat`'s `bullet` values and the bullets they pick. const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [ diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..e88f348085 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -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 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 = 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)?; } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 2859ecf1c0..525cef316a 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res /// [`transform_selected`] on the active document's selection, as one undo step `label`. A /// transform other than a move also transforms the selected ruler guides -/// ([`Document::transform_ruler_guides`]). -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { +/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds. +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result> { let sel = s.doc()?.selection.clone(); // As [`transform_selected`] tells a move apart, which moves the guides itself. let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; s.edit(label, |doc, live| { transform_selected(doc, &sel, xf, sc, interpolate)?; - if !is_translation { - doc.transform_ruler_guides(live, xf); - } - Ok(()) + Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) }) }) } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 6f8ce2256f..b93db7b8a2 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -42,7 +42,9 @@ //! //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them -//! unchanged ([`objects::decode_output_with`]). +//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds +//! among them it may change: type's runs and paragraph styles, an image's transform and opacity, +//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]). //! //! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is //! also given the parts of the active document it names in `_context.document`, whether or not @@ -53,7 +55,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Document, Effect, Node}; +use vectorcraft_doc::{Document, Effect, Node, NodeKind}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; @@ -113,6 +115,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.writes.is_empty() { + v["writes"] = json!(m.writes); + } if !m.context.is_empty() { v["context"] = json!(m.context); } @@ -377,7 +382,7 @@ impl FilterRun { fn finish(self, s: &mut Session, output: &[u8]) -> Result { let m = self.plugin.manifest(); let may = m.permissions(); - let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?; + let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?; if out.document_data.is_some() && !may.contains(&Permission::State) { return Err(not_granted(&m.name, Permission::State)); } @@ -393,18 +398,52 @@ impl FilterRun { if s.script_running() { return Err(EngineError::Busy); } - if !s.previewing && super::typing_in_progress(s) { + // Typing whose text Real-time Drawing off left out of the document isn't in what the + // plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it + // before the run is prepared). + if unapplied_typing(s) { + return Err(err(vectorcraft_plugins::Error::Output( + "typing in progress isn't in what the plug-in was given: nothing was changed".into(), + ))); + } + let data = out.document_data; + // The output applied to `now`, with the checks that refuse it. + let build = |now: &Document, objects: Vec| -> Result<(Document, Vec)> { + let mut d = now.clone(); + let before = (!may_write).then(|| d.layers.clone()); + let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?; + if before.is_some_and(|b| b != d.layers) { + return Err(not_granted(&m.name, Permission::DocWrite)); + } + // Type whose text the output changed is laid out again. + let retyped: Vec = ids + .iter() + .copied() + .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { + (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, + _ => false, + }) + .collect(); + super::typecmd::refresh_bounds_of(&mut d, &retyped); + if let Some(data) = data.clone() { + d.set_plugin_data(&m.id, data); + } + Ok((d, ids)) + }; + // Typing in progress, its text already in the document, is kept as `s.edit` keeps it once + // nothing can refuse the output, so a refused output leaves it in progress. Keeping it can + // change the document, and the output is then applied to the document as kept. + let typing = !s.previewing && super::typing_in_progress(s); + let again = typing.then(|| out.objects.clone()); + let mut now = s.doc()?.doc.clone(); + let (mut d, mut ids) = build(&now, out.objects)?; + if let Some(objects) = again { super::settle_interaction(s)?; - } - let now = s.doc()?.doc.clone(); - let mut d = (*now).clone(); - let before = (!may_write).then(|| d.layers.clone()); - let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; - if before.is_some_and(|b| b != d.layers) { - return Err(not_granted(&m.name, Permission::DocWrite)); - } - if let Some(data) = out.document_data { - d.set_plugin_data(&m.id, data); + let kept = s.doc()?.doc.clone(); + if !Arc::ptr_eq(&kept, &now) { + now = kept; + (d, ids) = build(&now, objects)?; + } } let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::>(); if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) { @@ -447,6 +486,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed"))) } +/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a +/// preview's run)? A run prepared now isn't given that text. +pub fn unapplied_typing(s: &Session) -> bool { + !s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some() +} + +/// Keeps typing in progress whose text Real-time Drawing off left out of the document +/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the +/// typed text; one prepared before it is prepared again. +pub fn keep_unapplied_typing(s: &mut Session) -> Result { + if !unapplied_typing(s) { + return Ok(false); + } + super::settle_interaction(s)?; + Ok(true) +} + /// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with @@ -464,6 +520,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; return r.run_with_calls(s); } + // Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it. + let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r }; // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -887,6 +945,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result }; return r.run_with_calls(s).map_err(failed); } + let r = match keep_unapplied_typing(s)? { + true => { + let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + FilterRun::prepare_with(s, plugin, Some(command), id, p)? + } + false => r, + }; let output = r.run().map_err(&failed)?; r.finish(s, &output).map_err(failed) } @@ -1808,18 +1873,49 @@ fn remove(s: &mut Session, p: &Value) -> Result { let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); - // Installed again, it asks again. A grant that can't be removed still approves the module, and - // so may a grants file that can't be opened or read. One that is too large or doesn't hold a - // list approves nothing and doesn't stop the removal. - let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id); - // Its settings and cache are moved aside and its grant removed before anything is deleted: when - // either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove` - // tries again. + // A module stored for an id that isn't installed (one no grant covers is skipped at startup) + // counts as removed once its file is gone. + let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id); + // An installed plug-in's stored module is deleted with its grant too, so that one that can't be + // deleted leaves the plug-in installed. Without a plug-in folder it has none. + let unstore = module || (installed && s.plugin_dir.is_some()); + // The grant the store keeps for an installed plug-in, which may differ from the one the session + // holds (an update whose module couldn't be stored): written back when its module can't be + // deleted, so that the stored module still loads at the next launch. + let kept_grant = if installed { s.stored_plugin_grant(id) } else { None }; + let module_left = std::cell::Cell::new(false); + let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default()); + // Installed again, it asks again. A grant that can't be removed may still approve the module, and + // so may a grants file that can't be opened or read, or a signed copy of the file put back when + // the generation couldn't be raised (the key store can't be reached). Without a plug-in folder + // nothing keeps a grant. The stored module is deleted next, while its settings and cache can + // still be moved back. + let forget = || { + if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() { + return false; + } + let deleted = !unstore || s.unstore_plugin(&turn, id); + if !deleted + && let Some(grant) = kept_grant.clone() + && !s.store_grant_in(&turn, id, Some(grant)) + { + log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch"); + } + module_left.set(!deleted); + deleted + }; + // Its settings and cache are moved aside, its grant removed and its stored module deleted before + // anything else is deleted: when one of them can't be done, the settings and cache are moved back, + // the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id + // names no grant and no module. let failed = if installed || stored { s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string()) - } else { + } else if vectorcraft_plugins::manifest::valid_id(id) { (!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string()) + } else { + None }; + let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e }); if let Some(e) = failed { if installed { s.attach_plugin_storage(&turn, id); @@ -1827,8 +1923,10 @@ fn remove(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other(e)); } registry::revoke(id); - s.unstore_plugin(&turn, id); - if !stored && (!installed || !registry::remove(id)) { + if !s.unstore_plugin(&turn, id) && module { + return Err(EngineError::Other(cant_delete())); + } + if !stored && !module && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } Ok(json!({"removed": id})) @@ -1860,7 +1958,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1878,7 +1976,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)", has_doc, run ), @@ -1887,7 +1985,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1905,7 +2003,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", always, remove ), diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 86c22d2776..7c271a326a 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -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> { + 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 { 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 { } fn reset(s: &mut Session, p: &Value) -> Result { - let cat = str_param(p, "category"); - if let Some(c) = cat - && !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c)) - { - return Err(bad("prefs.reset", format!("unknown category `{c}`"))); - } + let cat = text_param(p, "category", "prefs.reset")?; + let known = |c: &str| { + PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`"))) + }; + let category = cat.map(known).transpose()?; let mut next = s.prefs.clone(); next.reset(cat); s.apply_prefs(next); + if !s.prefs_resets.contains(&category) { + s.prefs_resets.push(category); + } Ok(json!({ "prefs": shown_prefs(&s.prefs) })) } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..1d3c8f7d7b 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -157,13 +157,13 @@ pub fn specs() -> Vec { "charStyle", "Character Styles", "Character", - "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt" + "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings" ); v.push(spec( "charStyle.edit", "Edit Character Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings", |s, p| edit_style(s, p, Kind::Char), true, )); @@ -636,52 +636,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); - for (key, value, lo, hi) in - [("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)] - { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) { - return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto")); - } - let shift_max = 1296.0; - for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] { - if changed(key) && !(-shift_max..=shift_max).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max))); - } - } - let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI); - for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME); - if changed(key) && !(lo..=hi).contains(&st.tsume) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; - let lo = -hi; - for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - let lines = vectorcraft_doc::text::WARICHU_LINES; - if changed("warichuLines") && !lines.contains(&st.warichu_lines) { - return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); - } - let scale = vectorcraft_doc::text::WARICHU_SCALE; - for (key, value, lo, hi) in [ - ("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP), - ("warichuScale", st.warichu_scale, *scale.start(), *scale.end()), - ] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } + st.check_ranges(changed).map_err(|e| bad(&c, e.message))?; // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") @@ -693,10 +648,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma style_paint(d, paint, key, &c)?; } } - let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD); - if changed(key) && !(lo..=hi).contains(&st.stroke_width) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } if changed("features") { style_features(&st.features, kept, &c)?; } @@ -753,85 +704,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } } -/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt), -/// as `text.setFormat` keeps them. -const PARA_DISTANCE: f64 = 1296.0; - /// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the -/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each -/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as -/// `attrs` gives them), and the number of tab stops with the position and leader of each stop -/// `kept` does not hold. A value `kept` has is not checked. +/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options +/// as `attrs` gives them. A value `kept` has is not checked. fn para_ranges(st: &ParaStyle, attrs: &Map, kept: Option<&Map>, c: &str) -> Result<()> { - let within = |key: &str, value: f64, lo: f64, hi: f64| { - if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) } - }; let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key); - let nested_changed = |key: &str, field: &str| { - changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)) + let check = |key: &str, field: Option<&str>| match field { + None => changed(key), + Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)), }; - for (key, value) in [ - ("left_indent", st.left_indent), - ("right_indent", st.right_indent), - ("first_line_indent", st.first_line_indent), - ("space_before", st.space_before), - ("space_after", st.space_after), - ] { - if changed(key) { - within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?; - } - } - let h = &st.hyphenation; - for (field, value, lo, hi) in [ - ("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0), - ("after_first", f64::from(h.after_first), 1.0, 15.0), - ("before_last", f64::from(h.before_last), 1.0, 15.0), - ("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0), - ("zone", h.zone, 0.0, PARA_DISTANCE), - ] { - if nested_changed("hyphenation", field) { - within(&format!("hyphenation.{field}"), value, lo, hi)?; - } - } // Read as given: a paragraph's attributes keep justification options in range as they load. - if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) { - let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?; - for (field, values, (lo, hi)) in [ - ("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING), - ("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING), - ("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING), - ] { - if !nested_changed("justification", field) { - continue; - } - let name = format!("justification.{field}"); - for value in values { - within(&name, value, lo, hi)?; - } - if !(values[0] <= values[1] && values[1] <= values[2]) { - return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); - } - } - if nested_changed("justification", "auto_leading") { - let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING; - within("justification.auto_leading", j.auto_leading, lo, hi)?; - } - } - if changed("tabs") { - let kept_tabs = kept_tab_stops(kept); - let max = TabStop::MAX_STOPS; - if st.tabs.len() > max.max(kept_tabs.len()) { - return Err(bad(c, format!("at most {max} tab stops"))); - } - for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { - within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; - let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); - if stop.leader.chars().count() > max { - return Err(bad(c, format!("{label} must be at most {max} characters"))); - } - } - } - Ok(()) + let given = attrs.get("justification").filter(|_| changed("justification")); + let justification: Option = + given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?; + st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message)) } /// The tab stops `kept` holds, each as it reads (a stop that does not read is left out). @@ -1204,17 +1090,22 @@ fn unused(s: &mut Session, kind: Kind) -> Result { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose +/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps, +/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose /// indents, spacing, Hyphenation or Justification options or tab stops are out of the range /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { - const RANGED: [&str; 24] = [ + const RANGED: [&str; 32] = [ "size", "h_scale", "v_scale", "leading", + "tracking", + "kerning", + "kerningBefore", "baseline_shift", + "rotation", "akiLeft", "akiRight", "tsume", @@ -1226,6 +1117,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { "warichuGap", "warichuScale", "stroke_width", + "stroke_miter_limit", + "stroke_dash", + "small_caps", + "fontAxes", "left_indent", "right_indent", "first_line_indent", diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index e8f57aa14f..c0a92a20e3 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"tsume": 100.1}), json!({"diacriticHorizontal": -1000.1}), json!({"diacriticVertical": 1000.1}), + json!({"tracking": -1000.1}), + json!({"kerning": 10000.1}), + json!({"rotation": 360.1}), + json!({"stroke_miter_limit": 0.9}), + json!({"small_caps": 200.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, "akiLeft": 0.0, "akiRight": 1000.0, "tsume": 100.0, - "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0 + "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0, + "tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0, + "stroke_miter_limit": 500.0, "small_caps": 200.0 }}), ) .unwrap(); @@ -830,8 +837,8 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } -/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is -/// out of the range `charStyle.new` takes is skipped. +/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or +/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped. #[test] fn loaded_styles_out_of_range_are_skipped() { let (mut s, _) = session_with_text("Title"); @@ -841,11 +848,17 @@ fn loaded_styles_out_of_range_are_skipped() { ("Shifted", json!({"baseline_shift": 5000.0})), ("Thick", json!({"stroke_width": -2.0})), ("Gapped", json!({"warichuGap": 500.0})), + ("Spun", json!({"rotation": 720.0})), + ("Tracked", json!({"tracking": 50000.0})), + ("Kerned", json!({"kerning": -5000.0})), + ("Before", json!({"kerningBefore": 50000.0})), + ("Mitered", json!({"stroke_miter_limit": 0.5})), ("Fine", json!({"size": 12.0, "h_scale": 50.0})), ]; let data = styles_file(&file, &[]); let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap(); - assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]})); + let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"]; + assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped})); assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]); } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..db1a641f2f 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection, use super::edit::selected_roots; use super::fileio::{absolute_path, read_file_head, write_file}; use super::textedit::set_story_text; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param}; +use super::{ + CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links, + str_param, +}; mod csv; mod library; @@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result { fn unbind(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.unbind"; - let ids = checked_ids_or_selection(s, p, C)?; + // Explicit bindings can include both a group and its children; retain every supplied ID. + let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? }; let name = defined_variable(s, p, C)?; let n = edit_variables(s, "Unbind Variable", |vars| { let mut n = 0; diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..379b8837f4 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -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, row: usize) -> Option<&'a Arc> { + pub fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { let current = self.undo.len(); match row.cmp(¤t) { std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f0d60d9a71..04461b332c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -136,6 +136,8 @@ pub struct Session { /// Set when a command that draws a shape was journaled outside saved steps /// ([`Session::take_shape_drawn`]). shape_drawn: bool, + /// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]). + prefs_resets: Vec>, /// Set when the active tool panicked (see [`guard`]); reported by the next tool event. tool_panic: Option, /// How many times switching or closing documents, or replacing the active one, has started the diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..9c137c96bd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -772,6 +772,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(open)) } +/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The +/// strings are the ones +/// +/// lists, and `Fit Artboard to artwork bounds` is the one +/// gives for Object › +/// Artboards › Fit to Artwork Bounds. +const MENU_COMMANDS: &[(&str, &str)] = &[ + ("selectall", "select.all"), + ("deselectall", "select.none"), + ("group", "object.group"), + ("ungroup", "object.ungroup"), + ("makeMask", "object.clippingMask.make"), + ("releaseMask", "object.clippingMask.release"), + ("compoundPath", "object.compoundPath.make"), + ("noCompoundPath", "object.compoundPath.release"), + ("Fit Artboard to artwork bounds", "artboard.fitToArt"), +]; + +/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names +/// ([`MENU_COMMANDS`]) on the active document, as +/// describes the method. A +/// name it does not list throws an error that names it. A menu item that is not available, with +/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does +/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error +/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does +/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims +/// the item then ([`DocState::any_art_to_fit`]). +fn app_menu_command(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the menu command is too long".into())); + } + let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else { + return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\""))); + }; + let params = { + let s = h.session.borrow(); + let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) }; + if (spec.enabled)(&s).is_err() { + return Ok(Data::Undefined); + } + match (id, s.active()) { + ("artboard.fitToArt", Some(st)) => { + let index = active_artboard(st); + if !st.any_art_to_fit(&[index]) { + return Ok(Data::Undefined); + } + json!({"index": index}) + } + _ => json!({}), + } + }; + command(h, id, ¶ms)?; + Ok(Data::Undefined) +} + // ---- Documents ---- fn docs_length(h: &Host, _: &[Data]) -> Answer { @@ -1303,6 +1359,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1317,7 +1374,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { Ok(text("PageItems")) } +fn items_to_string(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("[PageItems]")) +} + fn items_parent(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) @@ -2085,6 +2147,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, app_selection, app_set_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("executeMenuCommand", method(l, app_menu_command)), ("toString", class_text("Application")), ]); application.push(later(l, "Application", "beep")); @@ -2148,7 +2211,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), - ("toString", class_text("PageItems")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 66e2fdb67c..f6f2bd36f6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1649,24 +1649,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, /// with that file's name unless it is the run's own script. fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option>) { - let map = |m: &include::SourceMap| { - let (index, file, line, column) = m.locate(e.line, e.column); - let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) - }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file)); } + placed(host, e, realm.error_source(), realm.error_tag()) +} + +/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`] +/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name +/// unless it is the run's own script. +fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option>) { + let map = |m: &include::SourceMap| { + let (index, file, line, column) = m.locate(e.line, e.column); + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; + (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) + }; if e.line == 0 { return (e.clone(), None); } // An error in code from a source whose map is not at hand, such as code that `eval` compiled, // is given without a place. let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None); - match realm.error_source() { + match source { 0 => { let (e, index, file) = map(&host.script_map.borrow()); (e, (index > 0).then_some(file)) @@ -1683,7 +1690,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let kept = host.kept_maps.as_ref().map(|k| k.borrow()); - match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + match kept.as_ref().and_then(|k| k.get(tag)) { Some(kept) => { let (e, index, file) = map(&kept.map); let file = match &kept.script { @@ -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 { + 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()); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 170137028a..d1e51ea792 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -78,6 +78,7 @@ impl Session { depth: 0, replaying: false, shape_drawn: false, + prefs_resets: Vec::new(), tool_panic: None, tool_resets: 0, tool_set_since_reset: false, diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index a48795b910..29cd6f1bea 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -20,7 +20,10 @@ //! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional //! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins //! stored there that list permissions (id, module hash, permissions); a stored plug-in whose -//! permissions it doesn't grant is skipped with a log record, and stays in the folder. +//! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file +//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's +//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the +//! one the key store keeps for the folder, grants nothing. //! * **Plug-in settings and caches**: `storage/id-/` in the plug-in store, the id written as //! [`case_safe`] writes it, holds what a plug-in //! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a @@ -52,6 +55,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; use crate::Session; use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile}; +pub mod grant_keys; + /// Files read from one store folder, at most (the rest are ignored). pub const MAX_STORE_FILES: usize = 1000; /// The largest PDF presets file read (a preset is a few kilobytes). @@ -463,6 +468,11 @@ fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool { if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) { return true; } + #[cfg(test)] + if file == GRANTS_FILE && GRANTS_WRITE_FAILS.get() { + log::warn!("can't save {}: the test fails it", path.display()); + return false; + } let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes)); if let Err(e) = &written { log::warn!("can't save {}: {e}", path.display()); @@ -560,6 +570,9 @@ thread_local! { /// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when /// another program holds it open. pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: writing [`GRANTS_FILE`] fails on this thread and leaves the file as it was, as on a + /// full volume. + pub(crate) static GRANTS_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then /// reports a failure, as when the last flush of a copy fails. pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -810,18 +823,10 @@ impl Session { } let dir = load.dir.clone(); // The grants file is read once for this turn. `written` holds whether it names each id - // whose grant this turn removed or put back. + // whose grant this turn removed or put back. Only a signed file grants anything + // ([`signed_grants`]). let file = read_grants(&dir); - let mut grants = self.counted( - &dir, - match &file { - Ok(file) => file.grants.clone(), - Err(e) => { - log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); - BTreeMap::new() - } - }, - ); + let mut grants = self.counted(&dir, signed_grants(&dir, &file)); let mut written: BTreeMap = BTreeMap::new(); let named = |written: &BTreeMap, id: &str| { written.get(id).copied().unwrap_or_else(|| match &file { @@ -1304,9 +1309,25 @@ impl Session { /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use - /// are written back as they were, except one for `id`. A grants file that is too large, can't - /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; - /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and + /// are written back as they were, except one for `id`. The generation is raised, and the file is + /// written at the generation after the raised one with the MAC of its grants for this folder + /// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that + /// generation ([`put_grants`]). A signed file left empty is removed after raising the generation + /// ([`take_signed_grants`]). The generation is never lowered: when the file can't be written or + /// removed after the raise, the file in place grants nothing and its plug-ins ask again. A file + /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant replaces it with a file that holds that grant alone, and removing one + /// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the + /// rest unsigned. Removing a grant when there is no file, or when the file grants nothing + /// (unsigned, too large or not a list) and has no entry to take out, also raises the generation + /// when the key store holds a key ([`retire_signed_copies`]), so that a signed copy put back + /// doesn't grant it again. The generation is never read from the file; when it can't be raised, + /// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or + /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry + /// for `id` stays; a removal then reports a failure, also when the file doesn't name `id`. A + /// grants file that is too large, can't be read or doesn't hold a list is left as it is, with a + /// log record, and nothing is recorded; so is one whose new content would be larger than + /// `MAX_GRANTS_FILE`. A removal still holds for a file that is too large or doesn't hold a list + /// once the generation is raised ([`retire_signed_copies`]). The file is read and /// written in `turn`. → whether the store now holds what was asked (`false` without a folder, /// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every /// session in the process attached to the store ([`Session::ignore_stored_grant`]). @@ -1364,13 +1385,33 @@ impl Session { Ok(file) => file, Err(e) => { log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); - return false; + // A file that is too large or doesn't hold a list grants nothing and is left as it + // is, but a signed copy made before it must not grant `id` again once it is put back: + // the removal holds once no such copy can. + return grant.is_none() && !e.unread && retire_signed_copies(dir); } }; #[cfg(test)] if let Some(between) = AFTER_GRANTS_READ.take() { between(); } + match (file.trust, &grant) { + // Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for + // the session only, and one the file may still hold for `id` can't be removed. A file + // that doesn't name `id` may not be the one the kept generation was signed for, so the + // removal isn't known to hold either. + (Trust::Unknown, _) => return false, + // The file grants nothing. A new grant replaces it with a signed file that holds that + // grant alone; removing one takes its entry out and leaves the rest unsigned. + (Trust::Unsigned, Some(_)) => { + log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display()); + file.grants.clear(); + file.other.clear(); + } + (Trust::Unsigned | Trust::Signed, _) => {} + } + let signed = file.trust == Trust::Signed || grant.is_some(); + let removing = grant.is_none(); let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -1378,23 +1419,25 @@ impl Session { None => file.grants.remove(id).is_some(), } || file.other.len() != others; if !changed { - return true; + // Without a file, or with one that grants nothing, the last signed file may still be + // around as a copy at the kept generation: a removal raises the generation so that the + // copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id` + // is the latest, so every copy that does is at an earlier generation already. The new + // generation is past every one a file was signed at, so the file left in place grants + // nothing either. + return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir); } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); - if entries.is_empty() { - return take(dir, GRANTS_FILE); + if signed { + return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) }; } - // The file is read back only up to its cap: written compactly when pretty-printed is larger, - // and not at all when that is too. - let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; - match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes), - None => { - log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE)); - false - } + // An unsigned file loses an entry: the generation is raised first, so that no signed copy + // made before brings the entry back, nor the file itself when it can't be rewritten. + if raise_generation(dir).is_none() { + return false; } + if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } } /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this @@ -1408,6 +1451,19 @@ impl Session { }) } + /// The grant the attached plug-in store's signed grants file holds for the plug-in `id` (`None` + /// without a folder, and when the file grants nothing: unsigned, unreadable or without an entry + /// for `id`). + pub(crate) fn stored_plugin_grant(&self, id: &str) -> Option { + self.plugin_dir.as_deref().and_then(|dir| stored_grants(dir).remove(id)) + } + + /// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one + /// that no grant covers is skipped at startup and stays in the folder)? + pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool { + self.plugin_dir.as_deref().is_some_and(|dir| std::fs::symlink_metadata(dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)))).is_ok()) + } + /// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a /// folder, and when `turn` isn't held). pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { @@ -2049,10 +2105,16 @@ impl Storage for PluginStorage { /// What the grants file of a plug-in store holds. #[derive(Default)] struct GrantsFile { - /// The grants this version can use, by plug-in id. + /// The grants this version can use, by plug-in id. They grant something only when the file is + /// [`Trust::Signed`]. grants: BTreeMap, /// The entries it can't use (a permission it doesn't know, an invalid id), as they were. other: Vec, + /// Whether VectorCraft wrote the grants for this folder. + trust: Trust, + /// Whether there is a grants file: `false` when there is none, and the file is then empty and + /// [`Trust::Signed`]. + present: bool, } impl GrantsFile { @@ -2062,6 +2124,207 @@ impl GrantsFile { } } +/// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]). +#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] +enum Trust { + /// There is no file, or it is at the generation kept for its folder and carries the MAC of that + /// generation, its grants and its folder made with the user's key. + #[default] + Signed, + /// It doesn't: an older version wrote it, another program wrote or changed it, it was copied + /// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept + /// (its generation is not the one the key store keeps), or the key store holds no key. It grants + /// nothing. + Unsigned, + /// The key store can't be reached, so it is not known which. It grants nothing, and is left as + /// it is. + Unknown, +} + +/// The version of the grants file this version writes ([`SignedGrants::version`]). +const GRANTS_VERSION: u64 = 1; + +/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]), +/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as +/// compact JSON. +#[derive(serde::Serialize, serde::Deserialize)] +struct SignedGrants { + version: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + generation: Option, + grants: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + mac: Option, +} + +/// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it +/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft +/// writes one. +#[cfg(test)] +pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec { + let entries: Vec = serde_json::from_str(grants).unwrap_or_default(); + let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}")); + let folder = plugin_store_key(dir); + let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}")); + let canonical = serde_json::to_vec(&entries).unwrap_or_default(); + let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default(); + format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() +} + +/// Tests: the entries of the grants file `bytes`, signed or not. +#[cfg(test)] +pub(crate) fn grant_entries(bytes: &[u8]) -> Vec { + match serde_json::from_slice::(bytes) { + Ok(serde_json::Value::Array(entries)) => entries, + Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") { + Some(serde_json::Value::Array(entries)) => entries, + _ => vec![], + }, + _ => vec![], + } +} + +/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept +/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key. +/// A file at another generation, one behind or one ahead of the kept one included, is +/// [`Trust::Unsigned`]. +fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { + let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; + let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned }; + let folder = plugin_store_key(dir); + let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose()); + match kept { + Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed, + Ok(_) => Trust::Unsigned, + Err(e) => { + log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + Trust::Unknown + } + } +} + +/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when +/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the +/// key or the generation can't be had or it is too large either way. When `signed`, the generation +/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one +/// with its MAC, and the key store keeps that generation once the file is written. Every signed write +/// is then at a generation no file was signed at before, a write whose generation wasn't kept +/// included, since that one is at most one past the generation the key store kept. A file too large +/// either way is found before the raise, and then nothing changes. The kept generation only goes up: +/// when the file isn't written after the raise, the generation stays raised, so the file in place +/// grants nothing and its plug-ins ask again. When the file's generation can't be kept, the file is +/// at a generation the key store doesn't hold, so it grants nothing either. Both report a failure. +/// Call it in the store's turn ([`StoreTurn`]). +fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { + let path = dir.join(GRANTS_FILE); + let folder = plugin_store_key(dir); + if !signed { + return match grants_bytes(serde_json::to_value(entries).ok()) { + Some(bytes) => put(dir, GRANTS_FILE, &bytes), + None => { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + false + } + }; + } + let key = match grant_keys::signing_key() { + Ok(key) => key, + Err(e) => { + log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); + return false; + } + }; + // A file too large to keep is found before the raise, at the generation it would be written at + // (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place + // keeps its grants when nothing can be written. When the kept generation can't be read, the raise + // fails too. + let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX); + let mut file = + SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) }; + if grants_bytes(serde_json::to_value(&file).ok()).is_none() { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + return false; + } + let Some(raised) = raise_generation(dir) else { return false }; + let Some(next) = raised.checked_add(1) else { + log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display()); + return false; + }; + file.generation = Some(next); + file.mac = serde_json::to_vec(&file.grants).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); + let Some(bytes) = file.mac.as_ref().and_then(|_| grants_bytes(serde_json::to_value(&file).ok())) else { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + return false; + }; + put(dir, GRANTS_FILE, &bytes) && keep_generation(dir, &folder, next) +} + +/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than +/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap. +fn grants_bytes(file: Option) -> Option> { + let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; + file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) +} + +/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) → +/// whether the key store kept it; a failure is logged. +fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { + match grant_keys::set_current_generation(folder, generation) { + Ok(()) => true, + Err(e) => { + log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display()); + false + } + } +} + +/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is +/// raised first, so that no copy of the file grants anything once it is gone. The generation stays +/// raised when the file can't be removed: the file left in place then grants nothing, and its +/// plug-ins ask again. The file holds no grant but the one being removed. Nothing is removed when +/// the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). +fn take_signed_grants(dir: &Path) -> bool { + raise_generation(dir).is_some() && take(dir, GRANTS_FILE) +} + +/// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that +/// no signed copy of the file made before grants anything → the generation kept now; `None`, with a +/// log record, when the key store can't read or keep it or the generation is within two of the +/// largest 64-bit value. A signed write whose generation wasn't kept is at the generation after the +/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the +/// key store alone, never from a file, which anyone can edit, and it is never lowered again. +fn raise_generation(dir: &Path) -> Option { + let folder = plugin_store_key(dir); + let raised = grant_keys::current_generation(&folder).and_then(|generation| { + // A signed write goes one past the raised generation, so that one must fit too. + let next = generation.checked_add(3).and(generation.checked_add(2)); + let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; + grant_keys::set_current_generation(&folder, next).map(|()| next) + }); + match raised { + Ok(generation) => Some(generation), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + None + } + } +} + +/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything → +/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key, +/// and left as it is when it holds none, since no file is then signed. `false`, with a log record, +/// when the key store can't read or keep it. Call it in the store's turn ([`StoreTurn`]). +fn retire_signed_copies(dir: &Path) -> bool { + match grant_keys::current_key() { + Ok(None) => true, + Ok(Some(_)) => raise_generation(dir).is_some(), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + false + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is @@ -2072,8 +2335,10 @@ struct GrantsError { } /// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too -/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an -/// invalid id, is kept in [`GrantsFile::other`] with a log record. +/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it), +/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An +/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`] +/// with a log record. fn read_grants(dir: &Path) -> Result { let path = dir.join(GRANTS_FILE); let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) { @@ -2084,8 +2349,23 @@ fn read_grants(dir: &Path) -> Result { if bytes.len() as u64 > MAX_GRANTS_FILE { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } - let entries = serde_json::from_slice::>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?; - let mut file = GrantsFile::default(); + let not_a_list = |why: String| GrantsError { unread: false, why }; + let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned), + serde_json::Value::Object(_) => { + let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; + let trust = trust_of(dir, &signed); + (signed.grants, trust) + } + _ => return Err(not_a_list("not a list of grants".into())), + }; + if trust == Trust::Unsigned { + log::warn!( + "the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again", + path.display() + ); + } + let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { @@ -2106,11 +2386,19 @@ fn read_grants(dir: &Path) -> Result { } /// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when -/// there is no grants file, and none, with a log record, when it is too large, can't be read or -/// doesn't hold a list. +/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked +/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a +/// list. fn stored_grants(dir: &Path) -> BTreeMap { - match read_grants(dir) { - Ok(file) => file.grants, + signed_grants(dir, &read_grants(dir)) +} + +/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`] +/// read it. +fn signed_grants(dir: &Path, file: &Result) -> BTreeMap { + match file { + Ok(file) if file.trust == Trust::Signed => file.grants.clone(), + Ok(_) => BTreeMap::new(), Err(e) => { log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); BTreeMap::new() diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs new file mode 100644 index 0000000000..151cd4055d --- /dev/null +++ b/crates/engine/src/store/grant_keys.rs @@ -0,0 +1,541 @@ +//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an +//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of +//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps +//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one +//! an older version wrote, one another program wrote or changed, one copied from another folder or +//! machine) grants nothing. +//! +//! The key store also keeps a generation for each plug-in folder, raised on every signed write of +//! its grants file and never lowered, and the file carries its generation inside the MAC. A file +//! whose generation is not the one kept (an earlier copy put back over the current file, or a write +//! whose generation the key store didn't keep or that failed after the raise) grants nothing either. +//! +//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's +//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key +//! store can't be reached: a grant holds for the session only. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; + +/// The length of a key, in bytes, and of the MAC. +pub const KEY_LEN: usize = 32; + +/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`. +#[derive(Clone, PartialEq, Eq)] +pub struct GrantKey([u8; KEY_LEN]); + +impl GrantKey { + /// The key with the bytes `bytes`. + pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self { + GrantKey(bytes) + } + + /// A new key from the system's random source. + #[cfg(not(target_arch = "wasm32"))] + pub fn random() -> Result { + let mut bytes = [0u8; KEY_LEN]; + getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?; + Ok(GrantKey(bytes)) + } + + /// The browser keeps no grants file. + #[cfg(target_arch = "wasm32")] + pub fn random() -> Result { + Err(KeyStoreError("there is no key store".into())) + } +} + +impl std::fmt::Debug for GrantKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GrantKey(..)") + } +} + +/// Why a key store gave no key or didn't keep one. The message never holds key bytes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct KeyStoreError(pub String); + +/// Where the key of grants files is kept. +pub trait GrantKeyStore: Send + Sync { + /// The key kept, `None` when there is none; an error when the store can't be reached or read. + fn key(&self) -> Result, KeyStoreError>; + /// Keep `key` in place of any kept before. + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>; + /// The key kept, after making and keeping a new one when there is none. The key returned is the + /// one read back from the store, so a key another process kept first wins. + fn create_key(&self) -> Result { + if let Some(key) = self.key()? { + return Ok(key); + } + self.set_key(&GrantKey::random()?)?; + self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } + /// The generation kept for the grants file of the plug-in store whose folder is `folder` + /// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept. + fn generation(&self, folder: &Path) -> Result, KeyStoreError>; + /// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>; +} + +/// A key store in memory: the key and the generations last as long as the store. For tests and +/// embedders. +#[derive(Default)] +pub struct MemoryGrantKeys { + key: Mutex>, + generations: Mutex>, +} + +impl MemoryGrantKeys { + /// A store that holds `key`. + pub fn with_key(key: GrantKey) -> Self { + MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() } + } +} + +impl GrantKeyStore for MemoryGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone()) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); + Ok(()) + } + + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied()) + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation); + Ok(()) + } +} + +/// The key store of the process ([`set_grant_key_store`]). +static PROCESS_STORE: Mutex>> = Mutex::new(None); + +/// The one memory store of [`keep_grant_keys_in_memory`]. +static SHARED_MEMORY: LazyLock> = LazyLock::new(Arc::default); + +#[cfg(test)] +thread_local! { + /// Tests: the key store this thread uses in place of the process's. + pub(crate) static THREAD_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no +/// key store, so grants hold for the session only). +pub fn set_grant_key_store(store: Option>) { + *PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store; +} + +/// Keep the key in memory for the rest of the process, one key for every caller: grants files +/// written in the process count in it, and not in another process. For tests. +pub fn keep_grant_keys_in_memory() { + let shared: Arc = SHARED_MEMORY.clone(); + set_grant_key_store(Some(shared)); +} + +/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service +/// `org.storytold.vectorcraft.plugin-grants`. +#[cfg(not(target_arch = "wasm32"))] +pub fn use_os_grant_keys() { + set_grant_key_store(Some(Arc::new(OsGrantKeys::default()))); +} + +/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory +/// store when the process set none. +fn current_store() -> Option> { + #[cfg(test)] + if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) { + return Some(store); + } + let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone(); + #[cfg(test)] + let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc)); + store +} + +/// The key kept for grants files: `None` when there is none yet, an error when there is no key +/// store or it can't be reached. +pub(crate) fn current_key() -> Result, KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key() +} + +/// The key to sign a grants file with: the one kept, else a new one, kept first +/// ([`GrantKeyStore::create_key`]). +pub(crate) fn signing_key() -> Result { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + match store.key()? { + Some(key) => Ok(key), + None => store.create_key(), + } +} + +/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when +/// none is kept yet, an error when there is no key store or it can't be reached. +pub(crate) fn current_generation(folder: &Path) -> Result { + Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0)) +} + +/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept +/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a +/// lower one could match a file signed before. +pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + if store.generation(folder)?.is_some_and(|kept| generation < kept) { + return Err(KeyStoreError("the key store keeps a later generation".into())); + } + store.set_generation(folder, generation) +} + +/// The start of every MAC input: what it is a MAC of, and the version of the file. +#[cfg(not(target_arch = "wasm32"))] +const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0"; + +/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose +/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation +/// go in with their lengths first. +#[cfg(not(target_arch = "wasm32"))] +fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option> { + use hmac::Mac; + let mut mac = hmac::Hmac::::new_from_slice(&key.0).ok()?; + let folder = folder.as_os_str().as_encoded_bytes(); + let generation = generation.to_be_bytes(); + mac.update(DOMAIN); + mac.update(&(folder.len() as u64).to_be_bytes()); + mac.update(folder); + mac.update(&(generation.len() as u64).to_be_bytes()); + mac.update(&generation); + mac.update(grants); + Some(mac) +} + +/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option { + use hmac::Mac; + Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]), +/// compared in constant time; a shorter or longer tag is not. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool { + use hmac::Mac; + let Some(tag) = from_hex(tag) else { return false }; + mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option { + None +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool { + false +} + +/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them; +/// `None` for anything else. +#[cfg(not(target_arch = "wasm32"))] +fn from_hex(tag: &str) -> Option> { + let digits = tag.as_bytes(); + let (pairs, rest) = digits.as_chunks::<2>(); + if !rest.is_empty() || pairs.len() > KEY_LEN { + return None; + } + let digit = |d: u8| match d { + b'0'..=b'9' => Some(d - b'0'), + b'a'..=b'f' => Some(d - b'a' + 10), + _ => None, + }; + pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect() +} + +/// The system's key store, through `keyring-core` and the store crate of the platform. The key is +/// read from the store each time it is needed. The key and the generations are kept as lower-case +/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8. +#[cfg(not(target_arch = "wasm32"))] +struct OsGrantKeys { + /// Held while a key is kept, so that the threads of the process that make the first key at the + /// same time keep one. + making: Mutex<()>, + /// The connection to the system's key store, once one is made. A failed connection is not + /// kept, and a kept one is dropped when the key store can't be reached through it or fails + /// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after + /// VectorCraft, or restarts, is used. + store: Mutex>>, + /// How a connection is made ([`connect`]). + connect: fn() -> Result, keyring_core::Error>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for OsGrantKeys { + fn default() -> Self { + OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl OsGrantKeys { + const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants"; + const ACCOUNT: &str = "hmac-sha256-v1"; + + /// The system's key store: the connection made before, else a new one. + fn store(&self) -> Result, KeyStoreError> { + let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(store) = store.as_ref() { + return Ok(store.clone()); + } + Ok(store.insert((self.connect)().map_err(store_error)?).clone()) + } + + /// What the key store error `e` says ([`store_error`]). When the key store can't be reached or + /// fails, the connection is dropped first, so the next call makes a new one: the Secret Service + /// loses the session of a connection when it restarts. An entry that isn't there keeps it. + fn failed(&self, e: keyring_core::Error) -> KeyStoreError { + if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) { + *self.store.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + store_error(e) + } + + fn entry(&self, account: &str) -> Result { + self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e)) + } + + fn key_entry(&self) -> Result { + self.entry(Self::ACCOUNT) + } + + /// The key the system's key store keeps, read from it. + fn stored(&self, entry: &keyring_core::Entry) -> Result, KeyStoreError> { + match entry.get_secret() { + // A secret that is not 64 hexadecimal digits is not a key this version made: there is none. + Ok(secret) => Ok(std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok()) + .map(GrantKey)), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(e) => Err(self.failed(e)), + } + } + + /// The entry of the generation of the plug-in store whose folder is `folder`: the account + /// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits. + fn generation_entry(&self, folder: &Path) -> Result { + use sha2::Digest; + let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes()); + self.entry(&format!("generation-v1-{}", to_hex(&digest))) + } +} + +/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2 +/// uses, so entries it kept are read. +#[cfg(not(target_arch = "wasm32"))] +fn connect() -> Result, keyring_core::Error> { + #[cfg(target_os = "macos")] + { + let store: Arc = apple_native_keyring_store::keychain::Store::new()?; + Ok(store) + } + #[cfg(windows)] + { + let store: Arc = windows_native_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))] + { + let store: Arc = zbus_secret_service_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))] + Err(keyring_core::Error::NoDefaultStore) +} + +/// `bytes` as lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +fn to_hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +impl GrantKeyStore for OsGrantKeys { + /// Read from the key store each time, so that a key removed or replaced there is not used. + fn key(&self) -> Result, KeyStoreError> { + self.stored(&self.key_entry()?) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e)) + } + + /// Reads the key store again and makes the key only while holding [`creation_lock`], so that + /// processes of this user that make the first key at the same time all keep the first one made. + fn create_key(&self) -> Result { + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + let entry = self.key_entry()?; + if let Some(key) = self.stored(&entry)? { + return Ok(key); + } + let _turn = creation_lock()?; + match self.stored(&entry)? { + Some(key) => Ok(key), + None => { + entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?; + self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } + } + } + + /// Read from the key store each time, since another process on the folder may have raised it. + /// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed + /// with it. + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + match self.generation_entry(folder)?.get_secret() { + Ok(secret) => std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok()) + .map(|bytes| Some(u64::from_be_bytes(bytes))) + .ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(e) => Err(self.failed(e)), + } + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e)) + } +} + +/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is +/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary +/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file +/// can't be locked: no key is made then. +#[cfg(not(target_arch = "wasm32"))] +fn creation_lock() -> Result { + #[cfg(windows)] + let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%"); + #[cfg(target_os = "macos")] + let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR"); + #[cfg(not(any(windows, target_os = "macos")))] + let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR"); + let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); + let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?; + let file = std::fs::File::options() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(dir.join("vectorcraft-plugin-grant-key.lock")) + .map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?; + file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?; + Ok(file) +} + +/// What a key store error says, without the secret some of them hold. +#[cfg(not(target_arch = "wasm32"))] +fn store_error(e: keyring_core::Error) -> KeyStoreError { + KeyStoreError(match e { + keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), + keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"), + keyring_core::Error::NoDefaultStore => "there is no key store".into(), + _ => "the key store can't read or keep the key".into(), + }) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + use keyring_core::api::CredentialStoreApi; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Connections asked for from [`flaky`]. + static TRIES: AtomicUsize = AtomicUsize::new(0); + /// The store [`flaky`] connects to. + static MOCK: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that can't be reached on the first try and is reached on every later one. + fn flaky() -> Result, keyring_core::Error> { + if TRIES.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(keyring_core::Error::NoDefaultStore); + } + let store: Arc = MOCK.clone(); + Ok(store) + } + + /// Connections asked for from [`restarting`]. + static RESTARTS: AtomicUsize = AtomicUsize::new(0); + /// The store [`restarting`] connects to first. + static BEFORE: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + /// The store [`restarting`] connects to on every later try. + static AFTER: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that restarts after the first connection: later connections reach another store. + fn restarting() -> Result, keyring_core::Error> { + let store: Arc = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() }; + Ok(store) + } + + /// A connection that the key store can't be reached through is dropped, and the next call + /// connects again; an entry that isn't there keeps the connection. + #[test] + fn the_system_key_store_reconnects_after_it_restarts() { + let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() }; + assert_eq!(keys.key().unwrap(), None, "no key is kept yet"); + keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap(); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection"); + + AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap(); + let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap(); + let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap(); + cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into())); + assert!(keys.key().is_err(), "the connection fails"); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection"); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 2); + } + + /// The secret `MOCK` keeps for `account`, as it is kept. + fn kept(account: &str) -> Vec { + MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap() + } + + /// The system key store is connected again after a connection fails, the key and the + /// generations are kept as hexadecimal text, and the key is read from the store each time; a + /// value kept as raw bytes is not read as a key or a generation. + #[test] + fn the_system_key_store_reconnects_and_keeps_text() { + let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }; + assert!(keys.key().is_err(), "the first connection fails"); + let key = GrantKey::from_bytes([0xa7; KEY_LEN]); + keys.set_key(&key).unwrap(); + assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text"); + assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back"); + + let folder = Path::new("/plug-ins"); + keys.set_generation(folder, 0x1_0000_0005).unwrap(); + let account = format!("generation-v1-{}", to_hex(&::digest(folder.as_os_str().as_encoded_bytes()))); + assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text"); + assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005)); + + MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap(); + assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap(); + assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap(); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used"); + } +} diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 39f496557d..9b0147174e 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); } +/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the +/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no +/// error. +#[test] +fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap(); + let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let bucket = s.execute("color.contrast", &json!({})).unwrap(); + assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}"); + assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}"); + // A second selected object drawn at another opacity does not make the answer ambiguous. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let both = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}"); +} + #[test] fn a_translucent_group_counts_for_the_art_inside_it() { let mut s = session(); diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index d6e82af05b..b0b511e661 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -232,6 +232,29 @@ fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() { assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); } +/// Parts of an outline that lie on the mask's edge show: a square without a fill, clipped by a mask +/// of the same square, keeps all four sides and bounds its whole area. A square just outside the +/// mask is hidden and bounds nothing. +#[test] +fn fill_area_keeps_outline_parts_on_the_mask_edge() { + let mut s = session(); + let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 10000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + + let mut s = session(); + let square = rect(&mut s, -0.005, -0.005, 100.01, 100.01); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + /// In a clipping group inside another, clipped art shows only where both masks show it. #[test] fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() { @@ -305,6 +328,39 @@ fn fill_area_stays_inside_the_isolated_group() { assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer()); } +/// In isolation mode, `ids` naming the isolated group, or the layer or a group that holds it, takes +/// every path of the isolated group. The other paths of that layer or group, and other listed +/// objects outside the isolated group, do not bound areas. +#[test] +fn fill_area_ids_naming_what_holds_the_isolated_group_take_its_paths() { + let mut s = session(); + let outside = + [line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))]; + let lines = triangle(&mut s); + let ids: Vec = lines.iter().map(|l| l.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let outer = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + deselect(&mut s); + let layer = s.doc().unwrap().doc.default_layer().unwrap(); + let (undo, kids) = (undo_len(&s), stack(&s)); + for named in [vec![layer.0], vec![outer.0], vec![g.0], vec![layer.0, outside[0].0]] { + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named})); + assert!(r.is_err(), "the area outside the isolated group, ids {named:?}"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids.clone())); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).unwrap(); + let new = id_of(&r); + assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g), "ids {named:?}"); + assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new)); + s.execute("edit.undo", &json!({})).unwrap(); + } + let named: Vec = outside.iter().map(|l| l.0).collect(); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).is_err(), "only art outside it listed"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + /// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and /// changes nothing: the compound path cannot hold the new path. The same goes for an isolated /// Objects on Path group, a group with a Transform effect and a group that is a clipping mask. diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index d922be19dd..6f7fe9c581 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4644,6 +4644,47 @@ fn a_ruler_guide_rotates_with_the_selected_art() { assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s)); } +/// The reply to a transform lists the guide paths it makes of ruler guides: for a guide alone, +/// with a copy, beside selected art and beside direct-selected anchors. +#[test] +fn a_transform_replies_with_the_guide_paths_it_makes() { + fn reply_ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() + } + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // A copy keeps the ruler guide and adds a guide path, the only new object. + let r = s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap(); + let [copy] = selected(&s)[..] else { panic!("the copy is selected") }; + assert_eq!(reply_ids(&r), vec![copy]); + // Without a copy the guide becomes a guide path. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let [path] = selected(&s)[..] else { panic!("one guide path selected") }; + assert_ne!(path, copy); + assert_eq!(reply_ids(&r), vec![path]); + // With art selected, the reply lists the art and then the guide path. + let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + let r = s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let paths: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [mixed] = paths[..] else { panic!("the guide path is selected with the art") }; + assert_eq!(reply_ids(&r), vec![a, mixed]); + // With direct-selected anchors, the guide path joins the reply too. + s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.is_empty()); + let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let anchored: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [made] = anchored[..] else { panic!("the guide path is selected with the path") }; + assert!(line_ends(&s, made).1, "it is a guide path"); + assert!(reply_ids(&r).contains(&made), "{r}"); +} + #[test] fn ruler_guides_and_lock() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 0a255fb3a3..e47eb8377a 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2714,7 +2714,8 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap(); + let entry = + |hash: String| crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()); std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap(); let held = HeldLoad::new(later.clone()); let mut s = session(); @@ -2731,7 +2732,7 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { s.finish_plugin_loads(); let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); assert!(vectorcraft_plugins::registry::remove(id)); - let listed: Vec = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap(); + let listed = crate::store::grant_entries(&std::fs::read(&grants).unwrap()); assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed"); assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::>(), [json!(sha256_hex(&other))], "{listed:?}"); } @@ -2750,7 +2751,11 @@ fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); // The first write removes the grant; the second, which puts it back, finds a folder where the // file goes and fails. let blocked = grants.clone(); @@ -2785,7 +2790,11 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); // The first write removes the grant; while the second puts it back, the id is installed // elsewhere. crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { @@ -2800,7 +2809,14 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { assert!(vectorcraft_plugins::registry::remove(id)); // A grants file that went away holds no grant; one still there must read as a list. let listed: Vec = match std::fs::read(&grants) { - Ok(b) => serde_json::from_slice(&b).unwrap(), + Ok(b) => match serde_json::from_slice::(&b).unwrap() { + Value::Array(entries) => entries, + Value::Object(mut file) => match file.remove("grants") { + Some(Value::Array(entries)) => entries, + other => panic!("the grants file holds no list: {other:?}"), + }, + other => panic!("the grants file holds no list: {other:?}"), + }, Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![], Err(e) => panic!("the grants file could not be read: {e}"), }; @@ -3077,11 +3093,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { let other_wasm = asking(other, r#"["doc.read"]"#, &empty); let grants = folder.0.join("grants.json"); let ids = || -> Vec { - serde_json::from_slice::>(&std::fs::read(&grants).unwrap()) - .unwrap() - .iter() - .map(|e| e["id"].as_str().unwrap().to_string()) - .collect() + crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].as_str().unwrap().to_string()).collect() }; let mut s = session(); s.attach_plugin_store(folder.0.clone()); @@ -3101,7 +3113,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // A grant the store already holds for an id whose stored module lists no permissions. let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([entry, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); let mut third = session(); third.attach_plugin_store(folder.0.clone()); @@ -3111,7 +3123,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // So does an entry this version can't read, and a grant held only by the process. let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { id: id.into(), @@ -3171,8 +3183,8 @@ fn a_grant_that_cannot_be_removed_keeps_the_stored_module() { let file = s.stored_plugin_file(id).unwrap(); // An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which // makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", replace.clone()); @@ -3219,8 +3231,8 @@ fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() { run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS.set(true); @@ -3252,7 +3264,7 @@ fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]}); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); @@ -3285,8 +3297,8 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); std::fs::remove_file(&file).unwrap(); @@ -3315,13 +3327,14 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); vectorcraft_plugins::registry::remove(id); let mut next = session(); @@ -3331,12 +3344,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); assert!(refused.contains("doc.read"), "{refused}"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); next.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); // A load that can rewrite the file forgets the grant, and the store has nothing ignored again. - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); next.attach_plugin_store(folder.0.clone()); assert!(!grants.exists(), "the load removes the grant"); @@ -3346,7 +3359,7 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let mut third = session(); third.attach_plugin_store(folder.0.clone()); std::fs::remove_dir(&grants).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count"); // Attaching the same store again, with no stored module to try the removal for, keeps it out. @@ -3383,8 +3396,9 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); let mut first = session(); first.attach_plugin_store(folder.0.clone()); let inside = folder.0.join("inside"); @@ -3394,7 +3408,7 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); let file = first.stored_plugin_file(id).unwrap(); @@ -3414,13 +3428,13 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { later.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); other.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); other.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't"); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); for s in [&mut first, &mut other, &mut later] { assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); @@ -3478,7 +3492,7 @@ fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() { let mut other = session(); other.attach_plugin_store(alias); std::fs::create_dir(&dir).unwrap(); - std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(&dir, &json!([entry]).to_string())).unwrap(); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); first.ignore_stored_grant(id, first.grant_writes()); @@ -3519,11 +3533,10 @@ fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() { let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins")); for dir in [&old, &new] { std::fs::create_dir(dir).unwrap(); - std::fs::write(dir.join("grants.json"), &recorded).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(dir, &json!([entry]).to_string())).unwrap(); } std::os::unix::fs::symlink(&old, &link).unwrap(); let mut linked = session(); @@ -3590,8 +3603,8 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); std::fs::create_dir_all(&data).unwrap(); @@ -3649,8 +3662,8 @@ fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); let settings = br#"{"zoom":"aGVsbG8="}"#; @@ -3781,8 +3794,9 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { } /// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module -/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant -/// still covers, and the grant is left as it was. +/// that asks for no permissions doesn't stay in the store: the store gets back the earlier module, +/// and the file is left as it was. The generation was raised before the removal and stays raised, so +/// the file left in place grants nothing and the module asks again. #[test] fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants"); @@ -3802,8 +3816,8 @@ fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); crate::store::GRANTS_DELETE_FAILS.set(false); assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); - assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was"); - assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file stays as it was"); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the file left in place grants nothing"); run(&mut s, "plugin.remove", json!({"id": id})); assert!(!grants.exists(), "a removal that can delete the file forgets the grant"); @@ -3891,7 +3905,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() { // A malformed hash is no wildcard, even for the module on disk. let upper = sha256_hex(&first).to_uppercase(); for hash in ["", "00", upper.as_str()] { - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); assert!(!starts(), "hash {hash:?}"); } @@ -3951,11 +3969,11 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { // The grants file is full: the new grant, which is longer, doesn't fit. let cap = 1 << 20; - let mut entries: Vec = serde_json::from_slice(&recorded).unwrap(); + let mut entries: Vec = crate::store::grant_entries(&recorded); entries.push(json!({"id": "", "pad": ""})); - let room = cap - serde_json::to_vec(&entries).unwrap().len(); + let room = cap - crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()).len(); *entries.last_mut().unwrap() = json!({"id": "", "pad": "x".repeat(room)}); - let full = serde_json::to_vec(&entries).unwrap(); + let full = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()); assert_eq!(full.len(), cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", update.clone()); @@ -4195,7 +4213,7 @@ fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) { /// The ids `grants.json` in `dir` holds grants for, and the hash of each. fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap { - let entries: Vec = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap(); + let entries = crate::store::grant_entries(&std::fs::read(dir.join("grants.json")).unwrap()); entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect() } @@ -4497,8 +4515,8 @@ fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off( assert!(!disabled.is_empty()); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); @@ -4718,6 +4736,118 @@ fn read_only_kind_field_and_omission_refuse_without_undo() { assert!(e.contains("`inputs` needs `api` 2"), "{e}"); } +/// A filter at `api` 3 that lists type, images and symbol instances in `writes` changes a type +/// object's characters, an image's transform and opacity and the symbol an instance shows, as one +/// undo step that undo takes back and redo gives again, and the changes are kept when the document +/// is saved and opened. An echo records no undo step; a refused write, and a write by a filter that +/// lists the kinds in `inputs` alone, leave the document and the history as they were. +#[test] +fn a_filter_that_writes_type_images_and_instances_is_one_undo_step() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeKind, Symbol}; + use vectorcraft_geom::Affine; + let mut s = session(); + let r = rect(&mut s, 10.0, "#ff0000"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap()); + let (mut image, mut inst) = (NodeId(0), NodeId(0)); + s.edit("Set up", |d, _| { + for name in ["Sun", "Moon"] { + let art = Arc::new(Node::path(d.alloc_id(), triangle(), Appearance::default())); + d.symbols.push(Symbol { name: name.into(), art, dynamic: false }); + } + let layer = d.layers[0].id; + let im = vectorcraft_doc::ImageObject { + key: "none".into(), + width: 4, + height: 2, + xf: Affine::translate((100.0, 20.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + image = d.insert(Some(layer), usize::MAX, n).unwrap(); + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Sun".into(), xf: Affine::translate((200.0, 20.0)) }); + inst = d.insert(Some(layer), usize::MAX, n).unwrap(); + Ok(()) + }) + .unwrap(); + let manifest = |id: &str, writes: &str| { + format!( + r#"{{"id":"{id}","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"]{writes}}}"# + ) + }; + let all = r#","writes":["type","image","symbolInstance"]"#; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let p = |id: &str| json!({"id": id, "ids": [r.0, t.0, image.0, inst.0]}); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let edits = json!({"objects": [ + {"id": r.0}, + {"id": t.0, "text": {"runs": [{"text": "Bye now", "style": style}]}}, + {"id": image.0, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.25}, + {"id": inst.0, "symbolId": "Moon"}, + ]}); + let writer = "test.engine.writes.revise"; + let listed = put(&mut s, &tpl::returning(&manifest(writer, all), &edits.to_string())); + assert_eq!((&listed["api"], &listed["writes"]), (&json!(3), &json!(["type", "image", "symbolInstance"]))); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert_eq!(run(&mut s, "plugin.run", p(writer))["ids"], json!([r.0, t.0, image.0, inst.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let check = |d: &vectorcraft_doc::Document| { + let NodeKind::Text(x) = &d.node(t).unwrap().kind else { panic!("type") }; + assert_eq!(x.plain_text(), "Bye now"); + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("image") }; + assert_eq!((im.xf, d.node(image).unwrap().opacity), (Affine::new([2.0, 0.0, 0.0, 2.0, 50.0, 60.0]), 0.25)); + assert!( + matches!(&d.node(inst).unwrap().kind, NodeKind::SymbolInstance { symbol, xf } if symbol == "Moon" && *xf == Affine::translate((200.0, 20.0))) + ); + }; + let after = s.doc().unwrap().doc.clone(); + check(&after); + assert!(matches!(&after.node(t).unwrap().kind, NodeKind::Text(x) if x.cached_bounds.is_some()), "the type is laid out again"); + assert_eq!(s.doc().unwrap().selection.objects, [r, t, image, inst]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc().unwrap().doc.layers, after.layers); + check(&vectorcraft_format::load(&vectorcraft_format::save(&after, false)).unwrap()); + // An echo changes nothing and records no undo step. + let echo = "test.engine.writes.echo"; + put(&mut s, &tpl::module(&manifest(echo, all), tpl::ECHO, "", 1)); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + run(&mut s, "plugin.run", p(echo)); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "an echo records no undo step"); + // Refused writes leave the document and the history as they were, also when a valid change + // comes before the refused one. + let bad = "test.engine.writes.bad"; + let retyped = json!({"id": t.0, "text": {"runs": [{"text": "Hello again", "style": style}]}}); + for (writes, output, says) in [ + ( + all, + json!({"objects": [{"id": r.0}, retyped, {"id": image.0}, {"id": inst.0, "symbolId": "Nowhere"}]}), + format!("objects[3] (id {}).symbolId: 'Nowhere' is not a symbol in this document", inst.0), + ), + ( + all, + json!({"objects": [{"id": r.0}, {"id": t.0}, {"id": image.0, "opacity": 1.5}, {"id": inst.0}]}), + format!("objects[2] (id {}).opacity: must be a number from 0 to 1", image.0), + ), + ("", edits.clone(), format!("objects[1] (id {}): read-only field 'text.kind' changed", t.0)), + ] { + put(&mut s, &tpl::returning(&manifest(bad, writes), &output.to_string())); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p(bad)).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "{output}"); + } +} + /// The manifest of a filter at `api` 3 with id `id` that asks for the document information /// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or /// nothing). @@ -4880,6 +5010,73 @@ fn the_document_context_is_capped_and_its_rows_cost_instructions() { refused(&mut s); } +/// A filter that writes type, run while typing is in progress: the plug-in is given the typed +/// text, so an echo keeps it, with Real-time Drawing on and off. An output that is refused leaves +/// the document and the history as they were; with Real-time Drawing on the typing stays in +/// progress, and off it is kept as its own step before the plug-in is given its input. +#[test] +fn a_filter_that_writes_type_is_given_the_typing_in_progress() { + use vectorcraft_doc::NodeKind; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let manifest = |id: &str| { + format!( + r#"{{"id":"{id}","name":"Retype","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ) + }; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let plain = |s: &Session, t: NodeId| match &node(s, t).kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let typing = |real_time: bool| { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + let v = ViewInfo::default(); + let t = NodeId(run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20}))["id"].as_u64().unwrap()); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("B", v).unwrap(); + assert_eq!(plain(&s, t), if real_time { "AB" } else { "A" }, "real time {real_time}"); + (s, t) + }; + let bang = "test.engine.writes.typing.bang"; + let bad = "test.engine.writes.typing.bad"; + for real_time in [false, true] { + // The plug-in adds "!" to the text it is given: "AB" or, given only "A", "A". + let (mut s, t) = typing(real_time); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + put(&mut s, &tpl::when_given_else(&manifest(bang), tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!"))); + run(&mut s, "plugin.run", json!({"id": bang, "ids": [t.0]})); + assert_eq!(plain(&s, t), "AB!", "real time {real_time}: the plug-in is given the typed text"); + let steps = labels(&s); + assert_eq!(steps[steps.len() - 2..], ["Typing", "Retype"], "real time {real_time}"); + + let (mut s, t) = typing(real_time); + put(&mut s, &tpl::returning(&manifest(bad), &json!({"objects": [{"id": t.0, "transform": [0, 0, 0, 0, 0, 0]}]}).to_string())); + let undo = labels(&s); + let e = s.execute("plugin.run", &json!({"id": bad, "ids": [t.0]})).unwrap_err().to_string(); + assert!(e.contains("transform: flattens the object to a line or a point"), "{e}"); + assert_eq!(plain(&s, t), "AB", "real time {real_time}"); + if real_time { + assert_eq!(labels(&s), undo, "the refused output leaves the history as it was"); + assert!(s.in_interaction(), "and the typing in progress"); + } else { + assert_eq!(labels(&s)[undo.len()..], ["Typing"], "only the typing is kept"); + } + } +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or @@ -5121,7 +5318,7 @@ fn a_grant_covers_only_the_module_it_was_given_to() { // A kept grant that records no hash, or an empty one, covers no module: the stored module isn't // installed at the next start and `plugin.inspect` asks for approval. for entry in [json!({"id": id, "permissions": ["settings", "cache"]}), json!({"id": id, "hash": "", "permissions": ["settings", "cache"]})] { - std::fs::write(folder.0.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(folder.0.join("grants.json"), crate::store::signed_grants_file(&folder.0, &json!([entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::revoke(id); let mut again = session(); @@ -5152,9 +5349,9 @@ fn grants_this_version_cant_read_are_kept() { let invalid = json!({"id": "bad id/", "hash": "00", "permissions": ["doc.read"]}); let grant = json!({"id": kept, "hash": vectorcraft_plugins::permissions::sha256_hex(&kept_wasm), "permissions": ["doc.read"]}); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([future, grant, invalid])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, grant, invalid]).to_string())).unwrap(); std::fs::write(folder.0.join("kept.wasm"), &kept_wasm).unwrap(); - let entries = || serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap(); + let entries = || crate::store::grant_entries(&std::fs::read(&grants).unwrap()); let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(vectorcraft_plugins::registry::get(kept).is_some(), "the entries this version can't read don't drop the grant next to them"); @@ -5188,7 +5385,7 @@ fn grants_this_version_cant_read_are_kept() { // and left as it is when even compact would. let cap = 1 << 20; let many: Vec = (0..14_000).map(|i| json!({"id": format!("x.{i}"), "hash": "00", "permissions": ["ui.panel"]})).collect(); - let compact = serde_json::to_vec(&many).unwrap(); + let compact = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&many).unwrap()); assert!(compact.len() < cap && serde_json::to_vec_pretty(&many).unwrap().len() > cap); std::fs::write(&grants, &compact).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); @@ -5198,13 +5395,1082 @@ fn grants_this_version_cant_read_are_kept() { let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm)})); assert_eq!(inspected["needsApproval"], json!(false), "the compact file is read back"); run(&mut s, "plugin.remove", json!({"id": added})); - let full = serde_json::to_vec(&json!([{"id": "x.full", "hash": "0".repeat(cap - 100), "permissions": ["ui.panel"]}])).unwrap(); + let full = crate::store::signed_grants_file( + &folder.0, + &json!([{"id": "x.full", "hash": "0".repeat(cap - 250), "permissions": ["ui.panel"]}]).to_string(), + ); + assert!(full.len() < cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); assert_eq!(std::fs::read(&grants).unwrap(), full, "not written past the cap"); run(&mut s, "plugin.remove", json!({"id": added})); } +/// Tests: the key store `store` on this thread until the guard is dropped. +struct ThreadKeys; + +impl ThreadKeys { + fn using(store: impl crate::store::grant_keys::GrantKeyStore + 'static) -> Self { + crate::store::grant_keys::THREAD_STORE.set(Some(std::sync::Arc::new(store))); + ThreadKeys + } +} + +impl Drop for ThreadKeys { + fn drop(&mut self) { + crate::store::grant_keys::THREAD_STORE.set(None); + } +} + +/// A key store that is locked or can't be reached. +struct UnreachableKeys; + +impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } +} + +/// A memory key store the test keeps a handle on. While `file_generations_fail` is set, it fails to +/// keep the generation that the grants file in the folder is at, and keeps every other one. +struct SharedKeys { + keys: std::sync::Arc, + file_generations_fail: std::sync::Arc, +} + +impl SharedKeys { + fn new(keys: &std::sync::Arc) -> Self { + SharedKeys { keys: keys.clone(), file_generations_fail: std::sync::Arc::default() } + } +} + +impl crate::store::grant_keys::GrantKeyStore for SharedKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::key(self.keys.as_ref()) + } + + fn set_key(&self, key: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::set_key(self.keys.as_ref(), key) + } + + fn generation(&self, folder: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::generation(self.keys.as_ref(), folder) + } + + fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + if self.file_generations_fail.load(std::sync::atomic::Ordering::SeqCst) + && std::fs::read(folder.join("grants.json")).ok().and_then(|bytes| generation_of(&bytes)) == Some(generation) + { + return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into())); + } + crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation) + } +} + +/// The generation the grants file `bytes` is at. +fn generation_of(bytes: &[u8]) -> Option { + serde_json::from_slice::(bytes).ok()?["generation"].as_u64() +} + +/// The generation `keys` keeps for the plug-in store `dir`. +fn kept_generation(keys: &crate::store::grant_keys::MemoryGrantKeys, dir: &std::path::Path) -> Option { + crate::store::grant_keys::GrantKeyStore::generation(keys, &crate::store::plugin_store_key(dir)).unwrap() +} + +/// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether +/// `plugin.inspect` of `data` (its module) then asks for approval. +fn starts_from(dir: &std::path::Path, id: &str, data: &str) -> (bool, bool) { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(dir.to_path_buf()); + let asks = run(&mut next, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"] == json!(true); + (vectorcraft_plugins::registry::get(id).is_some(), asks) +} + +/// The grants file as VectorCraft wrote it keeps its grants; once it is changed outside VectorCraft +/// it grants nothing, and its plug-ins ask again: a grant given more permissions, a grant added, the +/// MAC taken out or cut short, a MAC made with another key, the file cut short, and the file copied +/// into another plug-in folder. +#[test] +fn a_grants_file_changed_outside_vectorcraft_grants_nothing() { + use crate::store::grant_keys::{GrantKey, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-signed"); + let copy = crate::tests_links::Folder::new("plugin-store-signed-copy"); + let id = "test.engine.permissions.signed"; + let added = "test.engine.permissions.signedadded"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let added_wasm = asking(added, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, added_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&added_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let added_file = folder.0.join(format!("{}.wasm", crate::store::file_stem(added))); + std::fs::write(&added_file, &added_wasm).unwrap(); + let written = std::fs::read(&grants).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file as written keeps its grant"); + + let file: Value = serde_json::from_slice(&written).unwrap(); + let with = |change: &dyn Fn(&mut Value)| { + let mut file = file.clone(); + change(&mut file); + serde_json::to_vec(&file).unwrap() + }; + // At the generation kept for the folder, so that only the MAC tells the file apart. + let generation = file["generation"].as_u64().unwrap(); + let other_key = { + let keys = MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32])); + crate::store::grant_keys::GrantKeyStore::set_generation(&keys, &crate::store::plugin_store_key(&folder.0), generation).unwrap(); + let _other = ThreadKeys::using(keys); + crate::store::signed_grants_file(&folder.0, &file["grants"].to_string()) + }; + let tag = file["mac"].as_str().unwrap().to_string(); + let changed: [(&str, Vec); 6] = [ + ("a permission added", with(&|f| f["grants"][0]["permissions"] = json!(["doc.read", "doc.write"]))), + ( + "a grant added", + with(&|f| f["grants"].as_array_mut().unwrap().push(json!({"id": added, "hash": sha256_hex(&added_wasm), "permissions": ["doc.read"]}))), + ), + ("the MAC taken out", with(&|f| _ = f.as_object_mut().unwrap().remove("mac"))), + ("the MAC cut short", with(&|f| f["mac"] = json!(tag[..32]))), + ("a MAC made with another key", other_key), + ("the file cut short", written[..written.len() - 2].to_vec()), + ]; + for (what, bytes) in changed { + std::fs::write(&grants, &bytes).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{what}"); + assert_eq!(starts_from(&folder.0, added, &added_data), (false, true), "{what}"); + assert_eq!(std::fs::read(&grants).unwrap(), bytes, "{what}: the file is left as it is"); + } + + std::fs::write(&grants, &written).unwrap(); + std::fs::write(copy.0.join("copied.wasm"), &wasm).unwrap(); + std::fs::write(copy.0.join("grants.json"), &written).unwrap(); + crate::store::grant_keys::set_current_generation(&crate::store::plugin_store_key(©.0), generation).unwrap(); + assert_eq!(starts_from(©.0, id, &data), (false, true), "copied into another folder"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file left as written keeps its grant"); + std::fs::remove_file(&added_file).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grants file in the form an older version wrote, a plain list, grants nothing. Approving a +/// plug-in again replaces it with a signed file that holds that grant alone; removing a plug-in takes +/// its entry out and leaves the rest unsigned. +#[test] +fn an_unsigned_grants_file_is_replaced_by_the_next_approval() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unsigned"); + let id = "test.engine.permissions.unsigned"; + let other = "test.engine.permissions.unsignedother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let entry = |id: &str, wasm: &[u8]| json!({"id": id, "hash": sha256_hex(wasm), "permissions": ["doc.read"]}); + let unsigned = serde_json::to_vec(&json!([entry(id, &wasm), entry(other, &other_wasm)])).unwrap(); + std::fs::write(&grants, &unsigned).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "an unsigned list grants nothing"); + assert_eq!(std::fs::read(&grants).unwrap(), unsigned, "and is left as it is"); + + // `other` isn't installed, so the removal reports it as not found after removing its entry. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.execute("plugin.remove", &json!({"id": other})).is_err()); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "the removal takes its entry out"); + assert!(std::fs::read(&grants).unwrap().starts_with(b"["), "and leaves the rest unsigned"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true)); + + std::fs::write(&grants, &unsigned).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the approval counts at the next start"); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// With no key in the key store, a signed grants file grants nothing; the next approval makes a key +/// and signs a file that holds that grant alone. +#[test] +fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() { + use crate::store::grant_keys::{GrantKey, GrantKeyStore, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-no-key"); + let id = "test.engine.permissions.nokey"; + let other = "test.engine.permissions.nokeyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let list = json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}, {"id": other, "hash": "0".repeat(64), "permissions": ["doc.read"]}]); + let signed = { + let _old = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([3; 32]))); + crate::store::signed_grants_file(&folder.0, &list.to_string()) + }; + std::fs::write(&grants, &signed).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let keys = std::sync::Arc::new(MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "no key, no grant"); + assert!(keys.key().unwrap().is_none(), "reading makes no key"); + assert_eq!(std::fs::read(&grants).unwrap(), signed, "the file is left as it is"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert!(keys.key().unwrap().is_some(), "the approval makes a key"); + let ids: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(ids, vec![json!(id)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// When the key store can't be reached, no grants file grants anything and none is written: an +/// approval holds for the session only, the stored module isn't replaced, and a grant the file may +/// hold can't be removed. +#[test] +fn an_unreachable_key_store_keeps_approvals_in_the_session() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-keys"); + let id = "test.engine.permissions.unreachable"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + + let locked = ThreadKeys::using(UnreachableKeys); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the stored grant can't be checked"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null})); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"], "replace": true})); + assert_eq!( + vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), + Some(vectorcraft_plugins::permissions::sha256_hex(&changed)), + "it runs in this session" + ); + assert_eq!(std::fs::read(&grants).unwrap(), written, "the grants file is left as it is"); + assert_eq!(std::fs::read(&module).unwrap(), wasm, "the store keeps the module its grant covers"); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert_eq!(std::fs::read(&grants).unwrap(), written); + + drop(locked); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the grant counts once the key store can be reached"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// While the key store can't be reached, removing a plug-in fails and leaves it installed when no +/// earlier signed copy of the grants file can be kept from granting it again: with the grants file +/// gone, and with a grants file that doesn't name the plug-in. Once the key store can be reached, the +/// removal raises the generation, and the copy put back grants nothing. +#[test] +fn a_removal_the_key_store_cannot_make_last_fails() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-remove"); + let id = "test.engine.permissions.unreachableremove"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let written = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + + let locked = ThreadKeys::using(UnreachableKeys); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with the grants file gone: {refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed"); + drop(locked); + run(&mut s, "plugin.remove", json!({"id": id})); + std::fs::write(&grants, &written).unwrap(); + std::fs::write(&module, &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing"); + std::fs::remove_file(&grants).unwrap(); + std::fs::remove_file(&module).unwrap(); + + let other = "test.engine.permissions.unreachableremoveother"; + let plain = vectorcraft_format::base64_encode(&asking(id, "[]", &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": plain})); + let names: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(names, vec![json!(other)], "the grants file doesn't name the plug-in"); + let locked = ThreadKeys::using(UnreachableKeys); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with a grants file that can't be checked: {refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed"); + drop(locked); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": other})); +} + +/// A stored plug-in that didn't load, because the grants file of an older version doesn't count, and +/// that keeps no settings or cache, is removed with its module and its entry, and the removal +/// reports it removed. A removal whose stored module can't be deleted fails and keeps its settings. +/// Removing an invalid id leaves the kept generation as it is. +#[test] +fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unloaded-remove"); + let id = "test.engine.permissions.unloadedremove"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write(&module, &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the unsigned list grants nothing"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id}))); + assert!(!module.exists(), "the module is removed"); + assert!(!grants.exists(), "and its entry"); + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "a second removal finds nothing"); + + // A stored module that can't be deleted (here a folder in its place), of a plug-in that keeps + // settings, fails the removal, and the settings stay for the next try. + std::fs::create_dir_all(module.join("held")).unwrap(); + let data_dir = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data_dir).unwrap(); + let setting = data_dir.join("settings.json"); + std::fs::write(&setting, b"{}").unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains("can't delete"), "{refused}"); + assert!(module.exists()); + assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back"); + std::fs::remove_dir_all(&module).unwrap(); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal deletes them"); + assert!(!data_dir.exists()); + + // An invalid id names no grant: its removal doesn't raise the generation. + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([3; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + for invalid in ["", "not an id"] { + assert!(s.execute("plugin.remove", &json!({"id": invalid})).is_err(), "{invalid:?} isn't found"); + assert_eq!(kept_generation(&keys, &folder.0), None, "{invalid:?}: the generation is left as it is"); + } + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err()); + assert_eq!(kept_generation(&keys, &folder.0), Some(2), "a valid id's removal still retires signed copies"); +} + +/// Removing an installed plug-in whose stored module can't be deleted fails, and the plug-in stays +/// installed with its settings and its stored grant; a second removal, once the module can be +/// deleted, removes it. +#[test] +fn removing_an_installed_plugin_whose_module_cant_be_deleted_keeps_it_installed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-installed-remove-held"); + let id = "test.engine.permissions.installedremoveheld"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert!(module.is_file(), "the module is stored"); + assert!(s.holds_plugin_grant(id), "and its grant"); + let stored_grant = s.stored_plugin_grant(id); + assert!(stored_grant.is_some(), "in the signed grants file"); + let data_dir = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data_dir).unwrap(); + let setting = data_dir.join("settings.json"); + std::fs::write(&setting, b"{}").unwrap(); + + // A folder in the module's place can't be deleted as a file. + std::fs::remove_file(&module).unwrap(); + std::fs::create_dir_all(module.join("held")).unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains("can't delete"), "{refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert!(module.exists()); + assert!(s.stored_plugin_grant(id) == stored_grant, "the stored grant is kept for the next launch"); + assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back"); + + std::fs::remove_dir_all(&module).unwrap(); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal removes it"); + assert!(vectorcraft_plugins::registry::get(id).is_none() && !module.exists() && !data_dir.exists()); + assert!(!s.holds_plugin_grant(id), "and its grant"); +} + +/// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same +/// key, generation, grants and folder verifies. A key's bytes are never printed. +#[test] +fn a_grants_mac_verifies_only_for_its_key_grants_and_folder() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let (key, other) = (GrantKey::from_bytes([1; 32]), GrantKey::from_bytes([2; 32])); + let folder = std::path::Path::new("/plug-ins"); + let tag = sign(&key, folder, 4, b"[]").unwrap(); + assert_eq!(tag.len(), 64); + assert!(verify(&key, folder, 4, b"[]", &tag)); + assert!(!verify(&other, folder, 4, b"[]", &tag), "another key"); + assert!(!verify(&key, std::path::Path::new("/other"), 4, b"[]", &tag), "another folder"); + assert!(!verify(&key, folder, 3, b"[]", &tag), "another generation"); + assert!(!verify(&key, folder, 4, b"[ ]", &tag), "other grants"); + assert!(!verify(&key, folder, 4, b"[]", &tag[..62]), "a MAC cut short"); + assert!(!verify(&key, folder, 4, b"[]", &tag.to_uppercase()), "upper case"); + assert!(!verify(&key, folder, 4, b"[]", "")); + assert_eq!(format!("{key:?}"), "GrantKey(..)"); +} + +/// A key store where another process keeps its key between this one's read and its write, and +/// that write does not replace it. +struct KeptFirstElsewhere { + reads: std::sync::Mutex, +} + +impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + let mut reads = self.reads.lock().unwrap(); + *reads += 1; + // signing_key and create_key each read once before the write. + Ok((*reads > 2).then(|| crate::store::grant_keys::GrantKey::from_bytes([7; 32]))) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Ok(None) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } +} + +#[test] +fn a_new_grants_key_is_the_one_the_key_store_kept() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let _keys = ThreadKeys::using(KeptFirstElsewhere { reads: std::sync::Mutex::new(0) }); + let key = crate::store::grant_keys::signing_key().unwrap(); + assert_eq!(key, GrantKey::from_bytes([7; 32]), "the key kept first signs"); + let folder = std::path::Path::new("/plug-ins"); + assert!(verify(&GrantKey::from_bytes([7; 32]), folder, 1, b"[]", &sign(&key, folder, 1, b"[]").unwrap())); +} + +/// An earlier copy of the grants file put back over the current one grants nothing: after one +/// plug-in's grant is revoked while another's stays, and after the last grant is revoked and the +/// file removed. +#[test] +fn an_earlier_grants_file_put_back_grants_nothing() { + let folder = crate::tests_links::Folder::new("plugin-store-earlier-copy"); + let id = "test.engine.permissions.earlier"; + let other = "test.engine.permissions.earlierother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + let both = std::fs::read(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": other})); + let one = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &both).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier copy grants nothing"); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the current file keeps its grant"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the last revoked grant doesn't come back"); + + // A grant revoked from a file edited outside VectorCraft doesn't come back with a signed copy + // made before the edit either. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + let mut edited: Value = serde_json::from_slice(&signed).unwrap(); + edited["mac"] = json!("0".repeat(64)); + std::fs::write(&grants, serde_json::to_vec(&edited).unwrap()).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back"); +} + +/// A grant revoked while the grants file is gone, or while another file that grants nothing (one +/// without a MAC, or one that doesn't hold a list) is in its place, doesn't come back with the last +/// signed file put back: the revoke raises the generation. A revoke that a signed file without an +/// entry for the plug-in already covers, or one while the key store holds no key, leaves the +/// generation as it is. +#[test] +fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-without-file"); + let id = "test.engine.permissions.revokedgone"; + let other = "test.engine.permissions.revokedgoneother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(other, None), "nothing to revoke in an empty folder"); + assert_eq!(kept(&folder.0), None, "without a key nothing is signed, so no generation is kept"); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + assert_eq!(kept(&folder.0), Some(3)); + assert!(s.store_grant(other, None)); + assert_eq!(kept(&folder.0), Some(3), "the signed file names no grant for it, so nothing is raised"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + + // The file is gone when the grant is revoked. + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept(&folder.0), Some(5)); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked while the file was gone doesn't come back"); + + // A file without a MAC that names no grant for it is in place. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, b"[]").unwrap(); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), b"[]", "the unsigned file is left as it is"); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over an unsigned file doesn't come back"); + + // A file that doesn't hold a list is in place: it is left as it is, and the revoke holds once it + // raises the generation. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, br#""not a list""#).unwrap(); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), br#""not a list""#, "the file is left as it is"); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back"); +} + +/// Every signed write of the grants file raises the generation by two and is at the generation after +/// that, which the key store then keeps, and the file stays signed; removing the last grant raises +/// the generation too. +#[test] +fn a_signed_grants_write_raises_the_generation_and_stays_signed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-generation"); + let id = "test.engine.permissions.generation"; + let other = "test.engine.permissions.generationother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(6), Some(6))); + run(&mut s, "plugin.remove", json!({"id": other})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(9), Some(9))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + assert_eq!(kept(&folder.0), Some(11), "removing the file raises the generation"); +} + +/// Each plug-in folder has a generation of its own. +#[test] +fn two_plugin_folders_keep_their_own_generations() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let first = crate::tests_links::Folder::new("plugin-store-generation-a"); + let second = crate::tests_links::Folder::new("plugin-store-generation-b"); + let ids = ["test.engine.permissions.foldera", "test.engine.permissions.folderaother", "test.engine.permissions.folderb"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let mut a = session(); + a.attach_plugin_store(first.0.clone()); + run(&mut a, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut a, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let mut b = session(); + b.attach_plugin_store(second.0.clone()); + run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]})); + assert_eq!((kept(&first.0), kept(&second.0)), (Some(6), Some(3))); + assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false)); + assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false)); + let (mut a, mut b) = (session(), session()); + a.attach_plugin_store(first.0.clone()); + b.attach_plugin_store(second.0.clone()); + run(&mut a, "plugin.remove", json!({"id": ids[0]})); + run(&mut a, "plugin.remove", json!({"id": ids[1]})); + run(&mut b, "plugin.remove", json!({"id": ids[2]})); +} + +/// A key store that holds a key and no generation for the folder, as one does the first time this +/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 3. +#[test] +fn a_key_without_a_generation_reads_generation_zero() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero"); + let id = "test.engine.permissions.generationzero"; + let other = "test.engine.permissions.generationzeroother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + assert_eq!(crate::store::grant_keys::current_generation(&crate::store::plugin_store_key(&folder.0)), Ok(0)); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(&grants, &file).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at generation 0 keeps its grant"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(3)); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": other})); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grant revoked while the file signed at generation 0 is gone doesn't come back with that file +/// put back: with a key kept, the revoke raises the generation from 0. +#[test] +fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([6; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero-revoke"); + let id = "test.engine.permissions.generationzerorevoke"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept_generation(&keys, &folder.0), Some(2)); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file at generation 0 grants nothing"); +} + +/// When the key store can't keep the generation of a write, the file written is one generation ahead +/// of the kept one and grants nothing, so its plug-ins ask again; so does the earlier file, since +/// the generation was raised past it before the write, and a file behind the kept generation. +#[test] +fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept"); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.generationunkept"; + let other = "test.engine.permissions.generationunkeptother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap(); + assert_eq!((generation_of(&ahead), kept), (Some(6), Some(5)), "the file is one generation ahead"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); + + std::fs::write(&grants, &written).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier file grants nothing"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 3).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 4).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); +} + +/// A revoke over a signed file whose generation wasn't kept raises the generation past the file's, +/// so the file left in place still grants nothing. +#[test] +fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-ahead"); + let id = "test.engine.permissions.revokeahead"; + let other = "test.engine.permissions.revokeaheadother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(6), Some(5))); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant("test.engine.permissions.revokeaheadnone", None)); + assert_eq!(std::fs::read(&grants).unwrap(), ahead, "the file is left as it is"); + assert_eq!(kept(&folder.0), Some(7), "the generation is past the file's"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file still grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); +} + +/// A signed write raises the generation before it writes the file, so a signed write whose generation +/// wasn't kept also leaves the earlier file granting nothing; a revoke over that earlier file put back +/// is then not at the generation of the unkept write, and a copy of that write put back after the +/// revoke grants nothing. +#[test] +fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-after-unkept"); + let ids = ["test.engine.permissions.afterunkept", "test.engine.permissions.afterunkeptother", "test.engine.permissions.afterunkeptthird"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let earlier = std::fs::read(&grants).unwrap(); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": data[2], "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let unkept = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &earlier).unwrap(); + assert_eq!(starts_from(&folder.0, ids[0], &data[0]), (false, true), "the earlier file grants nothing"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(ids[1], None)); + std::fs::write(&grants, &unkept).unwrap(); + assert_eq!(starts_from(&folder.0, ids[1], &data[1]), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, ids[2], &data[2]), (false, true), "the unkept write grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + for id in ids { + _ = s.execute("plugin.remove", &json!({"id": id})); + } +} + +/// A grant whose signed file fits the 1 MiB limit at the generation it is written at is kept, also +/// when the file would not fit with a longer generation number. +#[test] +fn a_grants_file_that_fits_at_its_generation_is_written() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-grants-fit"); + let id = "test.engine.permissions.grantsfit"; + let grant = doc_read_grant(id, &sha256_hex(b"module")); + let grants = folder.0.join("grants.json"); + // The file as it is written: compact, since pretty-printed it is larger than the limit. + let size = |pad: &str| serde_json::to_vec(&json!({"version": 1, "generation": 3, "grants": [grant, pad], "mac": "0".repeat(64)})).unwrap().len(); + let pad = "a".repeat((1 << 20) - size("")); + assert_eq!(size(&pad), 1 << 20); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([pad]).to_string())).unwrap(); + assert!(s.store_grant(id, Some(grant)), "the grant is kept"); + let written = std::fs::read(&grants).unwrap(); + assert_eq!((written.len(), generation_of(&written)), (1 << 20, Some(3))); + assert_eq!(kept_generation(&keys, &folder.0), Some(3)); +} + +/// A grants file edited to carry the largest generations doesn't stop a revoke and doesn't move the +/// generation the key store keeps near the limit, so later grants are still kept: the generation +/// comes from the key store alone. +#[test] +fn a_grants_file_at_the_largest_generations_doesnt_stop_a_revoke() { + use vectorcraft_plugins::permissions::sha256_hex; + for carried in [u64::MAX, u64::MAX - 1] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-largest-generation-{}", u64::MAX - carried)); + let id = "test.engine.permissions.largestgeneration"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let edited = |entries: Value| json!({"version": 1, "generation": carried, "grants": entries, "mac": "0".repeat(64)}).to_string(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!(kept(&folder.0), Some(3)); + + // The edited file names the grant, which the revoke takes out. + std::fs::write(&grants, edited(json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]))).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists(), "generation {carried}: the entry is taken out"); + assert_eq!(kept(&folder.0), Some(5), "generation {carried}: the kept generation is raised from its own value"); + + // The edited file names no grant for it. + std::fs::write(&grants, edited(json!([]))).unwrap(); + assert!(s.store_grant(id, None), "generation {carried}: the revoke is recorded"); + assert_eq!(kept(&folder.0), Some(7), "generation {carried}: the kept generation is raised from its own value"); + + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(10), Some(10)), "generation {carried}"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "generation {carried}: a later grant is kept"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +/// A signed write whose generation wasn't kept leaves a file one generation past the kept one. A +/// revoke raises the generation past that file too, so a copy of it put back grants nothing: a revoke +/// from a file without a MAC, one while the file is gone, one over a file that doesn't hold a list, +/// and one that removes the last grant of a signed file. +#[test] +fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() { + use vectorcraft_plugins::permissions::sha256_hex; + for path in ["unsigned", "gone", "not-a-list", "signed"] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-unkept-copy-{path}")); + let id = "test.engine.permissions.unkeptcopy"; + let other = "test.engine.permissions.unkeptcopyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let unkept = std::fs::read(&grants).unwrap(); + let before = kept(&folder.0).unwrap(); + assert_eq!(generation_of(&unkept), Some(before + 1), "{path}: the file is one generation past the kept one"); + + let other_grant = json!([{"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}]).to_string(); + match path { + "unsigned" => std::fs::write(&grants, &other_grant).unwrap(), + "gone" => std::fs::remove_file(&grants).unwrap(), + "not-a-list" => std::fs::write(&grants, br#""not a list""#).unwrap(), + _ => std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &other_grant)).unwrap(), + } + assert!(s.store_grant(other, None), "{path}"); + std::fs::write(&grants, &unkept).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "{path}: the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{path}: the copy grants nothing"); + assert_eq!(kept(&folder.0), Some(before + 2), "{path}: the generation is past the file whose generation wasn't kept"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); + _ = s.execute("plugin.remove", &json!({"id": other})); + } +} + +/// A signed write that fails after raising the generation leaves the generation raised: the file +/// left in place, signed at the generation before the raise, grants nothing and its plug-ins ask +/// again, and so does a copy of it put back after a later write. +#[test] +fn a_grants_write_that_fails_leaves_the_generation_raised() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-write-fails"); + let id = "test.engine.permissions.writefails"; + let other = "test.engine.permissions.writefailsother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let earlier = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&earlier), kept(&folder.0)), (Some(3), Some(3))); + + crate::store::GRANTS_WRITE_FAILS.set(true); + let grant = vectorcraft_plugins::permissions::Grant { + id: other.into(), + hash: vectorcraft_plugins::permissions::sha256_hex(b"module"), + permissions: vec![vectorcraft_plugins::permissions::Permission::DocRead], + }; + let written = s.store_grant(other, Some(grant)); + crate::store::GRANTS_WRITE_FAILS.set(false); + assert!(!written, "the write reports a failure"); + assert_eq!(std::fs::read(&grants).unwrap(), earlier, "the file is left as it was"); + assert_eq!(kept(&folder.0), Some(5), "the generation stays raised"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file left in place grants nothing"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(8), Some(8)), "the next write is past the raise"); + assert_eq!(starts_from(&folder.0, other, &other_data), (true, false), "the next write keeps its grant"); + std::fs::write(&grants, &earlier).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy from before the raise grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); + _ = s.execute("plugin.remove", &json!({"id": other})); +} + +/// A revoke whose signed grants file can't be removed leaves the generation raised: the grant left in +/// the file doesn't come back, and a later removal takes the file away. +#[test] +fn a_revoke_whose_grants_file_cant_be_removed_doesnt_bring_the_grant_back() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-remove-fails"); + let id = "test.engine.permissions.removefails"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let recorded = std::fs::read(&grants).unwrap(); + + crate::store::GRANTS_DELETE_FAILS.set(true); + let revoked = s.store_grant(id, None); + crate::store::GRANTS_DELETE_FAILS.set(false); + assert!(!revoked, "the removal reports a failure"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file is left as it was"); + assert_eq!(kept(&folder.0), Some(5), "the generation stays raised"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the revoked grant doesn't come back"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None), "a later removal is recorded"); + assert!(!grants.exists(), "and takes the file away"); + std::fs::write(&grants, &recorded).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); +} + +/// The key store's generation for a folder only goes up: a lower one is refused and the kept one +/// stays, while the same one and a higher one are kept. +#[test] +fn the_kept_grants_generation_is_never_lowered() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-lowered"); + let store = crate::store::plugin_store_key(&folder.0); + assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok()); + assert!(crate::store::grant_keys::set_current_generation(&store, 3).is_err(), "a lower generation is refused"); + assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(5), "the kept one stays"); + assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok(), "the same one is kept"); + assert!(crate::store::grant_keys::set_current_generation(&store, 6).is_ok()); + assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(6)); +} + +/// A kept generation within two of the largest 64-bit value isn't raised: a signed write leaves the +/// file and the generation as they are, and the file keeps its grant. Three below it, the write goes +/// to the largest value. +#[test] +fn a_kept_generation_near_the_largest_value_isnt_raised() { + use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + for (kept_before, written) in [(u64::MAX - 2, None), (u64::MAX - 3, Some(u64::MAX))] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-generation-near-max-{}", u64::MAX - kept_before)); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.nearmax"; + let other = "test.engine.permissions.nearmaxother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, kept_before).unwrap(); + let file = + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file grants"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let grant = Grant { id: other.into(), hash: sha256_hex(b"module"), permissions: vec![Permission::DocRead] }; + assert_eq!(s.store_grant(other, Some(grant)), written.is_some(), "{kept_before}"); + match written { + None => { + assert_eq!(std::fs::read(&grants).unwrap(), file, "{kept_before}: the file is left as it is"); + assert_eq!(kept_generation(&keys, &folder.0), Some(kept_before), "{kept_before}: the generation too"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file keeps its grant"); + } + Some(generation) => { + assert_eq!( + (generation_of(&std::fs::read(&grants).unwrap()), kept_generation(&keys, &folder.0)), + (Some(generation), Some(generation)) + ); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the new file keeps the grant"); + } + } + std::fs::remove_file(&grants).unwrap(); + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + } +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] @@ -6397,12 +7663,14 @@ fn deferred_move(s: &mut Session) -> NodeId { r } -/// The rectangle a run that hands back what it is given left during [`deferred_move`]: moved, with -/// the interaction ended and the move the last undo step, since the run changed nothing. +/// The rectangle an echoing run during [`deferred_move`] left: moved, with the interaction ended and +/// the move the last undo step, since the run handed the rectangle back as it was and so records +/// none. fn assert_moved_once(s: &Session, r: NodeId) { assert!(!s.in_interaction()); assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); - assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move")); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, ["Move", "Rectangle"]); } /// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 0f3e3ef459..7a339b6cbd 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -216,6 +216,24 @@ fn reset_category_and_all() { assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); } +/// `prefs.reset` records each category it reset once, `None` for every category, and a failed +/// reset records nothing. +#[test] +fn prefs_reset_records_the_categories_it_reset() { + let mut s = Session::new(); + assert!(s.take_prefs_resets().is_empty()); + s.execute("prefs.reset", &json!({"category": "general"})).unwrap(); + s.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![Some("General")]); + assert!(s.take_prefs_resets().is_empty(), "taking clears the list"); + assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); + assert!(s.execute("prefs.reset", &json!({"category": 5})).is_err()); + assert!(s.take_prefs_resets().is_empty(), "a failed reset records nothing"); + s.execute("prefs.reset", &json!({})).unwrap(); + s.execute("prefs.reset", &json!({"category": "Type"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![None, Some("Type")]); +} + /// A rectangle made into a guide path; nothing is selected after. fn guide_path(s: &mut Session, x: f64) -> NodeId { let id = square(s, x, 0.0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..43ee65ba46 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -680,9 +680,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); - for (member, message) in - [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] - { + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } @@ -1363,6 +1367,70 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let _ = std::fs::remove_file(path); } +#[test] +fn a_menu_command_runs_its_command_on_the_selection() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, "app.executeMenuCommand('ungroup'); vc.log(app.activeDocument.selection.length);"); + assert_eq!(out, vec![json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(g).is_none(), "the group is gone"); + assert!(st.doc.node(a).is_some() && st.doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + // With nothing selected the menu item does nothing and adds no undo step. + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = s.active().unwrap().doc.clone(); + log(&mut s, "app.executeMenuCommand('ungroup'); app.executeMenuCommand('releaseMask');"); + assert_eq!(undo_steps(&s), steps); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "nothing changed"); + // selectall then group makes one group of both rectangles. + let out = log(&mut s, "app.executeMenuCommand('selectall'); app.executeMenuCommand('group'); vc.log(app.activeDocument.selection[0].typename);"); + assert_eq!(out, vec![json!("GroupItem")]); +} + +#[test] +fn the_fit_to_artwork_menu_command_fits_the_artboard_to_the_art() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.artboards[0].rect; + log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds');"); + let after = s.active().unwrap().doc.artboards[0].rect; + assert!(after.width() < before.width() && after.height() < before.height(), "{before:?} -> {after:?}"); + // An artboard that is locked, or has no art on it, leaves the menu item dimmed: it does nothing. + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, before); + assert_eq!(undo_steps(&s), steps, "locked"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let empty = s.active().unwrap().doc.artboards[0].rect; + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, empty); + assert_eq!(undo_steps(&s), 0, "no art"); +} + +#[test] +fn an_unknown_menu_command_throws_and_names_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');"); + assert!(e.contains("acmeNoSuchMenu"), "{e}"); + assert!(failure(&mut s, "app.executeMenuCommand('Ungroup');").contains("Ungroup"), "names are matched exactly"); + assert!(failure(&mut s, "app.executeMenuCommand(5);").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand();").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand(new Array(5000).join('a'));").contains("too long")); + assert_eq!(undo_steps(&s), steps, "nothing changed"); + // With no document open a known menu item does nothing, and an unknown one still throws. + let mut s = Session::new(); + assert_eq!(log(&mut s, "app.executeMenuCommand('selectall'); vc.log(app.documents.length);"), vec![json!(0)]); + assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu")); +} + #[test] fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 78b0065b46..1b41d992fd 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -692,3 +692,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() { } let _ = std::fs::remove_dir_all(base); } + +#[test] +fn a_js_script_has_promise_and_a_jsx_script_does_not() { + let base = folder("promise-realm"); + let main = base.join("main/main.js"); + write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);"); + let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["function", 1, 2])); + assert!(r.get("unhandledRejections").is_none(), "{r}"); + let r = run(&base, "vc.log(typeof Promise);").unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() { + let base = folder("promise-engine"); + let jsx = base.join("main/a.jsx"); + let js = base.join("main/b.js"); + let mut s = Session::new(); + let mut go = |path: &Path, text: &str| { + write(path, text); + s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone() + }; + assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"])); + assert_eq!( + go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"), + json!([1, "function", 2]) + ); + assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() { + let base = folder("promise-rejections"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n"); + let main = base.join("main/main.js"); + write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n"); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + let got: Vec<(String, u64, Option)> = r["unhandledRejections"] + .as_array() + .unwrap() + .iter() + .map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc")))) + .collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}"); + assert_eq!(r["unhandledRejectionCount"], 2); + let c = s.execute("script.console", &json!({})).unwrap(); + let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect(); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}"); + assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0d766e238a..c12653602f 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 933ed15874..7a28a84ec7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -267,6 +267,25 @@ fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() { assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); } +/// A shared Liquify brush size set through another Liquify tool during a held press survives the +/// dropped press, also when the set value equals the size the press's drag has made current. +#[test] +fn a_shared_option_set_through_another_tool_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "warp"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + let before = s.tool_options()["width"].as_f64().unwrap(); + // The press's own change to the shared size, not stored. + s.tool.set_option("width", &json!(before + 40.0)); + let current = s.tool_options()["width"].clone(); + s.set_tool_option_cmd(&json!({"tool": "pucker", "key": "width", "value": before + 40.0})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["width"], current, "the tool keeps the size set through the other tool"); + assert_eq!(s.prefs.tool_settings["liquify"]["width"], current, "and stores it"); +} + /// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with /// the next click. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 222657ac1c..be4615bb43 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -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"; diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index cb364167a2..fb30bf3c5c 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -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, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{cmd} {params}: {e}"); + let checked = s.check_params(cmd, ¶ms).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", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + s.execute("effect.setParams", ¶ms).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] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 25067f5c0e..07389dc866 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -82,8 +82,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection selection= toString typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ + getIsFileOpen selection selection= toString typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs index 7a323390c9..488c094c63 100644 --- a/crates/engine/tests/plugin_clear_cache.rs +++ b/crates/engine/tests/plugin_clear_cache.rs @@ -39,6 +39,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() { let _ = std::fs::remove_dir_all(&folder); std::fs::create_dir_all(&folder).unwrap(); let ids = ["test.clearcache.a", "test.clearcache.b"]; + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 33bc8bc299..911b39de34 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1011,6 +1011,7 @@ proptest! { let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id()))); let _ = std::fs::remove_dir_all(&store.0); let folder = store.0.clone(); + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.attach_plugin_store(folder.clone()); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 9e23624a31..03bef1ea28 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -59,11 +59,13 @@ fn installed(id: &str) -> bool { vectorcraft_plugins::registry::get(id).is_some() } -/// A new launch: nothing installed, the plug-in folder `dir` attached. +/// A new launch: nothing installed, the plug-in folder `dir` attached, its grants' key kept in +/// memory. fn launch(dir: &std::path::Path) -> Session { for p in vectorcraft_plugins::registry::list() { vectorcraft_plugins::registry::remove(p.id()); } + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.attach_plugin_store(dir.to_path_buf()); s diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 31414bb517..86b31414b3 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -1,8 +1,8 @@ //! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the //! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`, //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex -//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with -//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in +//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and +//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in //! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and //! the iterators of arrays, strings and `arguments` objects (in `iterator`). //! @@ -17,6 +17,7 @@ pub(crate) mod iterator; mod json; mod math; mod object; +pub(crate) mod promise; mod symbol; use std::rc::Rc; @@ -242,6 +243,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, function_proto, "bind", function_bind, 1)?; method(interp, function_proto, "toString", function_to_string, 0)?; + let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?; + constructor(interp, "Boolean", boolean, boolean_proto)?; method(interp, boolean_proto, "toString", boolean_to_string, 0)?; method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?; @@ -262,6 +265,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + promise::install(interp)?; + } Ok(()) } @@ -516,6 +522,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Ok(Value::str(&format!("[object {class}]"))) } +/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2). +fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + let b = args.first().is_some_and(Value::truthy); + if !construct { + return Ok(Value::Bool(b)); + } + let proto = interp.intrinsics.boolean_proto; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto))))) +} + /// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a /// primitive, or the primitive value of a Boolean object. fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult { diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs new file mode 100644 index 0000000000..ab2c480c4b --- /dev/null +++ b/crates/js/src/builtins/promise.rs @@ -0,0 +1,1209 @@ +//! `Promise` (ECMA-262 11th edition, section 25.6, ) +//! and the run's queue of promise jobs (section 8.4), in realms with [`crate::Options::es2015`]: +//! the constructor, `then`, `catch` and `finally`, and `Promise.resolve`, `reject`, `all`, +//! `allSettled` and `race`. `Promise.any` (ES2021) is not provided. +//! +//! A job is queued when a promise settles with reactions waiting, when `then` is called on a +//! settled promise, and when a promise is resolved with a thenable. Jobs run one at a time, in the +//! order they were queued, once the script's own code has ended and no other code runs: at the end +//! of [`crate::Realm::run`], and in the slices [`crate::Realm::advance`] runs after the script's +//! code, before it reports the run done. A job that a job queues joins the end of the queue. A job +//! takes a unit of fuel, its callback runs on the run's fuel, heap and frame limits, and a callback +//! written in JavaScript runs as the script's own code, so a slice can pause inside it. Each queued +//! job counts [`JOB_BYTES`] toward the heap limit, and more than [`MAX_JOBS`] queued jobs end the +//! run with [`LimitKind::Jobs`]. A run that ends with an error or a limit, or is ended, drops the +//! jobs still queued. A promise that is still pending when the queue is empty stays pending. +//! +//! A promise rejected while it has no handler is noted (HostPromiseRejectionTracker, section +//! 25.6.1.9); one that still has none when the run ends successfully is reported by +//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. +//! +//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object +//! whose `length` is a whole number by index, and a string by code point; other values reject the +//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the +//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` +//! are not read. + +use std::collections::VecDeque; +use std::rc::Rc; + +use super::{arg, constructor, create_at, method, native, new_array}; +use crate::LimitKind; +use crate::bytecode::Code; +use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::string_builtins::flat_charged; +use crate::value::Value; + +/// Where a promise was rejected: the code and the instruction. +pub(crate) type Site = (Rc, usize); + +/// The estimated bytes of a promise's state, without its reactions. +pub(crate) const PROMISE_BYTES: usize = 64; +/// The estimated bytes of a reaction a pending promise holds. +pub(crate) const REACTION_BYTES: usize = 48; +/// The estimated bytes of the state a promise operation's functions share. +pub(crate) const RECORD_BYTES: usize = 48; +/// The estimated bytes of a queued job. +pub(crate) const JOB_BYTES: usize = 64; +/// The most jobs the queue may hold at once. +pub(crate) const MAX_JOBS: usize = 1 << 20; +/// The most unhandled rejections a run reports one by one. +pub(crate) const MAX_REPORTED: usize = 20; +/// The most characters of a rejection's reason a report gives. +const MAX_REASON_CHARS: usize = 500; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum State { + Pending, + Fulfilled, + Rejected, +} + +/// A `then` waiting for a pending promise: the handlers (`undefined` when not callable) and the +/// promise `then` returned. +#[derive(Clone)] +pub(crate) struct Reaction { + on_fulfilled: Value, + on_rejected: Value, + derived: ObjId, +} + +/// A promise's internal slots (section 25.6.6), with where it was rejected. +#[derive(Clone)] +pub(crate) struct PromiseData { + pub(crate) state: State, + pub(crate) result: Value, + reactions: Vec, + pub(crate) handled: bool, + pub(crate) site: Option, +} + +impl PromiseData { + fn new() -> Self { + Self { state: State::Pending, result: Value::Undefined, reactions: Vec::new(), handled: false, site: None } + } + + /// The values the promise holds, for the collector. + pub(crate) fn values(&self) -> Vec { + let mut out = vec![self.result.clone()]; + for r in &self.reactions { + out.extend([r.on_fulfilled.clone(), r.on_rejected.clone(), Value::Object(r.derived)]); + } + out + } + + /// The estimated bytes of the state, beyond the object. + pub(crate) fn bytes(&self) -> usize { + PROMISE_BYTES + REACTION_BYTES * self.reactions.len() + } +} + +/// The state the functions a promise operation makes share. +#[derive(Clone)] +pub(crate) enum Record { + /// A promise's resolve and reject functions (section 25.6.1.3): the first call wins. + Resolving { promise: ObjId, done: bool }, + /// `Promise.all` and `allSettled`: the result's resolving record, the values so far and the + /// inputs not yet settled. + Combinator { resolving: ObjId, values: ObjId, remaining: u64 }, + /// The functions for one input of `Promise.all` or `allSettled`. + Element { combinator: ObjId, index: u32, called: bool }, + /// `finally`'s callback. + Finally { on_finally: Value }, + /// A value `finally` passes on or throws again. + Thunk { value: Value }, +} + +impl Record { + /// The values the record holds, for the collector. + pub(crate) fn values(&self) -> Vec { + match self { + Record::Resolving { promise, .. } => vec![Value::Object(*promise)], + Record::Combinator { resolving, values, .. } => vec![Value::Object(*resolving), Value::Object(*values)], + Record::Element { combinator, .. } => vec![Value::Object(*combinator)], + Record::Finally { on_finally: v } | Record::Thunk { value: v } => vec![v.clone()], + } + } +} + +/// A queued job. +enum Job { + /// PromiseReactionJob (section 25.6.2.1): calls `handler` with `argument` and settles + /// `derived` with the result, or passes `argument` on when `handler` is not callable. + Reaction { handler: Value, argument: Value, reject: bool, derived: ObjId, site: Option }, + /// PromiseResolveThenableJob (section 25.6.2.2): calls `then` on `thenable` with new + /// resolving functions for `promise`. + Thenable { promise: ObjId, thenable: Value, then: Value }, +} + +/// What happens when the running job's call ends. +enum Then { + /// The result resolves this promise, and an exception rejects it. + Settle(ObjId, Option), + /// An exception rejects through this resolving record. + Reject(ObjId), + /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or + /// Catch Finally function: `derived` is settled as that function's result settles it. + Finally { derived: ObjId, value: Value, throws: bool }, +} + +/// The built-in functions a promise operation's functions call, with their record. +#[derive(Clone, Copy)] +enum Kind { + Resolve, + Reject, + AllElement, + SettledFulfilled, + SettledRejected, + ThenFinally, + CatchFinally, + ValueThunk, + Thrower, +} + +const KINDS: [(Kind, NativeFn); 9] = [ + (Kind::Resolve, resolve_function), + (Kind::Reject, reject_function), + (Kind::AllElement, all_element), + (Kind::SettledFulfilled, settled_fulfilled), + (Kind::SettledRejected, settled_rejected), + (Kind::ThenFinally, then_finally), + (Kind::CatchFinally, catch_finally), + (Kind::ValueThunk, value_thunk), + (Kind::Thrower, thrower), +]; + +/// `Promise`'s objects and the run's job queue. +pub(crate) struct Promises { + proto: Option, + ctor: Option, + /// The built-ins for each [`Kind`], in [`KINDS`] order. + natives: Vec, + queue: VecDeque, + running: Option, + /// The script's completion value while the jobs after it run. + completion: Option, + /// The script's own code has ended and the queue's jobs are running. + pub(crate) draining: bool, + /// Promises rejected in this run while they had no handler. + rejected: Vec, + /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). + pub(crate) max_jobs: usize, +} + +impl Default for Promises { + fn default() -> Self { + Self { + proto: None, + ctor: None, + natives: Vec::new(), + queue: VecDeque::new(), + running: None, + completion: None, + draining: false, + rejected: Vec::new(), + max_jobs: MAX_JOBS, + } + } +} + +impl Promises { + /// Adds what the queue and the promise objects hold to the collector's roots. + pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { + roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.values.extend(self.completion.iter()); + match &self.running { + Some(Then::Settle(o, site)) => { + roots.objects.push(*o); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Some(Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Finally { derived, value, .. }) => { + roots.objects.push(*derived); + roots.values.push(value); + } + None => {} + } + for job in &self.queue { + match job { + Job::Reaction { handler, argument, derived, site, .. } => { + roots.values.extend([handler, argument]); + roots.objects.push(*derived); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Job::Thenable { promise, thenable, then } => { + roots.values.extend([thenable, then]); + roots.objects.push(*promise); + } + } + } + } + + /// The estimated bytes the queued jobs hold. + pub(crate) fn queue_bytes(&self) -> usize { + JOB_BYTES.saturating_mul(self.queue.len()) + } + + /// How many jobs are queued, and how many the queue's buffer has room for. + #[cfg(test)] + pub(crate) fn queue_size(&self) -> (usize, usize) { + (self.queue.len(), self.queue.capacity()) + } + + /// Drops the noted rejections whose promise has a handler now. + pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { + self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); + } +} + +/// Creates `Promise`, its prototype methods and its statics. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.promises.proto = Some(proto); + let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; + interp.promises.ctor = Some(ctor); + constructor(interp, "Promise", ctor, proto)?; + method(interp, proto, "then", promise_then, 2)?; + method(interp, proto, "catch", promise_catch, 1)?; + method(interp, proto, "finally", promise_finally, 1)?; + method(interp, ctor, "resolve", promise_resolve_static, 1)?; + method(interp, ctor, "reject", promise_reject_static, 1)?; + method(interp, ctor, "all", promise_all, 1)?; + method(interp, ctor, "allSettled", promise_all_settled, 1)?; + method(interp, ctor, "race", promise_race, 1)?; + for (_, f) in KINDS { + let n = native(interp, "", f, 1, NativeKind::Plain, false)?; + interp.promises.natives.push(n); + } + Ok(()) +} + +/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global +/// `Promise` an earlier script defined, and leaves the language the realm's runs read as it is. A +/// realm that has the built-in `Promise` already keeps it. When `Promise` cannot be created, every +/// later run of the realm ends with an internal error, as for a realm whose built-ins could not be +/// installed. +pub(crate) fn add_to(interp: &mut Interp) { + if interp.promises.ctor.is_some() || interp.install_error.is_some() { + return; + } + if let Err(e) = install(interp) { + let reason = match e { + Abrupt::Throw(v) => interp.describe(&v), + Abrupt::Limit(kind) => format!("limit reached: {kind:?}"), + Abrupt::Internal(message) => message, + }; + interp.install_error = Some(format!("the built-ins could not be installed: {reason}")); + } +} + +// ---- helpers ---- + +/// Runs `f`, then drops the temporary roots it added. +fn scoped(interp: &mut Interp, f: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let mark = interp.temp_roots.len(); + let r = f(interp); + interp.temp_roots.truncate(mark); + r +} + +fn root(interp: &mut Interp, v: &Value) { + interp.temp_roots.push(v.clone()); +} + +/// An exception that a promise operation turns into a rejection: it is no longer propagating, and +/// the place it was thrown at, when known, is the rejection's. +fn caught(interp: &mut Interp) -> Option { + interp.passing = Value::Undefined; + interp.thrown_mark = None; + interp.throw_site.take() +} + +/// The instruction the innermost script frame is running. +fn here(interp: &Interp) -> Option { + interp.frames.last().map(|f| (f.code.clone(), f.pc.saturating_sub(1))) +} + +/// The value an error of type `t` with `message` is. +fn error_value(interp: &mut Interp, t: ErrorType, message: &str) -> Value { + match interp.throw(t, message) { + Abrupt::Throw(v) => v, + _ => Value::Undefined, + } +} + +fn promise_data(interp: &mut Interp, p: ObjId) -> JsResult<&mut PromiseData> { + match interp.heap.object_mut(p).map(|o| &mut o.class) { + Some(Class::Promise(d)) => Ok(d), + _ => Err(Abrupt::Internal("a promise operation lost its promise".into())), + } +} + +fn record<'a>(interp: &'a mut Interp, r: &Value) -> JsResult<&'a mut Record> { + match r.as_object().and_then(|o| interp.heap.object_mut(o)).map(|o| &mut o.class) { + Some(Class::PromiseRecord(rec)) => Ok(rec), + _ => Err(Abrupt::Internal("a promise function lost its record".into())), + } +} + +fn is_promise(interp: &Interp, v: &Value) -> bool { + v.as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Promise(_))) +} + +/// `this` for a `Promise.prototype` method that needs a promise. +fn this_promise(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if is_promise(interp, this) => Ok(o), + _ => Err(interp.type_error(&format!("Promise.prototype.{name} was called on a value that is not a promise"))), + } +} + +/// Invoke (section 7.3.18): calls `v[name]` with `v` as `this`. +fn invoke(interp: &mut Interp, v: &Value, name: &str, args: &[Value]) -> JsResult { + let f = interp.get_value(v, &key(name))?; + if !interp.is_callable(&f) { + return Err(interp.type_error(&format!("{name} is not a function"))); + } + interp.call(&f, v, args) +} + +/// A new pending promise. +fn new_promise(interp: &mut Interp) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + PROMISE_BYTES)?; + let proto = interp.promises.proto; + let o = interp.heap.alloc_object(Object::new(Class::Promise(Box::new(PromiseData::new())), proto)); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROMISE_BYTES); + Ok(o) +} + +/// A new record. The values it holds must be rooted. +fn new_record(interp: &mut Interp, rec: Record) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + RECORD_BYTES)?; + let o = interp.heap.alloc_object(Object::new(Class::PromiseRecord(Box::new(rec)), None)); + interp.heap.bytes = interp.heap.bytes.saturating_add(RECORD_BYTES); + Ok(o) +} + +/// A function that calls the built-in for `kind` with `rec` before its own arguments. `rec` must +/// be rooted. +fn record_function(interp: &mut Interp, kind: Kind, rec: ObjId, length: u32) -> JsResult { + let Some(&target) = interp.promises.natives.get(kind as usize) else { return Err(Abrupt::Internal("Promise is not installed".into())) }; + interp.reserve_heap(OBJECT_BYTES + PROP_BYTES + BOUND_ARG_BYTES + 16)?; + let proto = interp.intrinsics.function_proto; + let args: Rc<[Value]> = Rc::from([Value::Object(rec)]); + let f = interp.heap.alloc_object(Object::new(Class::Function(Func::Bound { target, this: Value::Undefined, args }), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES); + interp.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + Ok(Value::Object(f)) +} + +/// CreateResolvingFunctions (section 25.6.1.3): the shared record, the resolve function and the +/// reject function. `promise` must be rooted. +fn resolving_functions(interp: &mut Interp, promise: ObjId) -> JsResult<(ObjId, Value, Value)> { + scoped(interp, |interp| { + let rec = new_record(interp, Record::Resolving { promise, done: false })?; + root(interp, &Value::Object(rec)); + let resolve = record_function(interp, Kind::Resolve, rec, 1)?; + root(interp, &resolve); + let reject = record_function(interp, Kind::Reject, rec, 1)?; + Ok((rec, resolve, reject)) + }) +} + +/// Checks that `n` more jobs fit in the queue and in the heap. Everything the caller still needs +/// must be reachable from the roots. +fn reserve_jobs(interp: &mut Interp, n: usize) -> JsResult<()> { + if interp.promises.queue.len().saturating_add(n) > interp.promises.max_jobs { + return Err(Abrupt::Limit(LimitKind::Jobs)); + } + interp.reserve_heap(JOB_BYTES.saturating_mul(n)) +} + +/// Queues a job [`reserve_jobs`] made room for. +fn push_job(interp: &mut Interp, job: Job) { + interp.heap.bytes = interp.heap.bytes.saturating_add(JOB_BYTES); + interp.promises.queue.push_back(job); +} + +/// Settles pending promise `p` (FulfillPromise and RejectPromise, sections 25.6.1.4 and 25.6.1.7) +/// and queues a job for each reaction. `p` and `value` must be rooted. +fn settle(interp: &mut Interp, p: ObjId, fulfilled: bool, value: Value, site: Option) -> JsResult<()> { + let waiting = promise_data(interp, p)?.reactions.len(); + reserve_jobs(interp, waiting)?; + let data = promise_data(interp, p)?; + if data.state != State::Pending { + return Ok(()); + } + data.state = if fulfilled { State::Fulfilled } else { State::Rejected }; + data.result = value.clone(); + if !fulfilled { + data.site.clone_from(&site); + } + let reactions = std::mem::take(&mut data.reactions); + let handled = data.handled; + interp.heap.bytes = interp.heap.bytes.saturating_sub(REACTION_BYTES.saturating_mul(reactions.len())); + for r in reactions { + let handler = if fulfilled { r.on_fulfilled } else { r.on_rejected }; + push_job(interp, Job::Reaction { handler, argument: value.clone(), reject: !fulfilled, derived: r.derived, site: site.clone() }); + } + if !fulfilled && !handled { + interp.promises.rejected.push(p); + } + Ok(()) +} + +fn reject_promise(interp: &mut Interp, p: ObjId, reason: Value, site: Option) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &reason); + settle(interp, p, false, reason, site) + }) +} + +/// A resolve function's steps after its first-call check (section 25.6.1.3.2): `resolution` +/// fulfills `p`, unless it is `p` itself (a `TypeError` rejects it) or an object whose `then` is +/// callable (a job adopts its state), and an exception reading `then` rejects it. +fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &resolution); + let Value::Object(o) = resolution else { return settle(interp, p, true, resolution, None) }; + if o == p { + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + let site = here(interp); + return reject_promise(interp, p, e, site); + } + let then = match interp.get_from(o, &key("then"), &resolution) { + Ok(t) => t, + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + return settle(interp, p, false, e, site); + } + Err(e) => return Err(e), + }; + if !interp.is_callable(&then) { + return settle(interp, p, true, resolution, None); + } + root(interp, &then); + reserve_jobs(interp, 1)?; + push_job(interp, Job::Thenable { promise: p, thenable: resolution, then }); + Ok(()) + }) +} + +/// The resolve function of the resolving record `rec`. +fn resolve_through(interp: &mut Interp, rec: ObjId, value: Value) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + resolve_promise(interp, p, value) +} + +/// The reject function of the resolving record `rec`. +fn reject_through(interp: &mut Interp, rec: ObjId, reason: Value, site: Option) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + reject_promise(interp, p, reason, site) +} + +/// PerformPromiseThen (section 25.6.5.4.1) with `derived` as the result capability's promise. +/// Every value must be rooted. +fn perform_then(interp: &mut Interp, p: ObjId, on_fulfilled: Value, on_rejected: Value, derived: ObjId) -> JsResult<()> { + let on_fulfilled = if interp.is_callable(&on_fulfilled) { on_fulfilled } else { Value::Undefined }; + let on_rejected = if interp.is_callable(&on_rejected) { on_rejected } else { Value::Undefined }; + let state = promise_data(interp, p)?.state; + if state == State::Pending { + interp.reserve_heap(REACTION_BYTES)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(REACTION_BYTES); + } else { + reserve_jobs(interp, 1)?; + } + let data = promise_data(interp, p)?; + data.handled = true; + match data.state { + State::Pending => { + data.reactions.push(Reaction { on_fulfilled, on_rejected, derived }); + } + State::Fulfilled => { + let argument = data.result.clone(); + push_job(interp, Job::Reaction { handler: on_fulfilled, argument, reject: false, derived, site: None }); + } + State::Rejected => { + let (argument, site) = (data.result.clone(), data.site.clone()); + push_job(interp, Job::Reaction { handler: on_rejected, argument, reject: true, derived, site }); + } + } + Ok(()) +} + +/// PromiseResolve (section 25.6.4.5.1) with `c` as the constructor: `x` when it is a promise whose +/// `constructor` is `c`, otherwise a new promise resolved with `x`. +fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &x); + if let Value::Object(o) = x + && is_promise(interp, &x) + { + let ctor = interp.get_from(o, &key("constructor"), &x)?; + if crate::interp::same_value(&ctor, c) { + return Ok(x); + } + } + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + resolve_promise(interp, p, x)?; + Ok(Value::Object(p)) + }) +} + +// ---- the job queue ---- + +impl Interp { + /// A run begun with [`crate::Realm::start`] is going: its script's code or the jobs after it. + pub(crate) fn running(&self) -> bool { + !self.frames.is_empty() || self.promises.draining + } + + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's + /// code ended with `completion`, which this gives back. + pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { + self.promises.completion = Some(completion); + loop { + if !self.frames.is_empty() { + let r = self.execute(); + self.job_returned(r)?; + continue; + } + let Some(job) = self.promises.queue.pop_front() else { break }; + self.start_job(job)?; + } + Ok(self.promises.completion.take().unwrap_or(Value::Undefined)) + } + + /// [`Interp::execute_slice`] for a run begun with [`crate::Realm::start`]: runs the script's + /// code and then the queued jobs, and gives `Some` with the script's completion value once the + /// code has ended and the queue is empty. + pub(crate) fn execute_run_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + if self.frames.is_empty() { + let Some(job) = self.promises.queue.pop_front() else { + self.promises.draining = false; + // A pause asked for in the run's last step ends with the run. + self.pause.set(false); + return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); + }; + self.start_job(job)?; + if self.can_pause_between_jobs(pause_at) { + return Ok(None); + } + continue; + } + match self.execute_slice(pause_at) { + Ok(None) => return Ok(None), + Ok(Some(v)) if self.promises.running.is_none() => { + // The script's own code ended. + if self.promises.queue.is_empty() { + self.pause.set(false); + return Ok(Some(v)); + } + self.promises.completion = Some(v); + self.promises.draining = true; + } + Ok(Some(v)) => self.finish_job(Ok(v))?, + Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, + Err(e) => return Err(e), + } + if self.can_pause_between_jobs(pause_at) { + return Ok(None); + } + } + } + + /// No code is running and jobs are still queued, and the slice has used its fuel or the host + /// asked for a pause. With the queue empty the run is done instead, and the next turn of the + /// loop ends it. + fn can_pause_between_jobs(&self, pause_at: u64) -> bool { + self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) + } + + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { + match r { + Ok(v) => self.finish_job(Ok(v)), + Err(Abrupt::Throw(v)) => self.finish_job(Err(v)), + Err(e) => Err(e), + } + } + + /// Starts a job: a native callback runs to its end here, and a callback written in JavaScript + /// gets a frame the caller runs. + fn start_job(&mut self, job: Job) -> JsResult<()> { + self.heap.bytes = self.heap.bytes.saturating_sub(JOB_BYTES); + self.use_fuel()?; + scoped(self, |interp| { + let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, derived, site } => { + if !interp.is_callable(&handler) { + return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; + } + root(interp, &Value::Object(derived)); + match finally_callback(interp, &handler) { + // The callback runs as the job's own call, so a slice can pause inside it. + Some((on_finally, throws)) => { + interp.temp_roots.extend([handler, argument.clone()]); + (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) + } + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)), + } + } + Job::Thenable { promise, thenable, then } => { + interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); + let (rec, resolve, reject) = resolving_functions(interp, promise)?; + (then, thenable, vec![resolve, reject], Then::Reject(rec)) + } + }; + interp.temp_roots.push(f.clone()); + interp.temp_roots.push(this.clone()); + interp.temp_roots.extend(args.iter().cloned()); + interp.promises.running = Some(then); + match interp.start_call(f, this, args) { + Ok(Some(v)) => interp.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => interp.finish_job(Err(e)), + Err(e) => Err(e), + } + }) + } + + /// Ends the running job with its call's result or exception. + fn finish_job(&mut self, r: Result) -> JsResult<()> { + let site = if r.is_err() { caught(self) } else { None }; + let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; + match (then, r) { + (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), + (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), + (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(rec), Err(e)) => scoped(self, |interp| { + root(interp, &Value::Object(rec)); + reject_through(interp, rec, e, site) + }), + (Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| { + interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]); + match after_finally(interp, result, value, throws) { + Ok(v) => resolve_promise(interp, derived, v), + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + reject_promise(interp, derived, e, site) + } + Err(e) => Err(e), + } + }), + (Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site), + } + } + + /// Drops the run's queued jobs and its state; with `keep_rejections` false, the rejections it + /// noted too. + pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_sub(queued); + // A new queue frees the old one's buffer, which the heap estimate does not count. + self.promises.queue = VecDeque::new(); + self.promises.running = None; + self.promises.completion = None; + self.promises.draining = false; + if !keep_rejections { + self.promises.rejected.clear(); + } + } + + /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of + /// them described, and how many there are; the run's notes are cleared. + pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { + let rejected = std::mem::take(&mut self.promises.rejected); + let mut out = Vec::new(); + let mut attribution = Vec::new(); + let mut count = 0; + for p in rejected { + let (reason, site) = match self.heap.object(p).map(|o| &o.class) { + Some(Class::Promise(d)) if !d.handled && d.state == State::Rejected => (d.result.clone(), d.site.clone()), + _ => continue, + }; + count += 1; + if out.len() >= MAX_REPORTED { + continue; + } + // Two code units per character keeps MAX_REASON_CHARS characters and one more, so the + // cut below still marks a longer reason. + let mut message = self.describe_prefix(&reason, 2 * MAX_REASON_CHARS + 2); + if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { + message.truncate(cut); + message.push('…'); + } + let authored = if let Some(object) = reason.as_object() { + if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) { + *authored + } else { + let authored = self.thrown_by_script(&reason); + attribution.push((object, authored)); + authored + } + } else { + self.thrown_by_script(&reason) + }; + let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); + out.push(crate::Rejection { message, line, column, tag, authored }); + } + (out, count) + } +} + +// ---- Promise ---- + +/// `new Promise(executor)` (section 25.6.3.1). Calling `Promise` without `new` is a `TypeError`. +fn promise_ctor(interp: &mut Interp, _: Value, args: &[Value], constructed: bool) -> JsResult { + if !constructed { + return Err(interp.type_error("Promise must be called with new")); + } + let executor = arg(args, 0); + if !interp.is_callable(&executor) { + return Err(interp.type_error("the Promise executor is not a function")); + } + scoped(interp, |interp| { + root(interp, &executor); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match interp.call(&executor, &Value::Undefined, &[resolve, reject]) { + Ok(_) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// A promise's resolve function (section 25.6.1.3.2). +fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a resolve function lost its record".into()))?; + resolve_through(interp, rec, arg(args, 1))?; + Ok(Value::Undefined) +} + +/// A promise's reject function (section 25.6.1.3.1). +fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; + let site = here(interp).or_else(|| match &interp.promises.running { + Some(Then::Settle(_, site)) => site.clone(), + _ => None, + }); + reject_through(interp, rec, arg(args, 1), site)?; + Ok(Value::Undefined) +} + +/// `Promise.prototype.then` (section 25.6.5.4). +fn promise_then(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let p = this_promise(interp, &this, "then")?; + scoped(interp, |interp| { + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + perform_then(interp, p, arg(args, 0), arg(args, 1), derived)?; + Ok(Value::Object(derived)) + }) +} + +/// `Promise.prototype.catch` (section 25.6.5.1). +fn promise_catch(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + invoke(interp, &this, "then", &[Value::Undefined, arg(args, 0)]) +} + +/// `Promise.prototype.finally` (section 25.6.5.3). +fn promise_finally(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !matches!(this, Value::Object(_)) { + return Err(interp.type_error("Promise.prototype.finally was called on a value that is not an object")); + } + let on_finally = arg(args, 0); + if !interp.is_callable(&on_finally) { + return invoke(interp, &this, "then", &[on_finally.clone(), on_finally]); + } + scoped(interp, |interp| { + let rec = new_record(interp, Record::Finally { on_finally })?; + root(interp, &Value::Object(rec)); + let then_finally = record_function(interp, Kind::ThenFinally, rec, 1)?; + root(interp, &then_finally); + let catch_finally = record_function(interp, Kind::CatchFinally, rec, 1)?; + root(interp, &catch_finally); + invoke(interp, &this, "then", &[then_finally, catch_finally]) + }) +} + +/// Then Finally and Catch Finally (sections 25.6.5.3.1 and 25.6.5.3.2): calls the callback, then +/// passes `value` on, or throws it again when `throws`, once the callback's result settles. +fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult { + let rec_value = arg(args, 0); + let value = arg(args, 1); + let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) }; + let on_finally = on_finally.clone(); + let result = interp.call(&on_finally, &Value::Undefined, &[])?; + after_finally(interp, result, value, throws) +} + +/// The steps of Then Finally and Catch Finally after the callback returned `result`: a promise +/// that passes `value` on, or throws it again when `throws`, once `result` settles. +fn after_finally(interp: &mut Interp, result: Value, value: Value, throws: bool) -> JsResult { + scoped(interp, |interp| { + root(interp, &value); + root(interp, &result); + let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); + let promise = promise_resolve(interp, &ctor, result)?; + root(interp, &promise); + let rec = new_record(interp, Record::Thunk { value })?; + root(interp, &Value::Object(rec)); + let thunk = record_function(interp, if throws { Kind::Thrower } else { Kind::ValueThunk }, rec, 0)?; + root(interp, &thunk); + invoke(interp, &promise, "then", &[thunk]) + }) +} + +/// When `handler` is the Then Finally or Catch Finally function of a `finally` call, its callback, +/// and whether the function throws the value it gets again. +fn finally_callback(interp: &Interp, handler: &Value) -> Option<(Value, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let natives = &interp.promises.natives; + let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) { + false + } else if natives.get(Kind::CatchFinally as usize) == Some(target) { + true + } else { + return None; + }; + match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::PromiseRecord(rec)) => match &**rec { + Record::Finally { on_finally } => Some((on_finally.clone(), throws)), + _ => None, + }, + _ => None, + } +} + +fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, false) +} + +fn catch_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, true) +} + +fn thunk_value(interp: &mut Interp, args: &[Value]) -> JsResult { + match record(interp, &arg(args, 0))? { + Record::Thunk { value } => Ok(value.clone()), + _ => Err(Abrupt::Internal("not a thunk record".into())), + } +} + +fn value_thunk(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + thunk_value(interp, args) +} + +fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Err(Abrupt::Throw(thunk_value(interp, args)?)) +} + +/// `v` is a constructor: a function written in JavaScript other than an arrow function or a +/// method, a built-in constructor, or a bound function whose target is one. +fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { + let mut v = v.clone(); + loop { + let func = match v.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::Function(f)) => f.clone(), + _ => return Ok(false), + }; + match func { + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method), + Func::Native { constructor, .. } => return Ok(constructor), + Func::Bound { target, .. } => { + interp.use_fuel()?; + v = Value::Object(target); + } + _ => return Ok(false), + } + } +} + +/// The `this` value of a static method, which must be a constructor. +fn this_constructor(interp: &mut Interp, this: &Value, name: &str) -> JsResult<()> { + if is_constructor(interp, this)? { + return Ok(()); + } + Err(interp.type_error(&format!("Promise.{name} was called on a value that is not a constructor"))) +} + +/// `Promise.resolve` (section 25.6.4.6). +fn promise_resolve_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "resolve")?; + promise_resolve(interp, &this, arg(args, 0)) +} + +/// `Promise.reject` (section 25.6.4.5). +fn promise_reject_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "reject")?; + scoped(interp, |interp| { + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let site = here(interp); + reject_promise(interp, p, arg(args, 0), site)?; + Ok(Value::Object(p)) + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Combine { + All, + AllSettled, + Race, +} + +impl Combine { + fn name(self) -> &'static str { + match self { + Combine::All => "all", + Combine::AllSettled => "allSettled", + Combine::Race => "race", + } + } +} + +fn promise_all(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::All) +} + +fn promise_all_settled(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::AllSettled) +} + +fn promise_race(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::Race) +} + +/// `Promise.all`, `allSettled` and `race` (sections 25.6.4.1, 25.6.4.2 and 25.6.4.4): an exception +/// on the way rejects the promise they return (IfAbruptRejectPromise). +fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsResult { + this_constructor(interp, &this, how.name())?; + scoped(interp, |interp| { + root(interp, &input); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match combine_inputs(interp, &this, &input, how, rec, &resolve, &reject) { + Ok(()) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to +/// its length at each step, as an array iterator reads it, and another object up to the `length` +/// it had at the start. +enum Inputs { + Indexed { object: ObjId, length: f64 }, + CodePoints(Rc<[u16]>), +} + +impl Inputs { + fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + match input { + Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { + Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { + Ok(Inputs::Indexed { object: *o, length }) + } + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + }, + Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + } + } + + /// The input at `index`, which counts code units for a string; `None` past the end. + fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { + match self { + Inputs::Indexed { object, length } => { + let end = match interp.heap.object(*object).map(|o| &o.class) { + Some(Class::Array { length, .. }) => f64::from(*length), + _ => *length, + }; + if *index >= end { + return Ok(None); + } + let v = super::get_at(interp, *object, *index)?; + *index += 1.0; + Ok(Some(v)) + } + Inputs::CodePoints(units) => { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = *index as usize; + let Some(&first) = units.get(i) else { return Ok(None) }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let n = if pair { 2 } else { 1 }; + let piece = units.get(i..i + n).unwrap_or_default().to_vec(); + *index += n as f64; + let bytes = crate::heap::string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Some(Value::String(crate::value::Str::from_units(piece)))) + } + } + } +} + +fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { + let resolve_fn = interp.get_value(this, &key("resolve"))?; + if !interp.is_callable(&resolve_fn) { + return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); + } + root(interp, &resolve_fn); + let inputs = Inputs::new(interp, input, how)?; + let combinator = if how == Combine::Race { + None + } else { + let values = new_array(interp, 0)?; + root(interp, &Value::Object(values)); + let c = new_record(interp, Record::Combinator { resolving: rec, values, remaining: 1 })?; + root(interp, &Value::Object(c)); + Some((c, values)) + }; + let mut position = 0.0; + let mut index: u32 = 0; + loop { + interp.use_fuel()?; + let mark = interp.temp_roots.len(); + let Some(next) = inputs.get(interp, &mut position)? else { break }; + root(interp, &next); + let next_promise = interp.call(&resolve_fn, this, &[next])?; + root(interp, &next_promise); + match combinator { + None => { + invoke(interp, &next_promise, "then", &[resolve.clone(), reject.clone()])?; + } + Some((c, values)) => { + create_at(interp, values, f64::from(index), Value::Undefined)?; + let el = new_record(interp, Record::Element { combinator: c, index, called: false })?; + root(interp, &Value::Object(el)); + let (on_fulfilled, on_rejected) = if how == Combine::All { + (record_function(interp, Kind::AllElement, el, 1)?, reject.clone()) + } else { + let f = record_function(interp, Kind::SettledFulfilled, el, 1)?; + root(interp, &f); + (f, record_function(interp, Kind::SettledRejected, el, 1)?) + }; + interp.temp_roots.extend([on_fulfilled.clone(), on_rejected.clone()]); + if let Record::Combinator { remaining, .. } = record(interp, &Value::Object(c))? { + *remaining += 1; + } + invoke(interp, &next_promise, "then", &[on_fulfilled, on_rejected])?; + } + } + interp.temp_roots.truncate(mark); + index = index.checked_add(1).filter(|&i| i < u32::MAX).ok_or_else(|| interp.throw(ErrorType::Range, "too many promises to combine"))?; + } + if let Some((c, _)) = combinator { + element_done(interp, c)?; + } + Ok(()) +} + +/// Counts one more settled input of a `Promise.all` or `allSettled`; after the last one, resolves +/// the result with the values. +fn element_done(interp: &mut Interp, c: ObjId) -> JsResult<()> { + let Record::Combinator { resolving, values, remaining } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + *remaining = remaining.saturating_sub(1); + if *remaining > 0 { + return Ok(()); + } + let (resolving, values) = (*resolving, *values); + scoped(interp, |interp| { + root(interp, &Value::Object(c)); + resolve_through(interp, resolving, Value::Object(values)) + }) +} + +/// Stores `value` as one input's result (the first call only) and counts the input settled. +fn element_settled(interp: &mut Interp, args: &[Value], make: impl FnOnce(&mut Interp, Value) -> JsResult) -> JsResult { + let rec_value = arg(args, 0); + let Record::Element { combinator, index, called } = record(interp, &rec_value)? else { + return Err(Abrupt::Internal("not an element record".into())); + }; + if *called { + return Ok(Value::Undefined); + } + *called = true; + let (c, index) = (*combinator, *index); + let Record::Combinator { values, .. } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + let values = *values; + let v = make(interp, arg(args, 1))?; + scoped(interp, |interp| { + root(interp, &v); + super::put_at(interp, values, f64::from(index), v.clone())?; + element_done(interp, c) + })?; + Ok(Value::Undefined) +} + +/// `Promise.all` Resolve Element Functions (section 25.6.4.1.2). +fn all_element(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |_, v| Ok(v)) +} + +/// An `allSettled` result object: `{ status, value }` or `{ status, reason }`. +fn settled_object(interp: &mut Interp, fulfilled: bool, v: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &v); + interp.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES + 64)?; + let o = interp.new_object(); + root(interp, &Value::Object(o)); + let (status, name) = if fulfilled { ("fulfilled", "value") } else { ("rejected", "reason") }; + interp.define(o, key("status"), Prop::Data { value: Value::str(status), flags: OPEN })?; + interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?; + Ok(Value::Object(o)) + }) +} + +/// `Promise.allSettled` Resolve Element Functions (section 25.6.4.2.2). +fn settled_fulfilled(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, true, v)) +} + +/// `Promise.allSettled` Reject Element Functions (section 25.6.4.2.3). +fn settled_rejected(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, false, v)) +} diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index c009dddc9a..6a6867b270 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -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 diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index bddab84fd6..57ec9d6680 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -268,6 +268,10 @@ pub(crate) enum Class { Host(crate::host_classes::HostObj), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). UnitValue(Box), + /// A promise (ECMA-262 11th edition, section 25.6) and its state. + Promise(Box), + /// The state that the functions a promise operation makes share; scripts never see it. + PromiseRecord(Box), } /// 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, 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 diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..d2994fb80b 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -91,6 +91,8 @@ pub(crate) struct Entry { parent: Option, /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. own: Rc>, + /// The names of the members this class declares as unavailable. + unavailable: Rc>, } impl Entry { @@ -143,7 +145,9 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { 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 { 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::>(); 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 }) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..25265086e5 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -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> = 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); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 9edea621c5..6a57041cfe 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -55,12 +55,37 @@ pub(crate) fn internal(message: &str) -> JsResult { /// 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, /// [`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) -> JsResult> { + 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, saved: usize) -> JsResult { 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. diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 586ae77e24..a300d22451 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -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()); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 25e16d2337..17f2b1de0f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -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, ): 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; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs new file mode 100644 index 0000000000..ef0ed1d0d1 --- /dev/null +++ b/crates/js/src/promise_tests.rs @@ -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 = 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)); +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 71c42e0de0..b1273cb760 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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, 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 { 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, 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 { 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 diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index 4911c6e36b..1df3a9a6f0 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -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 { diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 61417a2879..bd8c406b79 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -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 = 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] = &[ diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1a2d805174..7c7be16279 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -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", diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs index 3777dab2e0..f154065fae 100644 --- a/crates/plugins/src/dialog.rs +++ b/crates/plugins/src/dialog.rs @@ -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>, + /// 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, +} + +/// 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> { + 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()); + } } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index ddbcb86582..e4274fc716 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -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, + /// 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, /// 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 { + 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>(d: D) -> std::result::Result, 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, 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 diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 4057af3eda..4b0a528703 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -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>, } /// 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 { 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 { + 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, 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 }); } 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 { /// 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 { + 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 { 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> { 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> { +/// [`decode_output_writing`] reads them, those of kinds `writes` changeable. +fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result> { 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 = 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 { /// 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 { @@ -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, parent: Option, admit: AdmitEffects) -> Result> { let wanted: HashSet = inputs.iter().copied().collect(); let mut originals: HashMap = HashMap::new(); @@ -1353,12 +1396,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec, 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) -> PathData { PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect()) } +mod writes; + #[cfg(test)] mod tests; diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 39d2d78776..5bfa28215d 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -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, Vec, 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> { + 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 = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect(); + let with = |entries: Vec| { + 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::>() + }; + 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 = (0..600).map(|i| format!("p{i}")).collect(); + let mut t = TextObject::point(Point::new(0.0, 0.0), ¶s.join("\n"), CharStyle::default()); + let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() }; + t.set_paragraph_styles((0..600).map(styled).collect()); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + // 600 old paragraphs times 602 new ones: none starts or ends both texts. + let text = format!("X\n{}\nY", paras.join("\n")); + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]}); + write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.paragraph_count(), 602); + let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect(); + let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect(); + assert_eq!(got, want); +} + +/// Every number in the character and paragraph styles a filter writes is checked against the range +/// the style commands keep it to, in a style of the filter's own and in one the type already has, +/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the +/// object and the field, and the document stays as it was. A set of the document's, given by +/// name, takes the document's characters. +#[test] +fn written_style_numbers_are_checked_even_in_a_style_the_type_has() { + use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject}; + let (mut d, _, layer, _) = mixed(); + d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() }); + let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }; + let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() }; + let bad_chars: [(&str, CharStyle, &str); 5] = [ + ("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"), + ("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"), + ("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"), + ("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"), + ("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"), + ]; + let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() }; + let bad_paras: [(&str, ParaStyle, &str); 4] = [ + ("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"), + ("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"), + ( + "hyphenation", + ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() }, + "paragraphs[0].hyphenation.after_first", + ), + ("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"), + ]; + // `own`: the type already has the bad style, and the filter changes only its other run or + // paragraph; otherwise the bad style is the filter's own. + let run = |id: NodeId, own: bool, bad: &CharStyle| { + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default()); + if own { + t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())]; + } + let mut doc = d.clone(); + let n = Node::new(id, NodeKind::Text(Box::new(t))); + let id = doc.insert(Some(layer), usize::MAX, n).unwrap(); + (doc, id) + }; + let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| { + let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap(); + let mut entry = entry; + entry["id"] = json!(id.0); + let mut changed = doc.clone(); + let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string(); + assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}"); + assert_eq!(&changed, doc, "{what}: nothing changed"); + }; + let fresh = d.clone().alloc_id(); + for (what, bad, says) in &bad_chars { + let (doc, id) = run(fresh, false, bad); + let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]); + check(&doc, id, json!({"text": {"runs": runs}}), says, what); + let (doc, id) = run(fresh, true, bad); + let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]); + check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has")); + } + let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() }; + for (what, bad, says) in &bad_paras { + let (doc, id) = run(fresh, false, &CharStyle::default()); + check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what); + let mut doc = doc; + if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) { + t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]); + } + check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has")); + } + // A set the document has, by name, takes the document's characters. + let (mut doc, id) = run(fresh, false, &CharStyle::default()); + let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap(); + let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() }); + let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]}); + write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、'])); +} + /// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON /// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output. #[test] diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs new file mode 100644 index 0000000000..574ebb6216 --- /dev/null +++ b/crates/plugins/src/objects/writes.rs @@ -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, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result>> { + 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) -> 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() -> &'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>(self, _: V) -> std::result::Result { + Err(Error::custom("not a struct")) + } + fn deserialize_struct>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result { + *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(v: &Value, parent: &str, key: &str) -> Result { + 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::(); + 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(v: &Value, at: &str, key: &str) -> Result<()> { + let names = attr_names::(); + let check = |o: &Map, 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 { + let c: Option> = 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 { + 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, 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 = 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::(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::>().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::>()?; + 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 { + 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> = 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 = am.iter().map(|s| id(s)).collect(); + let bi: Vec = 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 { + let mut st: ParaStyle = strict(v, parent, key)?; + let at = format!("{parent}.{key}"); + known_keys::(v, &at, "hyphenation")?; + known_keys::(v, &at, "justification")?; + known_keys::(v, &at, "tabs")?; + known_keys::(v, &at, "list")?; + let justification = match v.get("justification") { + None | Some(Value::Null) => None, + Some(j) => Some(serde_json::from_value::(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::(), + 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(()) +} diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 82f8db8641..5fda6fb896 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -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; diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index a4d9fda7af..ecba138052 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -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) } diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 01dc0dfbb2..0e331057d7 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -338,18 +338,19 @@ impl Operand { /// object: `[new] File|Folder(…)`, `new File|Folder`, `File.openDialog(…)`, `File.saveDialog(…)`, /// `Folder.selectDialog(…)`, `Folder.` ([`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.` 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.` 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) -> 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) { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 45f5d02d02..dd11c3dd0a 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -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. diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 9ae74c0936..845379311d 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -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 { + 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 { 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 { + 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 { + 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 { + 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 { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] .iter() @@ -252,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { 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 { 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 = 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 diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 2ce72b15f3..adb16b8f79 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -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 { +/// 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 { 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() { diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 0cdaad3434..a0d210f566 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -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::(), 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::(), 4, "{:?}", kept.path); +} + #[test] fn create_builds_the_three_tools() { for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] { diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 37c0e33bcd..52c3de1664 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -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 { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 6bbdc737d2..ede52c46c7 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -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 { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index db755ccae5..c8aa002add 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -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"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index acc5ff594e..ec2b83f1a6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -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 diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97b3c75cd2..185450a1ca 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -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"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index b93c94dddc..cb288e5938 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -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() }); diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index fa089bf4e7..993fc9c104 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -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::>() + }; + 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] diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 165ced795e..9d6fe2e887 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -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"); + } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 9483dea88f..3bd8df6cec 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -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(); diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 8765b57c00..1914b37a36 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -307,6 +307,7 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { 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()))), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 3c7af267e9..df2571a136 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -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"), diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6c4f808359..00a8b9cd61 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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 diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 23332c10cd..9f21fee18d 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -77,7 +77,10 @@ impl VectorcraftApp { pub fn run(&mut self, id: &str, params: Value) -> Result { self.beacon.command(id); let touch_workspace = self.session.prefs.touch_workspace; + // A `prefs.reset` that ran straight on the session applies before this command can switch workspaces. + crate::prefs_dialog::apply_prefs_resets(self); let result = self.run_now(id, params); + crate::prefs_dialog::apply_prefs_resets(self); if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 874146e102..1dbe830af4 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -406,7 +406,33 @@ impl VectorcraftApp { shape_widgets: self.ui.view.shape_widgets, screen: self.screen_frame(), artboard: self.view().map_or(0, |v| v.artboard), - ..ViewInfo::default() + precise: self.precise_cursors(), + } + } + + /// Whether the drawing tools show precise cursors: General › Use Precise Cursors is on, or Caps Lock is + /// (`Session::caps_lock`, which the canvas keeps at the host's state and `view.capsLock` sets). The canvas's pointer + /// and the tools' brush tips both follow it. + pub(crate) fn precise_cursors(&self) -> bool { + self.session.prefs.use_precise_cursors || self.session.caps_lock + } + + /// Takes the host's Caps Lock state `on` when it changes: the session follows it until the next change, and a + /// `view.capsLock` call between changes stays in place. + pub(crate) fn follow_caps_lock(&mut self, on: bool) { + if self.canvas.host_caps_lock == Some(on) { + return; + } + let first_reading = self.canvas.host_caps_lock.is_none(); + self.canvas.host_caps_lock = Some(on); + // A `view.capsLock` call that ran before the first reading stays in place; that reading is only the baseline. + if first_reading && self.session.caps_lock { + return; + } + if self.session.caps_lock != on + && let Err(err) = self.run("view.capsLock", serde_json::json!({ "on": on })) + { + log::error!("Could not update the Caps Lock state: {err}"); } } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 90875851d4..08b15cddc5 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,6 +25,10 @@ pub struct CanvasCache { /// The frame shown was rendered on the worker: an interaction's frames stay there /// ([`canvas::show`]). pub from_worker: bool, + /// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn + /// again on this thread would not have matched the frame around it: until the worker's next + /// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]). + pub worker_parts: bool, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. @@ -107,6 +111,9 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the + /// next reading; `None` before the first pass. + pub host_caps_lock: Option, /// A press on the canvas committed a panel field's running preview before the tool took the press, as the field's /// commit came first in production: the field's own commit later in the pass has nothing left to run. pub committed_preview: bool, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e0bc44b304..d13d79e4b9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,9 +5,11 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ - Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, + Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, + canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::primitives::PaintSlot; use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::NudgeMods; use craft::ui::style::StyleCx; @@ -108,6 +110,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) { app.ui.home = None; } + // The Home screen and the empty window show no marks: a closed document's text nodes are not kept. + if app.session.active().is_none() { + marks::release_text_marks(app); + } let full = ui.available_rect_before_wrap(); if crate::menus::home_showing(app) { // No type editor shows to lose the keys: the marked text stays as typed. @@ -133,6 +139,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { struct Body { reply: Option, context_at: Option, + /// The pasteboard's `context_at` answers the Menu key or Shift+F10, not a secondary click. + context_key: bool, /// A view a compass or scroll bar edit made this pass. edited: Option, } @@ -194,6 +202,11 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin }; let pasteboard = app.session.documents().get(win.0).map(|st| artboards::pasteboard_color(app, st, app.outline_view())); let layers = move || bounds; + let host_caps_lock = craft::ui::runtime::lock_keys::caps_lock(ui.ctx()); + app.follow_caps_lock(host_caps_lock); + // The canvas reverses the state it is given while the host's Caps Lock is on: given this, it shows the precise + // cursors the tools are told about. + let precise = app.precise_cursors() != host_caps_lock; let prefs = &app.session.prefs; let mut canvas = Canvas::new("Document") .id(canvas_id(win)) @@ -205,7 +218,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin .body_nudges(ARROWS) .rulers(x, y) .with_rulers(strips) - .precise_cursors(prefs.use_precise_cursors); + .precise_cursors(precise); if let Some(pasteboard) = pasteboard { canvas = canvas.pasteboard(pasteboard); } @@ -230,8 +243,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, edited } = body; - let request = reply.as_ref().and_then(|r| r.context.as_ref()).map(|c| c.at).or(context_at); + let Body { reply, context_at, context_key, edited } = body; + let request = reply + .as_ref() + .and_then(|r| r.context.as_ref()) + .map(|c| context_menu::Request { at: c.at, key: c.source == ContextSource::Key }) + .or(context_at.map(|at| context_menu::Request { at, key: context_key })); let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own. let view_now = @@ -261,11 +278,17 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the picture last. +/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the +/// picture last. fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; - let mut out = Body { context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), ..Body::default() }; + let background = space.background(); + let mut out = Body { + context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), + context_key: background.context.is_none() && background.context_key, + ..Body::default() + }; grids(app, ui, space, win); if live { find_shown_tool(app, ui.ctx(), space); @@ -276,7 +299,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - selection::show(app, ui, space, win, kind); + // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this + // frame's pointer event, from the document as the event leaves it. + let marks = PaintSlot::reserve(ui.painter()); widgets::show(app, ui, space, win, kind); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); @@ -313,6 +338,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } + let after = PaintSlot::reserve(ui.painter()); + selection::show(app, ui, space, win, kind); + marks.extend(ui.ctx(), after.take_after(ui.ctx())); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index 146e91d039..853ec2e038 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -4,25 +4,39 @@ use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; use craft::ui::menu::Menu; use egui::Pos2; use serde_json::json; +use vectorcraft_geom::Point; use super::marks; use super::outline::{hit_with, selection_hit_at}; use crate::VectorcraftApp; -/// The canvas context menu (right-click, Menu key, Shift+F10). A `request` (screen points: the pointer, or -/// the view centre for a key) selects the object under it unless it already is, then the menu lists what -/// applies to the selection ([`crate::menus::context_items`]) at that point until it closes. The locked -/// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` -/// for its Unlock submenu. With the Intertwine tool, a right-click where three or more objects of the group -/// overlap keeps the selection and puts what it arranges in `ui.context_intertwine` -/// ([`vectorcraft_tools::intertwine::menu_target`]). With the Artboard tool, an artboard takes the place of -/// the object ([`crate::panels::artboards::right_click`]). +/// A request for the canvas menu at `at` (screen points): a secondary click at the pointer, or the Menu key or +/// Shift+F10 (`key`), which the canvas reports at the view centre. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Request { + pub(crate) at: Pos2, + pub(crate) key: bool, +} + +/// The canvas context menu (right-click, Menu key, Shift+F10). A right-click selects the object under the +/// pointer unless it already is, then the menu lists what applies to the selection +/// ([`crate::menus::context_items`]) at that point until it closes. The locked objects under the pointer +/// ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` for its Unlock submenu. With +/// the Intertwine tool, a right-click where three or more objects of the group overlap keeps the selection and +/// puts what it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). With the +/// Artboard tool, an artboard takes the place of the object ([`crate::panels::artboards::right_click`]). A key +/// request keeps the selection and opens the menu at it ([`prepare_key`]). /// /// Called on every pass after the canvas shows, with its response as `opener`: the menu is shown from the /// point stored in `ui.context_menu_at`, so a later pass without a request keeps it open. -pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { - if let Some(at) = request { - prepare(app, space, at); +pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { + if let Some(request) = request { + let at = if request.key { + prepare_key(app, space) + } else { + prepare(app, space, request.at); + request.at + }; app.ui.context_menu_at = Some(at); } let Some(at) = app.ui.context_menu_at else { return }; @@ -69,3 +83,33 @@ fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let _ = app.run("select.set", json!({ "ids": [top.0] })); } } + +/// The one-shot work of a key request: the menu is for the selection as it is (the selected artboards with the +/// Artboard tool), at the centre of the part of it in view, or at the view centre when none of it is in view. +/// Nothing under a point is looked up: no locked objects, word or Intertwine target. Returns the menu's point. +fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { + app.ui.context_locked = None; + app.ui.context_intertwine = None; + app.ui.context_spelling = None; + let on_artboards = app.session.tool_id() == "artboard"; + let bounds = if on_artboards { + app.session.active().and_then(|st| { + let picked = crate::panels::artboards::picked(app, st.doc.artboards.len()); + picked.iter().filter_map(|&i| st.doc.artboards.get(i).map(|a| a.rect)).reduce(|a, b| a.union(b)) + }) + } else { + app.selection_bounds() + }; + let view = &space.view; + let at = bounds + .map(|b| { + egui::Rect::from_points(&[b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)].map(|p| view.to_screen(p))) + }) + .map(|r| r.intersect(view.rect)) + .filter(|r| !r.is_negative()) + .map_or(view.rect.center(), |r| r.center()); + if on_artboards { + crate::panels::artboards::measure_menu(app, view.to_doc(at)); + } + at +} diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index ca21ef7119..abe7c5a6db 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -160,6 +160,13 @@ pub(crate) struct Marks { artboard_marks: Vec, } +/// Drops the hidden-character and spelling memos and the text nodes they hold. +pub(crate) fn release_text_marks(app: &mut VectorcraftApp) { + app.canvas.hidden_chars.marks.clear(); + app.canvas.spelling = SpellingMarks::default(); + app.canvas.text_nodes = TextNodes::default(); +} + /// The marks of one canvas pass over `view`. The memos of [`crate::CanvasCache`] are kept while their /// gate is on and dropped, with the text nodes they hold, when it is off. pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { @@ -183,9 +190,7 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { let fades = artboards::fades_outside_artboards(app); let shows_artboards = artboards::shows_artboards(app); let Some(st) = app.session.active() else { - app.canvas.hidden_chars.marks.clear(); - app.canvas.spelling = SpellingMarks::default(); - app.canvas.text_nodes = TextNodes::default(); + release_text_marks(app); return m; }; let key = (st.uid, st.revision); diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 2bb6ecda50..29336a8ad8 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -122,6 +122,32 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() { assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept"); } +/// Closing the last document drops the memos' text nodes on the canvas's next frame, whether it +/// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window. +#[test] +fn a_canvas_frame_without_a_document_releases_the_text_nodes() { + let ctx = crate::testing::ui_context(); + let frame = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() }; + crate::testing::part_frame(app, &ctx, raw, crate::canvas::show); + }; + for home in [true, false] { + let mut app = app(); + app.session.execute("prefs.set", &json!({"key": "showHomeScreen", "value": home})).unwrap(); + text(&mut app, 20, 60, "one\ttwo qzxv\nthree"); + app.ui.view.hidden_chars = true; + app.ui.view.auto_spell_check = true; + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_some() && !app.canvas.hidden_chars.marks.is_empty(), "home {home}: the canvas keeps the memos"); + app.session.execute("file.close", &json!({})).unwrap(); + assert_eq!(crate::menus::home_showing(&app), home); + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_none(), "home {home}: no list of the closed document's text objects is kept"); + assert!(app.canvas.hidden_chars.marks.is_empty(), "home {home}: no hidden-character marks of the closed document are kept"); + assert!(app.canvas.spelling.lines.is_empty(), "home {home}: no spelling marks of the closed document are kept"); + } +} + /// `paths` small rectangles and three point type objects with hidden characters and words no /// dictionary knows: the first on the first layer, the second in a group on that layer and the /// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 7a80d814d6..03b8e4da67 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,12 +8,36 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } -/// Outline of a node for highlighting (paths, compound children, area type frames, other -/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip -/// group's clipping path only, as [`walk_drawn`] visits it). -pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { +/// What the view hides among a selected object's members, which the selection marks leave out as +/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on, +/// and paths made into guides while the guides are hidden. The default hides nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ViewHides { + pub(super) templates: bool, + pub(super) guides: bool, +} + +impl ViewHides { + /// What `app`'s view hides. + pub(super) fn of(app: &VectorcraftApp) -> Self { + Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() } + } + + /// [`Node::drawn_children`] of `n` without the members the view leaves out. Every path of a + /// compound path stays, since the compound path draws all of them, guides or not. + fn children(self, n: &Node) -> impl Iterator> { + let hide_guides = self.guides && !matches!(n.kind, NodeKind::Compound { .. }); + n.drawn_children().filter(move |c| !c.hidden_by_view(self.templates, hide_guides)) + } +} + +/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds, +/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures +/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it, +/// without the members `hides` leaves out). +pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()), // Area type shows its frame: the type area Direct Selection reshapes; type on a path its // path, which the selection tools' brackets sit on; point type shows its baseline(s). @@ -27,13 +51,20 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.line_to(t.xf * b); } } - } else if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + } else if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + // An image shows its frame, turned or distorted with it. + NodeKind::Image(_) => { + if let Some(frame) = c.image_frame() { + bp.extend(frame); + } + } + // A symbol instance shows its art's box, turned, skewed or in perspective with it. + NodeKind::SymbolInstance { .. } => { + if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } // A placed document shows its box, turned with it. @@ -56,6 +87,46 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Whether `n` is a linked image or a placed document, which the selection marks cross. +fn is_linked(n: &Node) -> bool { + match &n.kind { + NodeKind::Image(im) => im.link.is_some(), + NodeKind::PlacedDocument(_) => true, + _ => false, + } +} + +/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, +/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The +/// selection marks draw them; the hover highlight does not. +pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath { + let mut bp = BezPath::new(); + walk_drawn(n, hides, &mut |c| match &c.kind { + NodeKind::Image(_) if is_linked(c) => { + if let Some(cross) = c.image_cross() { + bp.extend(cross); + } + } + NodeKind::PlacedDocument(p) => { + let [tl, tr, br, bl] = p.corners(); + bp.move_to(tl); + bp.line_to(br); + bp.move_to(tr); + bp.line_to(bl); + } + _ => {} + }); + bp +} + +/// Adds the closed outline through the four corners `q` to `bp`. +fn corners(bp: &mut BezPath, q: [Point; 4]) { + let [a, b, c, d] = q; + bp.move_to(a); + [b, c, d].into_iter().for_each(|p| bp.line_to(p)); + bp.close_path(); +} + /// The most points ([`overlay_points`]) the selection's outlines and anchors, and the hover /// highlight, are drawn for: an Image Trace of a photo selects hundreds of thousands of paths at /// once, and selecting all of an opened PDF can select as many type objects, images and gradient @@ -63,22 +134,36 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { /// #2460). pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; -/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; -/// counting stops there). -pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - fn over(n: &Node, left: &mut usize) -> bool { - match left.checked_sub(overlay_points(n)) { +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`], +/// without the members `hides` leaves out; counting stops there). +pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, false, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them +/// without the members `hides` leaves out. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, true, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the +/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool, hides: ViewHides) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool { + let ends = if crosses && is_linked(n) { 4 } else { 0 }; + match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, None => return true, } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left)) + !matches!(n.kind, NodeKind::Envelope { .. }) && hides.children(n).any(|c| over(c, left, crosses, hides)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left)) + nodes.into_iter().any(|n| over(n, &mut left, crosses, hides)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a @@ -106,21 +191,22 @@ fn overlay_points(n: &Node) -> usize { } /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the -/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping -/// path, its first child, not the art the path clips (#2422). -pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { +/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, +/// its first child, not the art the path clips (#2422), and hidden members +/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out. +pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { return; } if n.clips() { if let Some(clip) = n.children().and_then(|children| children.first()) { - walk_drawn(clip, f); + walk_drawn(clip, hides, f); } return; } - for c in n.editing_children().iter() { - walk_drawn(c, f); + for c in hides.children(n) { + walk_drawn(c, hides, f); } } diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 0ed7de10cd..4ea015bac6 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -798,6 +798,69 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert!(!crate::canvas::selection::outlines(&app, st).is_empty(), "the selected rectangle is outlined in its pane"); } +/// Another pane crosses a selected linked image from corner to corner, as the current pane does, and outlines a +/// selected embedded image alone (#9080). +#[test] +fn other_panes_cross_a_selected_linked_image() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir("panes-linked-image").join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut place = |link: bool, at: [f64; 2]| { + app.session.execute("file.place", &json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (linked, embedded) = (place(true, [100.0, 100.0]), place(false, [250.0, 100.0])); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // How many paths the first document's pane outlines with `id` selected there. + let mut paths = |id: u64| { + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(&app, st).iter().map(|o| o.paths.len()).sum::() + }; + let (linked, embedded) = (paths(linked), paths(embedded)); + assert_eq!((linked, embedded), (2, 1), "the outline of a linked image and its crossing lines; an embedded image's outline alone"); +} + +/// Another pane outlines a selected group's visible members only: hiding a member draws the same outlines as deleting +/// it. +#[test] +fn other_panes_leave_out_a_selected_groups_hidden_members() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let id = |made: serde_json::Value| made["id"].as_u64().unwrap(); + let shown = id(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap()); + let hidden = id(app.run("shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60})).unwrap()); + app.run("select.set", json!({"ids": [shown, hidden]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // The paths the first document's pane outlines with the group selected there, after the commands `edit` there. + let outlines = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + app.run("document.activate", json!({"index": 0})).unwrap(); + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(app, &ctx, vec![]); + frame(app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect::>() + }; + let both = outlines(&mut app, &[]); + let without = outlines(&mut app, &[("select.set", json!({"ids": [hidden]})), ("edit.clear", json!({}))]); + let with_hidden = outlines(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the outlines show both members"); + assert_eq!(with_hidden, without, "a hidden member is not outlined"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 8243444d39..780dd5f7a8 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -48,13 +48,19 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// The pixels of the `w`×`h` frame through `view` to render again for `doc`, when only the document /// changed, or placed documents' bitmaps were made, since the frame shown (its key `key` but for -/// the revision and [`CacheKey::placed`], and its render options `opts`), which this thread -/// rendered, and no frame is on its way from the worker: those it changed in, and those the -/// objects showing those bitmaps' files cover (`Some(None)`: none), grown to whole eighths of the -/// frame, as long as they are at most half of it. None: render the whole frame. Frames the worker -/// renders stay whole: its renderer keeps the rasters of the art's effects, this thread's doesn't. -/// What changed is measured by this thread's renderer, which drew the frame shown: it keeps what -/// it measures (a 3D effect's art) to draw the part again. +/// the revision and [`CacheKey::placed`], and its render options `opts`), and no frame of another +/// document, or of this revision or a later one, is on its way from the worker: those it changed +/// in, and those the objects showing those bitmaps' files cover (`Some(None)`: none), grown to +/// whole eighths of the frame, as long as they are at most half of it. None: render the whole +/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve) +/// shows in the frame it is made in, when the part's share of the frame's last whole render time +/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their +/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame +/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn +/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]): +/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What +/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to +/// draw the part again. pub(super) fn changed_pixels( app: &mut VectorcraftApp, key: &CacheKey, @@ -71,19 +77,25 @@ pub(super) fn changed_pixels( } let shown_key = app.canvas.key.as_ref()?; let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() }; - if !same_view || app.canvas.texture.is_none() || app.canvas.from_worker || app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) { + let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some()); + // A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]). + let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision); + if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way { return None; } // The placed documents' files whose bitmaps were made since the frame shown. let entry = app.session.documents().iter().find(|d| d.uid as usize == key.doc).and_then(|d| app.canvas.placed_keys.get(&d.uid)); let placed = placed_changes(entry, shown_key.placed, key.placed, doc, vectorcraft_render::placed_document::made_between)?; + // Over a frame the worker rendered, the part's share of the whole frame's time is at most 8 ms. + let budget = if app.canvas.from_worker { 8.0 / app.canvas.last_ms } else { 0.5 }; match app.canvas.renderer.changed(shown, doc, opts).and(placed) { vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), Some([x0, y0, x1, y1]) => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); - (u64::from(x1 - x0) * u64::from(y1 - y0) * 2 <= u64::from(w) * u64::from(h)).then_some(Some([x0, y0, x1, y1])) + let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); + (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } }, vectorcraft_render::Changed::Everything => None, @@ -122,6 +134,9 @@ pub(crate) struct WorkerFrame { pub(crate) moved: usize, /// The frame holds pixels copied from the last frame. pub(crate) reused: bool, + /// The frame drew art in a way that depends on its size + /// ([`vectorcraft_render::FrameStats::view_sized`]). + pub(crate) view_sized: bool, } /// Nothing but the position of the view differs between the frame `kept` and the job `job`, in @@ -239,6 +254,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option let moved = r.stats.moved; (img, moved) }); + // A copied frame's parts draw nothing that depends on the frame's size ([`composed_frame`]). + let view_sized = !reused && r.stats.view_sized > 0; let keeps = job.may_keep && moved == 0 && r.stats.view_sized == 0 && img.pixels.len() <= MAX_KEPT_BYTES && (img.width, img.height) == (job.w, job.h); *kept = @@ -246,7 +263,7 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option // The kept frame stays sRGB, so the next frame's copied pixels are converted only once. let width = img.width; crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over()); - WorkerFrame { img, moved, reused } + WorkerFrame { img, moved, reused, view_sized } } /// Upload the art's raster directly into the canvas texture without reallocating or copying pixels; @@ -580,6 +597,7 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.reused = done.reused.then(|| frame::clock(ctx)); app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; + app.canvas.worker_parts = done.view_sized; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -667,7 +685,13 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f /// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s /// key: only the document changed since the frame shown, in that part of it /// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. -fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) { +/// +/// Over a frame the worker rendered, a part that drew raster effects from rasters made before +/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]), +/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]), +/// would not match the frame around it: it is not drawn, false is returned, and the edits after it +/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]). +fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool { let Frame { key, doc, effects, view, opts, pixel, .. } = frame; let t0 = monotonic_ms(); if region.is_none() { @@ -679,6 +703,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) { + app.canvas.worker_parts = true; + return false; + } let width = part.width; crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); let color = color_image(&part); @@ -689,6 +717,7 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] app.canvas.key = Some((*key).clone()); app.canvas.shown = Some(((*doc).clone(), opts.clone())); app.perf.render_ms = monotonic_ms() - t0; + true } /// With `waits_for_still` set (the web build) and the last render slow, an edit while the view @@ -736,7 +765,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this - // thread's renderer has none, so a frame fast on the worker would be slow here. + // thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a + // part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]). let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; @@ -751,11 +781,14 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let may_copy = app.canvas.key.as_ref() != Some(key); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); let mut landed = None; - match (&mut app.canvas.worker, heavy, changed) { - // Only the document changed since the frame shown, in a part of it: that part is - // rendered again, here, into the texture. `last_ms` stays the whole frame's. - (_, _, Some(region)) => draw_changed(app, &Frame { key, doc, effects, size: (w, h), view, opts, pixel }, region), - (Some(worker), true, None) => { + // Only the document changed since the frame shown, in a part of it: that part is rendered + // again, here, into the texture. `last_ms` stays the whole frame's. + let part = Frame { key, doc, effects, size: (w, h), view, opts, pixel }; + let drawn = changed.is_some_and(|region| draw_changed(app, &part, region)); + let Frame { opts, .. } = part; + match (&mut app.canvas.worker, heavy, drawn) { + (_, _, true) => {} + (Some(worker), true, false) => { // The worker draws the frame: what this thread's renderer made to measure the edit // isn't drawn here. app.canvas.renderer.let_go_of_measured(); diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 96be3fcc89..c8e0dd5212 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; -use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn}; +use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). @@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool { crate::dialogs::halftone::previewing(app) } -/// Whether the selection has too many points to outline: its bounds stand for it. -fn too_big(st: &DocState) -> bool { - too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id))) +/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it. +fn too_big(app: &VectorcraftApp, st: &DocState) -> bool { + too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app)) } /// The rectangle of `bounds` as a path. @@ -166,17 +166,17 @@ fn group(out: &mut Vec, color: Color32) -> &mut Outlined { &mut out[at] } -/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline (the bounds of -/// all of them when they have too many points), the spine of each selected blend, and the key object's outline (its +/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline and the lines +/// across its linked images and placed documents (the bounds of all of them when they have too many points), the spine of each selected blend, and the key object's outline (its /// bounds when it has too many points). Nothing during Halftone Preview. pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { let mut out: Vec = vec![]; if hidden(app) { return out; } - let (sel, symbols) = (&st.selection, st.doc.symbol_boxes()); + let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app)); let color_of = |id: NodeId| c32(st.doc.layer_color(id)); - if too_big(st) { + if too_big(app, st) { // The cache is warmed by `show`; a test or a miss measures again. let bounds = match app.canvas.selection_bounds { Some((key, bounds)) if key == (st.uid, st.revision) => bounds, @@ -188,9 +188,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } else { for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; - let path = node_outline(node, &symbols); - if !path.elements().is_empty() { - group(&mut out, color_of(*id)).paths.push(path); + // Linked images and placed documents are also crossed from corner to corner. + for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] { + if !path.elements().is_empty() { + group(&mut out, color_of(*id)).paths.push(path); + } } } for (blend, spine) in blend_spines(st) { @@ -198,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } } if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) { - let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) }; + let path = if too_many_anchors([node], hides) { + node.geometric_bounds_with(&symbols).map(bounds_path) + } else { + Some(node_outline(node, &symbols, hides)) + }; if let Some(path) = path { group(&mut out, color_of(key)).key = Some(path); } @@ -266,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin segment_mark: SegmentMark::Line, options: path_options(prefs), }; - if hidden(app) || too_big(st) || (curvature && tool_points) { + if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; } - let sel = &st.selection; + let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; @@ -277,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let Some(node) = st.doc.node(*id) else { continue }; let partial = sel.partial(*id); let color = c32(st.doc.layer_color(*id)); - walk_drawn(node, &mut |c| { + walk_drawn(node, hides, &mut |c| { let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid); let grid = match &c.kind { NodeKind::Mesh(m) => Some(m), @@ -369,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, if kept { return None; } - outline_of(st, id) + outline_of(st, id, ViewHides::of(app)) } -/// The hover outline of `id` in its layer colour, unless it has too many points. -fn outline_of(st: &DocState, id: NodeId) -> Option { - let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; - Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) +/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many +/// points. +fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option { + let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?; + Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) }) } /// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view @@ -405,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, } let info = app.view_info(); let id = eyedropper_hover_object(app, at, mods, info)?; - outline_of(app.session.active()?, id) + outline_of(app.session.active()?, id, ViewHides::of(app)) } /// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and @@ -495,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; - if hidden(app) || too_big(st) { + if hidden(app) || too_big(app, st) { return out; } let symbols = st.doc.symbol_boxes(); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 4f5e469a63..a2c32f5d53 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() { let ids = app.session.active().unwrap().selection.objects.clone(); app.run("select.key", json!({"id": curve.0})).unwrap(); let st = app.session.active().unwrap(); - let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes()); + let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default()); let color = c32(st.doc.layer_color(curve)); let out = outlines(&app, st); let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap(); @@ -252,6 +252,298 @@ fn the_key_object_has_its_own_outline() { assert_eq!(out.iter().map(|o| o.paths.len()).sum::(), ids.len(), "the selection's own outlines stay"); } +/// A file with a 40 × 40 px red PNG in a new temporary folder named `name`. +fn red_png(name: &str) -> std::path::PathBuf { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir(name).join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + png +} + +/// The two lines from corner to corner of `[tl, tr, br, bl]`. +fn cross_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(br), PathEl::MoveTo(tr), PathEl::LineTo(bl)] +} + +/// The outline of `[tl, tr, br, bl]`: its corners joined by straight lines. +fn frame_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(tr), PathEl::LineTo(br), PathEl::LineTo(bl), PathEl::ClosePath] +} + +/// A selected linked image and a selected placed document are crossed from corner to corner, on a turned or +/// distorted image along its frame; a selected embedded image shows its outline alone, along its frame when turned or +/// distorted. The key object's outline and the hover outline are not crossed (#9080). +#[test] +fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { + let png = red_png("selection-linked"); + let placed = png.with_file_name("art.vectorcraft"); + std::fs::write(&placed, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(60.0, 40.0))).unwrap(); + let mut app = blank(); + let place = |app: &mut VectorcraftApp, path: &std::path::Path, link: bool, at: [f64; 2]| { + NodeId(app.run("file.place", json!({"path": path, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap()) + }; + let linked = place(&mut app, &png, true, [100.0, 120.0]); + let embedded = place(&mut app, &png, false, [300.0, 120.0]); + let document = place(&mut app, &placed, true, [200.0, 230.0]); + let corners = |app: &VectorcraftApp, id: NodeId| { + let n = app.session.active().unwrap().doc.node(id).unwrap(); + match &n.kind { + NodeKind::PlacedDocument(p) => p.corners(), + _ => n.image_corners().unwrap(), + } + }; + // Whether the selection's outlines hold a path made of `els`. + let drawn = |app: &VectorcraftApp, els: &[PathEl]| { + outlines(app, app.session.active().unwrap()).iter().any(|o| o.paths.iter().any(|p| p.elements() == els)) + }; + // Whether `id` is crossed, and whether it is outlined along its frame. + let marked = |app: &VectorcraftApp, id: NodeId| (drawn(app, &cross_of(corners(app, id))), drawn(app, &frame_of(corners(app, id)))); + app.run("select.all", json!({})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a linked image"); + assert!(drawn(&app, &cross_of(corners(&app, document))), "a placed document"); + assert_eq!(marked(&app, embedded), (false, true), "an embedded image"); + assert_eq!(outlines(&app, app.session.active().unwrap()).iter().map(|o| o.paths.len()).sum::(), 5, "three outlines and two crosses"); + app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a turned linked image, along its frame"); + assert_eq!(marked(&app, embedded), (false, true), "a turned embedded image, outlined along its frame"); + // Move each image's bottom right corner up its right side, so its corners no longer make a parallelogram. + app.session + .edit("Distort", |doc, _| { + for id in [linked, embedded] { + if let Some(n) = doc.node_mut(id) + && let Some([tl, tr, br, bl]) = n.image_corners() + { + n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?; + } + } + Ok(()) + }) + .unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted"); + assert_eq!(marked(&app, linked), (true, true), "a distorted linked image, corner to corner"); + assert_eq!(marked(&app, embedded), (false, true), "a distorted embedded image, outlined along its frame"); + // The key object's outline is its frame alone, and so is the hover outline. + for id in [linked, embedded] { + app.run("select.key", json!({"id": id.0})).unwrap(); + let st = app.session.active().unwrap(); + let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap(); + assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}"); + assert_eq!( + outline_of(st, id, ViewHides::default()).unwrap().path.elements(), + frame_of(corners(&app, id)).as_slice(), + "the hover outline of {id:?}" + ); + } +} + +/// The selection's outlines count the ends of the lines that cross linked images toward the overlay's limit; the +/// hover outline and the key object's outline, which draw no such lines, do not (#9080). +#[test] +fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { + use super::super::outline::{too_many_anchors, too_many_marks}; + let image = |link: Option| { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + vectorcraft_doc::Node::new(NodeId(1), NodeKind::Image(Box::new(im))) + }; + // Four corners each fit; with the four ends of the crossing lines they do not. + let count = OVERLAY_MAX_ANCHORS / 6; + let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; + let embedded = vec![image(None); count]; + let all = ViewHides::default(); + assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images"); + assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images"); +} + +/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image +/// in a hidden group inside it leave no outline, anchors or crossing lines, in the selection's marks and in the hover +/// outline. Hiding them shows the same as deleting them. +#[test] +fn a_selected_group_leaves_its_hidden_members_unmarked() { + let png = red_png("selection-hidden"); + let mut app = blank(); + let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap()); + let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap()); + let linked = app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let inner = id_of(&app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + // With the group selected after the commands `edit`: its outline paths, the paths that show anchors with their + // anchor count, and its hover outline. + let shown = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app, &[]); + let without = shown(&mut app, &[("select.set", json!({"ids": [hidden.0, inner.0]})), ("edit.clear", json!({}))]); + let with_hidden = shown(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden.0, inner.0]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the marks show every member"); + assert_eq!(without.1, vec![4, 4], "the anchors of the two visible members"); + assert_eq!(with_hidden, without, "hidden members are not marked"); +} + +/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its +/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is +/// marked too. +#[test] +fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { + let mut app = blank(); + let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + assert!( + matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })), + "the group holds a guide" + ); + // With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box. + let shown = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides_shown(), "the guides are hidden"); + let guides_hidden = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let without = shown(&mut app); + assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}"); + assert_ne!(both, without, "with the guides shown, the guide is marked"); + assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked"); +} + +/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide +/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws. +#[test] +fn the_marks_leave_out_template_layers_and_guides_the_view_hides() { + use super::super::outline::{node_outline, too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0))); + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default()); + let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1)); + if let NodeKind::Layer { template: on, children, .. } = &mut template.kind { + *on = true; + children.push(Arc::new(many.clone())); + } + let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(template), path.clone()]); + } + if let NodeKind::Path { guide, .. } = &mut many.kind { + *guide = true; + } + let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]); + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box(); + let mut wrong = vec![]; + for (n, what, hides) in [ + (&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }), + (&group, "a group with a guide", ViewHides { templates: false, guides: true }), + ] { + for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] { + let outline = node_outline(n, &symbols, hides).bounding_box(); + if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden { + wrong.push(format!("{what}, hidden by the view: {hidden}")); + } + } + } + assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}"); + // A compound path made into a guide draws every path, so each stays outlined while the guides are hidden. + let guide_rect = |id: u64, r: vectorcraft_geom::Rect| { + let mut n = rect(id, r); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let compound = Node::new( + NodeId(7), + NodeKind::Compound { + children: vec![ + guide_rect(8, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0)), + guide_rect(9, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)), + ], + rule: vectorcraft_geom::FillRule::EvenOdd, + }, + ); + let contours = |hides| node_outline(&compound, &symbols, hides).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(ViewHides { templates: false, guides: true }), contours(ViewHides::default()), "a compound path keeps its guide paths"); +} + +/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a +/// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it. +#[test] +fn the_overlay_limit_leaves_out_hidden_members() { + use super::super::outline::{too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default())); + let few = Arc::new(Node::path( + NodeId(3), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::default(), + )); + let mut wrong = vec![]; + for visible in [true, false] { + let mut member = (*many).clone(); + member.visible = visible; + let members = || vec![Arc::new(member.clone()), few.clone()]; + let group = Node::group(NodeId(1), members()); + let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() }); + let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0))); + let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() }); + let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = visible; + if let Some(children) = sublayer.children_mut() { + children.push(many.clone()); + } + let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(sublayer), few.clone()]); + } + for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { + if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible { + wrong.push(format!("{what}, member visible: {visible}")); + } + } + } + assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}"); +} + #[test] fn the_anchors_of_a_container_selected_whole_draw_selected() { let (mut app, _) = scene(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..50bcfc23d0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11,7 +11,7 @@ use super::artboards::names_an_artboard; use super::cursor::still_wait; use super::fill::{fill_view, polygon_area}; use super::marks::{HiddenMarks, thread_overlays}; -use super::outline::{node_outline, walk_drawn}; +use super::outline::{ViewHides, node_outline, walk_drawn}; use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker}; use super::*; use crate::CacheKey; @@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() { let g = st.doc.node(st.selection.objects[0]).unwrap(); assert!(g.extras().shaper.is_some()); let symbols = st.doc.symbol_boxes(); - let bounds = node_outline(g, &symbols).bounding_box(); + let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box(); assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}"); - assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline"); + assert_eq!( + node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0, + 50.0, + "an isolated original still shows its full outline" + ); } #[test] @@ -50,7 +54,95 @@ fn a_symbol_instance_is_outlined_around_its_art() { inst = Some(n); } }); - assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); + assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); +} + +/// The points of `bp`'s move and line elements, in order. +fn outline_points(bp: &vectorcraft_geom::BezPath) -> Vec { + use vectorcraft_geom::kurbo::PathEl; + bp.elements() + .iter() + .filter_map(|el| match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }) + .collect() +} + +/// Whether `got` are the points `want`, each within 1e-9, a last point of `got` that repeats its +/// first left out. +fn same_points(got: &[Point], want: &[Point]) -> bool { + let near = |a: &Point, b: &Point| a.distance(*b) < 1e-9; + let got = match got { + [first, rest @ .., last] if !rest.is_empty() && near(first, last) => &got[..got.len() - 1], + _ => got, + }; + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(a, b)) +} + +/// Puts `n` in perspective, drawn through `h`. +fn in_perspective(n: &mut Node, h: vectorcraft_geom::Homography) { + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some(h.to_array()), ..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0) }; + n.extras_mut().perspective = Some(Box::new(at)); +} + +#[test] +fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { + // The 20 × 20 square symbol of the test above, its instance at (20, 30). + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "star.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let st = s.active().unwrap(); + let mut inst = None; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + inst = Some(n.clone()); + } + }); + let inst = inst.unwrap(); + let symbols = st.doc.symbol_boxes(); + let square = [(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y)); + let placed = |a: Affine| { + let mut n = inst.clone(); + let NodeKind::SymbolInstance { xf, .. } = &mut n.kind else { panic!("an instance") }; + *xf = a * *xf; + let xf = *xf; + (n, square.map(|p| xf * p)) + }; + for (case, a) in [ + ("unturned", Affine::IDENTITY), + ("turned 30 degrees", Affine::rotate_about(30f64.to_radians(), Point::new(30.0, 40.0))), + ("skewed", Affine::skew(0.5, 0.0)), + ] { + let (n, frame) = placed(a); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); + assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}"); + } + // In perspective, the frame's corners go through the projection. + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.004, 0.0, 1.0]]); + let mut n = inst.clone(); + in_perspective(&mut n, h); + let (_, flat) = placed(Affine::IDENTITY); + let drawn = flat.map(|p| h.apply(p).unwrap()); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); + assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}"); +} + +#[test] +fn type_in_perspective_is_outlined_by_its_projected_box() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "Hello world", "size": 24})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + let st = s.active().unwrap(); + let mut n = st.doc.node(id).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + let b = t.bounds().unwrap(); + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]); + in_perspective(&mut n, h); + let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap()); + let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes(), ViewHides::default())); + assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); } /// One headless canvas frame on an 800 × 600 window. @@ -166,6 +258,99 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); } +/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the +/// points of lines and paths. +fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut points = vec![]; + for shape in flat_shapes(out.shapes) { + match shape { + Shape::Circle(c) => points.push(c.center), + Shape::Rect(r) => points.push(r.rect.center()), + Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends), + Shape::Path(p) => points.extend_from_slice(&p.points), + _ => {} + } + } + points +} + +/// A document with smart guides and the task bar off, every frame drawn on this thread. +fn drag_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.task_bar = false; + app.canvas.worker_started = true; + app +} + +fn press(at: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the +/// object has after that frame's event, and none at the corner it had before it. +#[test] +fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let corner = |app: &VectorcraftApp| { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + xf.to_screen(Point::new(b.x0, b.y0)) + }; + let start = xf.to_screen(Point::new(180.0, 120.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut moved = 0; + for i in 1..=6 { + let before = corner(&app); + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]); + let after = corner(&app); + if after.distance(before) < 4.0 { + continue; + } + moved += 1; + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}"); + assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}"); + } + assert!(moved >= 4, "the drag moves the object: {moved} frames"); +} + +/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and +/// none at the pointer of the frame before. +#[test] +fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pen"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let start = xf.to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut before = start; + for i in 1..=6 { + let at = start + vec2(9.0, 5.0) * i as f32; + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}"); + if i > 1 { + assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}"); + } + before = at; + } +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] @@ -1613,6 +1798,89 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } +/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the +/// frame of the move: once the press's frame arrives from the worker, every move shows the +/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters +/// from before their objects moved, when a part drawn here would have differed from it, or when +/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker, +/// and the moves after the worker's frame are drawn here again. A frame of an older revision on +/// its way does not hold a move back. +#[test] +fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..60 { + let (x, y) = (f64::from(i % 10) * 40.0, f64::from(i / 10) * 50.0); + app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 30, "height": 30})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + app.ui.view.smart_guides = false; + app.canvas.worker_started = true; // the first frame renders on this thread + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + app.select_tool("pen"); + let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision); + let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true)]); + assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker"); + assert!(side.render()); + let mut drag = |app: &mut VectorcraftApp| { + at += vec2(9.0, 5.0); + frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); + }; + for step in 0..6 { + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "move {step}: the curve is drawn in its own frame"); + assert!(side.jobs.try_recv().is_err(), "move {step}: nothing is queued on the worker"); + } + for case in ["moved", "differs", "slow"] { + match case { + "moved" => app.canvas.moved = true, + "differs" => app.canvas.worker_parts = true, + _ => app.canvas.last_ms = 10_000.0, + } + drag(&mut app); + assert!(shown(&app) < revision(&app), "{case}: the move is not drawn here"); + assert!(side.render(), "{case}: the move renders on the worker"); + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here"); + assert!(!app.canvas.worker_parts, "{case}"); + } + // A worker's frame that drew art in a way that depends on its size: the move after it renders + // on the worker too. + app.canvas.worker_parts = true; + drag(&mut app); + let job = side.jobs.try_iter().last().expect("the move is on the worker"); + let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job); + side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap(); + drag(&mut app); + assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size"); + assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker"); + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here"); + // A frame on its way of an older revision: the next move is drawn here, and that frame is not + // shown when it arrives. + app.canvas.worker_parts = true; + drag(&mut app); + assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way"); + app.canvas.worker_parts = false; + for late in [false, true] { + if late { + assert!(side.render()); + } + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "drawn here, the frame on its way arrived: {late}"); + } + frame(&mut app, &ctx, vec![button(at, false)]); + app.canvas.worker = None; +} + /// The frame after an interaction renders without `interacting` also when the interaction /// leaves the document as it was (#1257): here a drag back to where it started. #[test] @@ -1777,7 +2045,9 @@ fn cached_frames_keep_their_scale() { // Deliver the actual replacement and verify that it replaces the cached key. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false }).unwrap(); + completed + .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); frame(&mut app, size, new_ppp); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived"); } @@ -1917,7 +2187,9 @@ fn a_pan_fills_the_area() { // The fill arrives; the next frame draws it, and asks for no other fill. let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts); let (doc, opts) = (fill_job.doc, fill_job.opts); - fill_completed.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false }).unwrap(); + fill_completed + .send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); let (meshes, pixels) = frame(&mut app); assert!(fill_jobs.try_recv().is_err(), "the fill covers the canvas"); assert_eq!(app.canvas.key.as_ref(), Some(&old), "the last frame is still shown"); @@ -1962,11 +2234,15 @@ fn a_pan_fills_the_area() { app.view_mut().unwrap().center = Point::new(250.0, 150.0); // That fill finishes after the worker's frame: it is taken and not kept. let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts); - fill_completed.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false }).unwrap(); + fill_completed + .send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); // The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false }).unwrap(); + completed + .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); let (meshes, _) = frame(&mut app); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame is shown"); assert!(app.canvas.fill.is_none() && meshes.iter().all(|m| m.texture_id != fill_tex), "the fill is dropped"); @@ -3420,7 +3696,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // Cancel: nothing is edited, and the document, its undo history and the selection stay. let (before, undo, selected) = (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + let cancelled_token = app.missing_font_edit_token.expect("the question's edit token"); answer(&mut app, false); + // A delayed approval for the cancelled question can no longer start an edit. + app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true})); timed(&mut app, 1.5, vec![]); assert_eq!(app.session.tool_options()["editing"], json!(null)); assert!(!app.session.tool_wants_text()); @@ -3430,6 +3709,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // A new double-click asks again; OK edits with the caret where the type was clicked. double_click(&mut app, 3.0); assert!(asking(&app), "asked again"); + let replaced_token = app.missing_font_edit_token; + // A Type press sent through automation can replace the prompt before the user answers. + let view = app.view_info(); + let point = Point::new(b.x0 + b.width() * 0.25, b.center().y); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view); + } + assert_ne!(app.missing_font_edit_token, replaced_token); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(asking(&app), "the replacement question is open"); answer(&mut app, true); timed(&mut app, 3.5, vec![]); assert!(!asking(&app)); @@ -4653,17 +4942,83 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); let mut visited = vec![]; - walk_drawn(&group, &mut |n| visited.push(n.id)); + walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id)); assert_eq!(visited.contains(&NodeId(2)), view.shows_source()); let want = if view.shows_source() { vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0) } else { vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0) }; - assert_eq!(node_outline(&group, &symbols).bounding_box(), want); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want); } + // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + // A hidden path sent to the back of a trace is not its source image, in any view. + let mut path = + Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); + path.visible = false; + let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default()); + let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); + assert_eq!( + node_outline(&group, &symbols, ViewHides::default()).bounding_box(), + vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), + "{view:?}" + ); + } +} + +/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them +/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a +/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is +/// hidden, and a hidden object on its own keeps its outline. +#[test] +fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::{FillRule, PathEl}; + let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| { + let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + n.visible = visible; + Arc::new(n) + }; + let children = || { + vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)] + }; + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); + assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat"); + // A clip group shows its clipping path, hidden or not, and none of the art it clips. + let clip = |visible: bool| { + let mut members = children(); + members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible)); + let mut n = Node::group(NodeId(1), members); + if let NodeKind::Group { clip, .. } = &mut n.kind { + *clip = true; + } + contours(&n) + }; + assert_eq!((clip(true), clip(false)), (1, 1), "a clip group"); + // A hidden object that is itself selected keeps its outline. + assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object"); + let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); + let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = false; + if let Some(c) = sublayer.children_mut() { + c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true)); + } + if let Some(c) = layer.children_mut() { + c.extend(children()); + c.push(Arc::new(sublayer)); + } + assert_eq!(contours(&layer), 1, "a layer"); } /// #2572: Show Text Threads links a thread's frames from the out port of one to the in port of @@ -5043,6 +5398,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5066,6 +5422,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5088,6 +5445,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5110,6 +5468,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5170,7 +5529,16 @@ fn the_contour_bar_sets_corners_and_bakes() { /// A frame the render worker finished for `job`: white pixels of the job's size. fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; - crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), opts: job.opts.clone(), img, ms: 40.0, moved: 0, reused: false } + crate::render_worker::Done { + key: job.key.clone(), + doc: job.doc.clone(), + opts: job.opts.clone(), + img, + ms: 40.0, + moved: 0, + reused: false, + view_sized: false, + } } /// A job for the render worker to pan over a document of `doc`: a view at 100% moved by `(dx, dy)` @@ -5636,7 +6004,8 @@ fn a_pan_after_the_settling_frame() { let job = jobs.try_recv().unwrap_or_else(|_| panic!("{name}: the canvas asks for a frame")); let f = render_job(&mut r, &mut kept, &job); assert_eq!(f.reused, copies, "{name}"); - let done = crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img: f.img, ms: 40.0, moved: f.moved, reused: f.reused }; + let (key, doc, opts, img) = (job.key, job.doc, job.opts, f.img); + let done = crate::render_worker::Done { key, doc, opts, img, ms: 40.0, moved: f.moved, reused: f.reused, view_sized: f.view_sized }; done_tx.send(done).unwrap(); }; frame(&mut app, 1.0); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 3a8f20f69c..5bda6d918e 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -577,8 +577,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too } // Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after // the release, and a pointer over another window for the pointer to come in. - if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) { - crate::stylus::sync_eraser_tool(app); + if ui.ctx().current_pass_index() == 0 + && app.canvas.grab.is_none() + && ui.input(|i| i.pointer.has_pointer()) + && crate::stylus::sync_eraser_tool(app) + { + // Before the press, which holds what the host was told about the wheel until its release. + crate::stylus::sync_wheel_use(app); } // A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press // elsewhere for the clicks the tool's double-click or triple-click compares. diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index 88e1c533be..1ff48b983a 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -67,3 +67,88 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() { assert_ne!(alt, plain, "Alt shows the Eyedropper's cursor"); assert_eq!(shown(&mut app, egui::Modifiers::NONE), plain, "and letting go brings the bucket back"); } + +/// The Blob Brush's or the Eraser's tip outline at the pointer, as the canvas draws it this pass. +fn shows_tip(app: &mut VectorcraftApp) -> bool { + let view = app.view_info(); + app.session.overlays(view).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. })) +} + +/// Use Precise Cursors or Caps Lock, or both, gives the Blob Brush and the Eraser only the crosshair: the tool draws no +/// tip outline around it. With both off, each shows its own pointer and the tip outline. +#[test] +fn precise_cursors_hide_the_brush_tip_outline() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + for tool in ["blobBrush", "eraser"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + for (preference, caps_lock) in [(false, false), (true, false), (false, true), (true, true), (false, false)] { + app.run("prefs.set", serde_json::json!({"key": "usePreciseCursors", "value": preference})).unwrap(); + WindowHost::of(&ctx).set_caps_lock(Some(caps_lock)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + let precise = preference || caps_lock; + let case = format!("{tool}, Use Precise Cursors {preference}, Caps Lock {caps_lock}"); + assert_eq!(app.session.caps_lock, caps_lock, "{case}: the session takes the host's Caps Lock state"); + assert_eq!(app.view_info().precise, precise, "{case}"); + assert_eq!(shows_tip(&mut app), !precise, "{case}"); + assert_eq!(craft::ui::runtime::cursor::current(&ctx) == crosshair, precise, "{case}"); + } + } +} + +/// `view.capsLock` sets the Caps Lock state the tools and the canvas's pointer follow until the host's state changes. +#[test] +fn the_caps_lock_command_gives_the_brushes_the_crosshair() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(app.session.caps_lock, "the host's unchanged state leaves the command's in place"); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); + // With the host's Caps Lock on, the command turns it off for the tools and the canvas's pointer alike. + WindowHost::of(&ctx).set_caps_lock(Some(true)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!app.session.caps_lock); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); +} + +/// A `view.capsLock` call that runs before the first canvas pass stays in place when the host's Caps Lock is off. +#[test] +fn the_caps_lock_command_before_the_first_frame_stays_in_place() { + use craft::ui::runtime::windows::WindowHost; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock, "the first host reading is only the baseline"); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock); +} diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ab90d71dc2..a0d69c55c5 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -609,9 +609,8 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if typed && paragraph { - ranked(ui, rank::TYPE, |ui| { - crate::panels::paragraph::control_bar(app, ui); - }); + // The Paragraph group ranks its link and its Align buttons as two members, so the buttons leave first. + crate::panels::paragraph::control_bar(app, ui); } let vertical = group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some(); if vertical { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index c4b6f8a5fe..04a7240cf7 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -34,6 +34,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let rotation = app.view().map_or(0.0, |v| v.rotation); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); + // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 + // turns the -0 of a small negative angle into 0. + let angle = format!("{}°", rotation.round() + 0.0); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); @@ -68,13 +71,18 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let zoom = Field::new(tl!("Zoom")) .side(SideLabel::new().kind(LabelKind::Hidden)) .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); - // PLAN: assumed CanvasView::zoom and crate::state::zoom_display_percent(zoom, print) through the scheme (cv.S4). + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) { - zoom_to = Some(crate::state::zoom_display_percent(view.zoom, print)); + zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print)); } Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles).look(SelectLook::Filled).show(ui).value().copied(); + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .show(ui) + .value() + .copied(); }); Divider::vertical().show(ui); for (icon, to, tip, enabled) in diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 0fbfa24fd4..4ba5c01293 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -224,11 +224,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { crumbs.push((None, false, pn.clone())); } // Up one level: the isolated object's parent group, or `object.exitIsolation`, which goes from an - // isolated sublayer to its parent layer and otherwise leaves isolation mode. - let up = match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + // isolated sublayer to its parent layer, from a group in a symbol's art to the symbol's layer, and + // otherwise leaves isolation mode. While a pattern is edited the back arrow is Done. Screen readers + // call it by what it does. + let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer())); + let up = match parent_group { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), }; + let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer); + let up_one = parent_group.is_some() + || symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l)) + || (st.doc.mask_edit.is_none() + && symbol_layer.is_none() + && st.doc.node(iso).is_some_and(|n| n.is_layer()) + && st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p))); + let back_name = if pattern_edit.is_some() { + tl!("Done") + } else if up_one { + tl!("Back One Level") + } else if symbol_layer == Some(iso) { + tl!("Exit Symbol Editing Mode") + } else { + tl!("Exit Isolation Mode") + }; let entries: Vec> = crumbs.iter().enumerate().map(|(i, (_, _, name))| Entry::new(i, name.clone())).collect(); let mut nav: Option<(&str, serde_json::Value)> = None; let mut pattern_cmd: Option<&str> = None; @@ -237,7 +256,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area)); Bar::new(tl!("Isolation mode"), BarKind::Options).show(&mut bar_ui, |ui, _| { Row::new().fill().senses_surface().show(ui, |ui, cx| { - if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(tl!("Back")).show(ui).clicked() { + if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(back_name).show(ui).clicked() { if pattern_edit.is_some() { pattern_cmd = Some("object.pattern.done"); } else { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2c3b214c69..6484290054 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -716,6 +716,33 @@ fn the_status_bar_show_choice_is_checked_and_saved() { ); } +/// The status bar's Rotation box shows the view's angle: a preset angle shows its row's label, an angle between the +/// presets shows rounded to a whole degree, and a pick from the list still turns the view. +#[test] +fn the_status_bar_rotation_box_shows_the_view_angle() { + let mut bar = status_readout_app(); + let rotation = |bar: &mut Shown, angle: f64| { + bar.app().run("view.rotate", json!({ "angle": angle })).unwrap(); + let rotation = bar.settle().find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + let value = bar.tree().value_of(rotation.node).map(str::to_owned); + (rotation, value) + }; + for (angle, shown) in [(17.0, "17°"), (37.4, "37°"), (-0.3, "0°"), (-122.6, "-123°")] { + let (_, value) = rotation(&mut bar, angle); + assert_eq!(value.as_deref(), Some(shown), "the box at {angle}°"); + assert!(bar.texts().iter().any(|t| t.text == shown), "the box draws {shown}"); + } + let (_, value) = rotation(&mut bar, 45.0); + assert_eq!(value.as_deref(), Some("45°")); + // From an angle between the presets, the list still turns the view to the row picked. + let (opener, _) = rotation(&mut bar, 17.0); + bar.click_on(&opener).settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); + let rotation = bar.find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + assert_eq!(bar.tree().value_of(rotation.node), Some("-45°")); +} + /// While background work runs the status bar shows it where the message was, with the count of the jobs after the /// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress. #[test] @@ -806,6 +833,28 @@ fn set_zoom_100_matches_actual_size_with_display_print_size() { assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12); } +/// At UI Scaling 150% the zoom field shows the zoom `view.setZoom` set, and a zoom typed into it is the zoom the view +/// gets, as at 100%: 200% gives the view the zoom `view.setZoom` gives for 200%. +#[test] +fn the_zoom_field_sets_the_typed_zoom_at_any_ui_scaling() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.prefs.ui_scaling = 1.5; + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(460.0, 260.0)); + app.run("view.setZoom", json!({"zoom": 200})).unwrap(); + let wanted = app.view().unwrap().zoom; + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, super::status_bar); + assert!((bar.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling"); + let shown = |bar: &crate::tests::panel_harness::Panel| bar.value("Zoom").unwrap_or_default(); + assert!(shown(&bar).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&bar)); + bar.type_into("Zoom", "200"); + let zoom = bar.app().view().unwrap().zoom; + assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}"); + assert!(shown(&bar).starts_with("200"), "the field shows the typed zoom: {}", shown(&bar)); +} + /// Read the painted coordinates while checking that drawing never changes the source /// position, document, selection or either branch of its edit history. fn assert_status_coordinates(bar: &mut Shown, expected: Option<&str>) { @@ -1228,9 +1277,28 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown { /// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up /// to the pattern editing buttons at its right. fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 { - let back = bar.named("Back"); let path = bar.named("Isolation path"); - egui::pos2(path.rect.right() - 8.0, back.center().y) + egui::pos2(path.rect.right() - 8.0, path.center().y) +} + +/// The names of the isolation bar's controls in the latest frame that screen readers read with `role`, sorted. +fn isolation_names(bar: &Shown, role: Role) -> Vec { + let tree = bar.tree(); + let mut names: Vec = + tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(role)).filter_map(|key| tree.name_of(key)).map(str::to_owned).collect(); + names.sort(); + names +} + +/// The isolation bar's back arrow: the leftmost button named `name`. +fn isolation_back(bar: &mut Shown, name: &str) -> Target { + bar.frame(Vec::new()); + let tree = bar.tree(); + let keys: Vec<_> = tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key) == Some(name)).collect(); + keys.into_iter() + .filter_map(|key| bar.fixture.target(key)) + .min_by(|a, b| a.rect.left().total_cmp(&b.rect.left())) + .unwrap_or_else(|| panic!("no {name:?} button in {:?}", bar.names())) } /// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy, @@ -1259,15 +1327,15 @@ fn isolation_bar_navigation_and_back_button_steps_up() { let isolation = |bar: &Shown| bar.app().session.active().unwrap().isolation; // Clicking back from `a` steps up to parent group `g1` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g1))); // Clicking back from `g1` steps up to grandparent group `g2` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g2))); // Clicking back from `g2` (parent is layer) exits isolation mode completely - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None); // Deep isolate again to test clicking ancestor breadcrumb directly @@ -1306,11 +1374,11 @@ fn isolation_bar_back_button_steps_up_through_sublayers() { let steps = |bar: &Shown| bar.app().session.doc().unwrap().history.undo.len(); let before = steps(&bar); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(mid), "back from the deepest sublayer"); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(top), "back from the middle sublayer"); - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None, "back from the top-level layer"); assert_eq!(steps(&bar), before, "no undo step"); @@ -1373,7 +1441,8 @@ fn isolation_bar_background_click_leaves_pattern_edit_open() { let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open"); } - bar.click("Back"); + let back = isolation_back(&mut bar, "Done"); + bar.click_on(&back); let app = bar.app(); let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing"); @@ -1457,6 +1526,72 @@ fn isolation_bar_click_on_the_current_name_exits() { assert_eq!(bar.app().session.active().unwrap().isolation, None); } +/// Screen readers call the isolation bar's back arrow by what it does: Back One Level, Exit Isolation Mode, Exit +/// Symbol Editing Mode, or Done while a pattern is edited, in the UI's language. Each crumb of the levels above is +/// a link with the name it shows, and the current object's name is not a control. +#[test] +fn the_isolation_bars_controls_have_screen_reader_names() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name(); + let st = app.session.active().unwrap(); + let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap()); + let (layer_name, group_name) = (name(&app, layer), name(&app, group)); + let mut bar = isolation_shown(app); + let shown = |bar: &mut Shown, role: Role| { + bar.frame(Vec::new()); + isolation_names(bar, role) + }; + + // A path in a group: back goes to the group. + bar.app().run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + let mut crumbs = vec![layer_name.clone(), group_name.clone()]; + crumbs.sort(); + assert_eq!(shown(&mut bar, Role::LINK), crumbs, "the current object's name is not a link"); + + // The group itself: back leaves isolation mode. + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + assert_eq!(shown(&mut bar, Role::LINK), std::slice::from_ref(&layer_name)); + + // An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves. + let sub = bar.app().run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap(); + bar.app().run("object.isolate", json!({"id": sub})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + bar.app().run("object.isolate", json!({"id": layer.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + + // In German. + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = shown(&mut bar, Role::BUTTON); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(german, ["Isolationsmodus beenden"]); + bar.app().run("object.exitIsolation", json!({"all": true})).unwrap(); + + // Pattern editing: back is Done, beside Save a Copy, Done and Cancel. + let c = rect(&mut bar.app(), 200.0); + bar.app().run("select.set", json!({"ids": [c]})).unwrap(); + bar.app().run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Cancel", "Done", "Done", "Save a Copy"]); + bar.app().run("object.pattern.cancel", json!({})).unwrap(); + + // Symbol editing mode: back leaves it. + let d = rect(&mut bar.app(), 300.0); + bar.app().run("select.set", json!({"ids": [d]})).unwrap(); + bar.app().run("symbol.new", json!({"name": "Box"})).unwrap(); + bar.app().run("symbol.edit", json!({"name": "Box"})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Symbol Editing Mode"]); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern @@ -2551,6 +2686,26 @@ fn the_type_groups_leave_the_control_bar_before_opacity_and_style() { assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group"); } +/// With type selected, the Paragraph group's Align left, Align center and Align right buttons leave the Control bar +/// before its Paragraph: link: some width shows the link without them, and no width shows them without the link. +#[test] +fn the_paragraph_link_stays_on_the_control_bar_after_its_align_buttons_leave() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Paragraph:", "Align left", "Align center", "Align right"]; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s.iter().all(|shown| *shown)), "a wide bar shows {names:?}"); + for s in &seen { + assert!(s[1..].iter().all(|shown| *shown == s[1]), "the three Align buttons show or go together: {s:?}"); + assert!(!s[1] || s[0], "the Align buttons show only with the Paragraph: link: {s:?}"); + } + assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Paragraph: link without the Align buttons"); +} + /// With area type selected, its vertical alignment buttons leave the Control bar before Opacity and the Style group, /// and after the Align buttons that follow them, with the Character and Paragraph groups shown and with both off. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 813ed31d97..9d729c31d4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1465,6 +1465,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { params["dialog"] = json!(top.id.value().to_string()); } + if method == "ui.dialog.set" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::effect::normalize_set_mode(app, id, &mut params); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 2b3f5c31d1..2f9c594ab7 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -39,10 +39,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new( /// Where the glyphs that start at the box's upper left have their tip, in the icon's 24-unit box. const TIP: Vec2 = Vec2::new(2.0, 2.0); -/// The tip of the glyphs that point down-left (a pipette, a brush, a bucket, a knife). -const LOWER_LEFT: Vec2 = Vec2::new(2.0, 22.0); +/// The pipette's sampling tip, at the box's lower left. +const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0); /// The middle of the Anchor Point caret's square. const CARET: Vec2 = Vec2::new(12.0, 6.0); +/// The blade's point of the knife, at the box's upper right. +const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0); +/// The bottom of the drop below the paint bucket. +const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0); +/// The bottom of the drop beside the Live Paint diamond. +const DIAMOND_DROP: Vec2 = Vec2::new(20.0, 18.0); +/// The middle of the brush's bristle edge, at its lower left. +const BRISTLE_TIP: Vec2 = Vec2::new(6.0, 17.5); fn system(icon: CursorIcon) -> cb::Cursor { cb::Cursor::System(icon) @@ -111,7 +119,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::HandGrab => system(CursorIcon::Grabbing), Cursor::ZoomIn => PaintedCursor::zoom(false).into(), Cursor::ZoomOut => PaintedCursor::zoom(true).into(), - Cursor::Eyedropper => tool("pipette", LOWER_LEFT, None), + Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None), Cursor::NotAllowed => system(CursorIcon::NotAllowed), Cursor::Busy => system(CursorIcon::Progress), Cursor::AddStop => badged(CursorBadge::Add), @@ -136,10 +144,10 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::PencilContinue => marked(Crosshair, "cursor-mark-line-rising"), // Only the centre: the tool draws the tip's outline round it, at the zoom. Cursor::BlobBrush | Cursor::Eraser => PaintedCursor::circle(1.25).into(), - Cursor::Knife => tool("dc-knife", LOWER_LEFT, None), - Cursor::LivePaintBucket => tool("paint-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketFace => tool("dc-live-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketEdge => tool("paintbrush", LOWER_LEFT, None), + Cursor::Knife => tool("dc-knife", BLADE_POINT, None), + Cursor::LivePaintBucket => tool("paint-bucket", BUCKET_DROP, None), + Cursor::LivePaintBucketFace => tool("dc-live-bucket", DIAMOND_DROP, None), + Cursor::LivePaintBucketEdge => tool("paintbrush", BRISTLE_TIP, None), Cursor::LivePaintSelectFace => marked(Arrow, "cursor-mark-square"), Cursor::LivePaintSelectEdge => marked(Arrow, "cursor-mark-edge"), Cursor::LivePaintSelectOutside => marked(Arrow, "x"), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 68357f6b65..c3e9fc92e4 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -10,6 +10,41 @@ fn every_tool_cursors_hotspot_lies_inside_its_icon_box() { } } +/// A click lands where the glyph points: in every painted tool cursor's image, the icon's own +/// mark color (not only its halo) covers the hotspot pixel or one next to it. +#[test] +fn every_tool_cursors_hotspot_is_on_its_glyph() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + let mut missed = Vec::new(); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let ink = rgba_color(env.tokens.tokens().color.overlay.stroke); + let near_ink = |px: &[u8]| px[3] == 255 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + for c in GLYPHS { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { .. }) = tool_cursor(c) else { continue }; + let Some(image) = painted_image(&env, &painted, 2.0) else { + missed.push(format!("{c:?}: no image")); + continue; + }; + let ([w, h], [hx, hy]) = (image.size.map(usize::from), image.hotspot.map(usize::from)); + let on_glyph = (hy.saturating_sub(1)..=(hy + 1).min(h - 1)) + .flat_map(|y| (hx.saturating_sub(1)..=(hx + 1).min(w - 1)).map(move |x| (y * w + x) * 4)) + .any(|i| near_ink(&image.rgba[i..i + 4])); + if !on_glyph { + missed.push(format!("{c:?}")); + } + } + }) + .textures_delta + .clear(); + assert!(missed.is_empty(), "hotspots off their glyphs: {missed:?}"); +} + /// A `cursor-` icon name a cursor uses must be in the set the host registers. #[test] fn every_cursor_icon_the_app_names_is_in_its_set() { diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 9a89308e38..b1d1c3b356 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -23,7 +23,7 @@ use std::collections::BTreeSet; use craft::behavior::IconId; -use craft::behavior::dock::{Action, DockEdge}; +use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target}; use craft::ui::buttons::IconButton; use craft::ui::contract::{PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::DialogResult; @@ -345,6 +345,133 @@ fn set_shown(app: &mut VectorcraftApp, name: &str, show: Option) -> Result Ok(show) } +// ---------- docking and floating ---------- + +/// The window edge and column index from that edge where `panel` docks; none while it floats or is hidden. +fn docked_at(ui: &UiState, panel: &str) -> Option<(DockEdge, usize)> { + panel_docking::column_of(panel_docking::layout_of(ui), panel).and_then(|(slot, _)| slot) +} + +/// The window edge toolbar panel `panel` docks at: while docked, its edge; while it floats or is +/// hidden, the edge of the docked panel the dock records it left; else the left edge. +fn last_edge(ui: &UiState, panel: &str) -> DockEdge { + let ws = &ui.dock_workspace; + let left = ws.floated().iter().chain(ws.hidden()).find(|(p, _)| p == panel).and_then(|(_, at)| at.anchor.as_deref()); + docked_at(ui, panel).or_else(|| left.and_then(|anchor| docked_at(ui, anchor))).map_or(DockEdge::Start, |(edge, _)| edge) +} + +/// The `side` param's name of `edge`. +fn side_name(edge: DockEdge) -> &'static str { + if edge == DockEdge::End { "right" } else { "left" } +} + +/// Where toolbar `bar` is: `{toolbar, floating, side, order, pos}`, as `window.toolbar.dock` and +/// `window.toolbar.float` return it. +fn placement(app: &VectorcraftApp, bar: &str) -> Result { + let b = find(&app.ui, bar).ok_or_else(|| format!("no toolbar named `{bar}`"))?; + let panel = panel_id(b.id); + let docked = docked_at(&app.ui, &panel); + let pos = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| [w.rect.min.x, w.rect.min.y]); + Ok(json!({ + "toolbar": b.name, + "floating": docked.is_none(), + "side": side_name(last_edge(&app.ui, &panel)), + "order": docked.map(|(_, n)| n), + "pos": pos, + })) +} + +/// `window.toolbar.dock`: docks the toolbar named `name` as a column of the dock on the `side` edge +/// (omitted: [`last_edge`]), at column `order` from the window edge (omitted: the innermost, or where it +/// is when it docks at that edge already). Bad params are errors and change nothing. +fn dock(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?; + let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone()); + let edge = match p.get("side") { + None | Some(Value::Null) => last_edge(&app.ui, &panel), + // `Start` and `End`, as panels take them, too. + Some(Value::String(s)) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => DockEdge::Start, + Some(Value::String(s)) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => DockEdge::End, + Some(Value::String(s)) => return Err(format!("side is left or right, not `{s}`")), + Some(v) => return Err(format!("side is left or right, not `{v}`")), + }; + // A panel of each other column of that edge's dock, from the window edge inwards. + let others: Vec = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), edge) + .iter() + .filter(|c| !c.panels().any(|q| *q == panel)) + .filter_map(|c| c.panels().next().cloned()) + .collect(); + let order = match p.get("order") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|&n| n <= others.len()) { + Some(n) => Some(n), + None => return Err(format!("order is a whole number from 0 to {}, not `{v}`", others.len())), + }, + }; + let here = docked_at(&app.ui, &panel).filter(|(e, _)| *e == edge).map(|(_, n)| n); + if here.is_none() { + // A new innermost column of that edge's dock; a hidden toolbar shows. + let hidden = !panel_docking::layout_of(&app.ui).contains(&panel); + app.run("window.panel.dock", json!({ "panel": panel, "side": if edge == DockEdge::End { "End" } else { "Start" } }))?; + shown_again(app, id, hidden); + } + let now = docked_at(&app.ui, &panel).map(|(_, n)| n); + if let Some(n) = order.filter(|n| Some(*n) != now) { + let to = match others.get(n) { + Some(anchor) => Target::at(anchor.clone(), DockPlacement::column(false)), + None => match others.last() { + Some(last) => Target::at(last.clone(), DockPlacement::column(true)), + None => return placement(app, &name), + }, + }; + let ctx = app.ui_ctx.clone(); + panel_docking::apply(app, ctx.as_ref(), vec![Action::move_panel(panel, to)])?; + } + // A toolbar where it was asked to go shows too, which ends a Tab hide. + panel_docking::show_panels(app); + placement(app, &name) +} + +/// `window.toolbar.float`: floats the toolbar named `name` with its top-left corner at `x`, `y` in +/// window points (both or neither; neither: where the dock floats a panel, and a floating toolbar +/// stays where it is). +fn float(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?; + let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone()); + let coord = |k: &str| match p.get(k) { + None | Some(Value::Null) => Some(None), + Some(v) => v.as_f64().filter(|f| f.abs() <= 1e6).map(|f| Some(f as f32)), + }; + let at = match (coord("x"), coord("y")) { + (Some(Some(x)), Some(Some(y))) => Some(pos2(x, y)), + (Some(None), Some(None)) => None, + _ => return Err("x and y must both be numbers from -1000000 to 1000000".into()), + }; + let window = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| w.rect); + let hidden = !panel_docking::layout_of(&app.ui).contains(&panel); + match (at, window) { + (Some(at), _) => panel_docking::place_floating(app, &panel, at, window.map_or(0.0, |r| r.width()))?, + (None, None) => { + app.run("window.panel.float", json!({ "panel": panel }))?; + } + (None, Some(_)) => {} + } + shown_again(app, id, hidden); + // A toolbar floating already shows too, which ends a Tab hide. + panel_docking::show_panels(app); + placement(app, &name) +} + +/// After a command showed toolbar `id`, which was `hidden`, the groups torn off it show again, as +/// Show Toolbar brings them back. +fn shown_again(app: &mut VectorcraftApp, id: u32, hidden: bool) { + if hidden && panel_docking::layout_of(&app.ui).contains(&panel_id(id)) { + crate::toolbar::strips_follow(app, &Owner::Toolbar(id), true); + } +} + /// Opens New Toolbar: a name box whose OK is held while the name is refused, the refusal shown under /// the row. fn open_new(app: &mut VectorcraftApp) -> Result<(), String> { @@ -464,6 +591,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option dock(app, p), + "window.toolbar.float" => float(app, p), "window.toolbar.list" => { let layout = panel_docking::layout_of(&app.ui); Ok(json!( @@ -474,7 +603,6 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option>().len(), MAX, "every toolbar has an id of its own"); } + + /// A hidden toolbar that `window.toolbar.dock` or `window.toolbar.float` shows brings back the + /// group torn off it, as Show Toolbar does. + #[test] + fn docking_or_floating_a_hidden_toolbar_brings_back_its_torn_off_group() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "curvature", "toolbar": "Mine", "slot": 0, "place": "group"})).unwrap(); + app.run("window.floatTools", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + let id = find(&app.ui, "Mine").unwrap().id; + let strip = strip_id(&Owner::Toolbar(id), "pen"); + let on = |app: &VectorcraftApp| panel_docking::layout_of(&app.ui).contains(&strip); + assert!(on(&app)); + for (command, params) in [ + ("window.toolbar.dock", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine", "x": 40, "y": 50})), + ] { + app.run("window.toolbar.custom", json!({"name": "Mine", "show": false})).unwrap(); + assert!(!on(&app), "the strip hides with its toolbar"); + app.run(command, params.clone()).unwrap(); + assert!(panel_docking::layout_of(&app.ui).contains(&panel_id(id)), "{command} {params} shows the toolbar"); + assert!(on(&app), "{command} {params} brings the strip back"); + } + } + + /// The dock layout, to compare. + fn layout(app: &VectorcraftApp) -> Value { + serde_json::to_value(panel_docking::layout_of(&app.ui)).unwrap() + } + + /// Where the toolbar named `name` docks: its edge and column from that edge (none: floating). + fn dock_place(app: &VectorcraftApp, name: &str) -> Option<(DockEdge, usize)> { + docked_at(&app.ui, &panel_id(find(&app.ui, name).unwrap().id)) + } + + /// `window.toolbar.dock` docks a toolbar at an edge, innermost or at the column asked for, and + /// `window.toolbar.float` floats it, at x, y when given; bad params and a toolbar already where + /// it is asked to go change nothing, and `window.toolbar.list` reports the same places. + #[test] + fn toolbars_dock_and_float_by_their_commands() { + let mut app = app(); + for name in ["A", "B", "C"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + assert_eq!(dock_place(&app, "A"), None, "New Toolbar floats"); + let undo = app.session.doc().map_or(0, |d| d.history.undo.len()); + let r = app.run("window.toolbar.dock", json!({"name": "a"})).unwrap(); + assert_eq!((&r["toolbar"], &r["floating"], &r["side"], &r["pos"]), (&json!("A"), &json!(false), &json!("left"), &Value::Null)); + let (edge, a) = dock_place(&app, "A").unwrap(); + assert_eq!(edge, DockEdge::Start); + assert_eq!(r["order"], json!(a)); + // Each one docked after it goes inside it; one asked to go at A's column goes outside it. + app.run("window.toolbar.dock", json!({"name": "B", "side": "left"})).unwrap(); + let b = dock_place(&app, "B").unwrap().1; + assert!(b > dock_place(&app, "A").unwrap().1, "B docks inside A"); + let at_a = dock_place(&app, "A").unwrap().1; + app.run("window.toolbar.dock", json!({"name": "C", "side": "start", "order": at_a})).unwrap(); + let [c, a, b] = ["C", "A", "B"].map(|n| dock_place(&app, n).unwrap().1); + assert!(c < a && a < b, "C goes outside A: {c} {a} {b}"); + // Docked again at the edge it docks at, with no column asked for, nothing changes. + let before = layout(&app); + app.run("window.toolbar.dock", json!({"name": "A"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "A", "side": "left", "order": a})).unwrap(); + assert_eq!(layout(&app), before); + // Bad params are errors and change nothing. + let columns = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), DockEdge::Start).len(); + for p in [ + json!({"name": "A", "side": "top"}), + json!({"name": "A", "side": 1}), + json!({"name": "A", "order": columns}), + json!({"name": "A", "order": -1}), + json!({"name": "A", "order": 0.5}), + json!({"name": "A", "order": "1"}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.dock", p.clone()).is_err(), "{p}"); + } + for p in [ + json!({"name": "A", "x": 10}), + json!({"name": "A", "x": 1e7, "y": 0}), + json!({"name": "A", "x": "1", "y": 2}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.float", p.clone()).is_err(), "{p}"); + } + assert_eq!(layout(&app), before); + // The innermost column asked for: A moves inside B. + app.run("window.toolbar.dock", json!({"name": "A", "order": columns - 1})).unwrap(); + assert!(dock_place(&app, "A").unwrap().1 > dock_place(&app, "B").unwrap().1); + // At the right edge. + let r = app.run("window.toolbar.dock", json!({"name": "A", "side": "RIGHT"})).unwrap(); + assert_eq!(r["side"], json!("right")); + assert_eq!(dock_place(&app, "A").map(|(e, _)| e), Some(DockEdge::End)); + // Floated, it remembers the right edge, and docks there again. + let r = app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!((&r["floating"], &r["side"], &r["order"]), (&json!(true), &json!("right"), &Value::Null)); + assert!(r["pos"].is_array()); + let listed = app.run("window.toolbar.list", json!({})).unwrap(); + let a_row = listed.as_array().unwrap().iter().find(|t| t["name"] == "A").unwrap().clone(); + assert_eq!((&a_row["floating"], &a_row["side"]), (&json!(true), &json!("right"))); + // Floating already, with no x, y: it stays where it is. + let before = layout(&app); + app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!(layout(&app), before); + let r = app.run("window.toolbar.float", json!({"name": "A", "x": 300, "y": 200})).unwrap(); + assert_eq!(r["pos"], json!([300.0, 200.0])); + assert_eq!(app.run("window.toolbar.dock", json!({"name": "A"})).unwrap()["side"], json!("right")); + // A hidden toolbar shows where it is docked or floated to. + app.run("window.toolbar.custom", json!({"name": "B", "show": false})).unwrap(); + app.run("window.toolbar.float", json!({"name": "B", "x": 50, "y": 60})).unwrap(); + assert!(panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel_id(find(&app.ui, "B").unwrap().id)).is_some()); + // Neither command records an undo step. + assert_eq!(app.session.doc().map_or(0, |d| d.history.undo.len()), undo); + } } diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs index 859d7752f6..36fab4b2a1 100644 --- a/crates/ui-egui/src/dialogs/color_group_options.rs +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -32,7 +32,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let key = "group"; let group = match p.get(key) { Some(Value::String(g)) => g.clone(), - None | Some(Value::Null) => crate::panels::swatches::sole_selected_group(app).ok_or("missing `group`")?, + None | Some(Value::Null) => { + crate::panels::swatches::sole_selected_group(app).ok_or("select a color group in the Swatches panel, or pass group")? + } Some(_) => return Err(format!("`{key}` must be a string")), }; let st = app.session.active().ok_or("no document open")?; diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..e0ad66addf 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -6,7 +6,8 @@ //! `artboard.setProps {index, color}`. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog -//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's +//! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor +//! Artwork shows the library that Limit to Library limits to. The OK for a Save for Web colour table cell shifts the cell's //! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, @@ -104,7 +105,7 @@ pub(crate) fn open_picker(app: &VectorcraftApp) -> Option { /// The document's swatches and the swatch libraries as the picker's Color Swatches view: solid /// colours only, tints as their colour. -fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { +pub(crate) fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { let solid = |swatches: &[vectorcraft_color::Swatch]| -> Vec<(Label, Srgba)> { swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect() }; @@ -124,6 +125,15 @@ fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")) } +/// The index in [`swatch_view`]'s libraries of the library a Limit to Library key names +/// (`"document"` or a library id); `None` when the view does not list it. +fn library_index(app: &VectorcraftApp, limit: &str) -> Option { + if limit == swatchlib::DOCUMENT_SWATCHES { + return Some(0); + } + colour_libraries(app).iter().position(|lib| lib.id == limit).map(|i| i + 1) +} + /// The working CMYK profile as the picker's CMYK converter, so its CMYK fields follow the document's /// inks; `None` (the picker's built-in coated CMYK) when the profile can't link to sRGB. fn working_cmyk() -> Option { @@ -204,8 +214,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { while let Some((parent, request)) = dialogs.with(|h| h.take_color_request()) { let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }); let key = request.key.clone(); - let child = ColorPickerDialog::from_request(request).eyedropper(true).add_to_swatches(false).gamut(gamut(app)).working_rgb(WorkingRgb); + let library = super::recolor::limit_to(&dialogs, parent).and_then(|limit| library_index(app, &limit)); + let child = ColorPickerDialog::from_request(request) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); let id = dialogs.with(|h| h.open_child(child, parent)); + // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. + if let Some(i) = library + && let Err(e) = dialogs.with(|h| h.set_json_field(ctx, id, "library", json!(i))) + { + app.status(e); + } app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() }); } let busy = app.screen_pick.busy(); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 12e13a36b3..72fb9a40a6 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -100,8 +100,7 @@ wrapped_dialog!(Question, StandardPrompt, KIND); pub(crate) struct Message(HostedAlert); wrapped_dialog!(Message, HostedAlert, MESSAGE); -/// The Type tool's question whether to edit type set in fonts that aren't available; its tag is the -/// tool's edit token. +/// The Type tool's question whether to edit type set in fonts that aren't available. pub(crate) struct MissingFontQuestion(StandardPrompt); wrapped_dialog!(MissingFontQuestion, StandardPrompt, MISSING_FONT_EDIT); @@ -215,13 +214,15 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str /// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog /// stays and the Type tool forgets the edit, as Cancel would. pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { - let token = p.get("token").cloned().unwrap_or(Value::Null); + let Some(token) = p.get("token").and_then(Value::as_u64) else { + return; + }; let Some(dialogs) = app.dialogs() else { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; }; if app.any_dialog_open() && !dialogs.with(|host| host.is_open::()) { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; } let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); @@ -234,14 +235,18 @@ pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { let prompt = StandardPrompt::custom(tl!("Edit type set in fonts that aren't available?")) .paragraph(detail) .button(PromptChoice::Proceed, tl!("OK")) - .button(PromptChoice::Cancel, tl!("Cancel")) - .tag(token); - dialogs.with(|host| host.open(MissingFontQuestion(prompt))); + .button(PromptChoice::Cancel, tl!("Cancel")); + dialogs.with(|host| { + host.open(MissingFontQuestion(prompt)); + // Replacing a prompt leaves its Cancel in the host. The tool is already waiting on the new token. + let _ = host.take::(); + }); + app.missing_font_edit_token = Some(token); } /// Give the Type tool the answer to [`ask_missing_font_edit`]'s question about the edit `token` /// names: with `ok` the edit starts at once; without, the tool forgets it. -pub(crate) fn answer_missing_font_edit(app: &mut VectorcraftApp, token: &Value, ok: bool) { +fn answer_missing_font_edit(app: &mut VectorcraftApp, token: u64, ok: bool) { app.session.set_tool_option("missingFontEdit", &json!({"token": token, "ok": ok})); if ok { let r = app.session.tool_poll(app.view_info(), false); @@ -277,13 +282,12 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { let Some(dialogs) = app.dialogs() else { return; }; - let (ok, token) = match dialogs.with(|host| host.take::()) { - None => return, - Some(DialogResult::Ok(mut answer)) => (answer.choice == PromptChoice::Proceed, answer.take_tag::()), - // PLAN: a question the host cancelled carries no tag, so the tool's token is unknown here. - Some(_) => (false, None), - }; - answer_missing_font_edit(app, &token.unwrap_or(Value::Null), ok); + if let Some(result) = dialogs.with(|host| host.take::()) + && let Some(token) = app.missing_font_edit_token.take() + { + let ok = matches!(result, DialogResult::Ok(answer) if answer.choice == PromptChoice::Proceed); + answer_missing_font_edit(app, token, ok); + } } /// The confirmation open now, if one is: its message and detail as shown, and the command OK runs. diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 9c2a03ad10..6eb3d2702c 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -115,21 +115,51 @@ fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { if let Some(k) = f.text("kind") { p["kind"] = json!(k); } - if let Some(mut r) = f.number("radius") { - if relative { - let id = NodeId(json_field(f, "id").as_u64().unwrap_or(0)); - let st = app.session.active().ok_or("no document")?; - if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) { - let corners: BTreeSet = serde_json::from_value(json_field(f, "corners")).unwrap_or_default(); - if let Some(k) = corners.iter().next() { - let max = lc.corner(*k).map(|c| c.max_radius()).unwrap_or(0.0); - r = (r / 100.0).clamp(0.0, 1.0) * max; - } + let Some(r) = f.number("radius") else { + return app.run("object.setLiveShape", p).map(|_| ()); + }; + if !relative { + p["radius"] = json!(r); + return app.run("object.setLiveShape", p).map(|_| ()); + } + // Relative: the percentage is of each corner's own maximum, so corners with different + // maximums (a star's points and its inner corners) get different lengths. Corners of the + // same length share one `object.setLiveShape`; several run as one undo step. + let id = NodeId(json_field(f, "id").as_u64().unwrap_or(0)); + let st = app.session.active().ok_or("no document")?; + let mut lengths: Vec<(f64, Vec)> = vec![]; + if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) { + let corners: BTreeSet = serde_json::from_value(json_field(f, "corners")).unwrap_or_default(); + for k in corners { + let len = (r / 100.0).clamp(0.0, 1.0) * lc.corner(k).map(|c| c.max_radius()).unwrap_or(0.0); + match lengths.iter_mut().find(|(l, _)| (*l - len).abs() < 1e-9) { + Some((_, ks)) => ks.push(k), + None => lengths.push((len, vec![k])), } } - p["radius"] = json!(r); } - app.run("object.setLiveShape", p).map(|_| ()) + match &lengths[..] { + [] => { + p["radius"] = json!(r); + app.run("object.setLiveShape", p).map(|_| ()) + } + [(len, _)] => { + p["radius"] = json!(len); + app.run("object.setLiveShape", p).map(|_| ()) + } + _ => { + let commands: Vec = lengths + .iter() + .map(|(len, ks)| { + let mut step = p.clone(); + step["corners"] = json!(ks); + step["radius"] = json!(len); + json!({"command": "object.setLiveShape", "params": step}) + }) + .collect(); + app.run("command.batch", json!({"label": "Live Shape", "commands": commands})).map(|_| ()) + } + } } #[cfg(test)] @@ -277,4 +307,38 @@ mod tests { assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))); assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0)); } + + /// Relative rounding gives each corner the percentage of its own maximum: a star's point and + /// the inner corner beside it differ, and OK rounds both as one undo step. + #[test] + fn relative_radius_is_a_percentage_of_each_corners_own_maximum() { + let (mut app, _) = app(); + let id = app.run("shape.star", json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("object.setLiveShape", json!({"id": id, "radius": 1})).unwrap(); + let lc = |app: &VectorcraftApp| { + let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone(); + let c = LiveCorners::of(&n).unwrap(); + (c.radii_relative(), c.radius(0), c.radius(1), c.corner(0).unwrap().max_radius(), c.corner(1).unwrap().max_radius()) + }; + let (_, _, _, max0, max1) = lc(&app); + assert!((max0 - max1).abs() > 1.0, "the corners' maximums differ: {max0} and {max1}"); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let n = steps(&app); + app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap(); + set(&app, "radii", json!("relative")); + set(&app, "radius", json!(50)); + confirm(&mut app); + assert!(!is_open(&app)); + let (relative, f0, f1, _, _) = lc(&app); + assert!(relative); + assert!((f0 - 0.5).abs() < 1e-9 && (f1 - 0.5).abs() < 1e-9, "stored fractions: {f0} and {f1}"); + assert_eq!(steps(&app), n + 1, "one undo step"); + // The same values again change nothing and record no step. + app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap(); + set(&app, "radius", json!(50)); + confirm(&mut app); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(!lc(&app).0, "undo brings back absolute radii"); + } } diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 805a502223..b53bab2351 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -718,7 +718,8 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); - let picker = dialogs.with(|host| host.open(ColorPickerDialog::from_request(request))); + let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app)); + let picker = dialogs.with(|host| host.open(picker)); app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) }); } Row::new().show(ui, |ui, _| { diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0d28e683a2..195d2759f9 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -389,7 +389,14 @@ fn grid_colors_row(setup: DocSetup) -> Param { picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + let number = (i + 1).to_string(); + let template = tl!("Grid Colors: {number}"); + let name = if template == "Grid Colors: {number}" { + // Keep the translated prefix for catalogs that have yet to add the complete label. + format!("{} {number}", tl!("Grid Colors:")) + } else { + crate::i18n::fmt(template, &[("number", &number)]) + }; let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index bcfecb47e1..97dc95426d 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -69,6 +69,26 @@ pub(crate) struct Open { asking: bool, } +/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog. +pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) { + let Some(open) = app.effect_dialogs.effect.as_ref() else { return }; + if id != open.id || open.asking || !vectorcraft_effects::takes_blend_mode(&open.cx.id, "mode") { + return; + } + let normalize = |field: &mut Value| { + if field["field"] == "mode" + && let Some(mode) = field["value"].as_str().and_then(vectorcraft_effects::parse_blend_mode) + { + field["value"] = json!(vectorcraft_effects::blend_mode_id(mode)); + } + }; + if let Some(fields) = params.get_mut("fields").and_then(Value::as_array_mut) { + fields.iter_mut().for_each(normalize); + } else { + normalize(params); + } +} + /// `effect.dialog {effect, index?, item?}`: edit applied effect `index` of `item` (null: the /// object's effects; omitted: the active item's, else the object's) prefilled with its values, /// or add `effect`, first asking when that list already has it. @@ -561,6 +581,21 @@ mod tests { assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value"); } + /// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size + /// with Relative, a share of the object's size, shows one. + #[test] + fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() { + use craft::ui::runtime::env::UnitKind; + let app = app(); + for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] { + let cx = EffectCx::new(&app, effect, false); + let rows = super::super::effect_rows::distort(&cx, &DialogFields::new()); + let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit); + assert_eq!(unit(key), Some(None), "{effect} {key}"); + assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size"); + } + } + /// The lists the dialogs draw hold the values the effect's parameter documentation lists, in /// its order; Rasterize's Color Model names the document's mode first. #[test] diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 06bf617898..ef5b2a5ea4 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -150,6 +150,11 @@ fn generic_row(cx: &EffectCx, key: &str, default: &Value, relative: bool) -> Opt Param::number(key, label, n, 1.0, 2) } } + // The blend mode the effect draws in: the mode it draws a name in, Normal for one it doesn't know. + Value::String(text) if vectorcraft_effects::takes_blend_mode(id, key) => { + let mode = vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(text)); + Param::new(key, label, ParamKind::blend(crate::fields::effect_blend_modes(), Some(mode))) + } Value::String(text) => match options() { Some(list) => Param::new(key, label, ParamKind::choice(list, Some(text.clone()))), None if text.starts_with('#') => Param::new(key, label, ParamKind::color(None)), diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index 580036d430..ef91055575 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -36,7 +36,12 @@ fn data_label(text: &str) -> Label { /// A whole-number slider row over `0..=100` percent. fn percent_range(key: &str, label: Label, default: f64) -> Param { - Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent) + count_range(key, label, default).unit(UnitKind::Percent) +} + +/// A whole-number slider row over `0..=100` with no unit after the number. +fn count_range(key: &str, label: Label, default: f64) -> Param { + Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0) } /// The row of `key` for either unit of a Relative/Absolute pair: a share of the object's size, or a distance in the @@ -82,7 +87,7 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec { pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec { let roughen = cx.id == "distort.roughen"; // PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it - let second = if roughen { percent_range("detail", lbl!("Detail:"), 10.0) } else { percent_range("ridges", lbl!("Ridges per segment:"), 4.0) }; + let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) }; let points: Vec<(String, Label)> = choices(&cx.id, "points") .unwrap_or_default() .iter() diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 6d81d18214..be7cf18a3b 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -171,6 +171,13 @@ fn field_value(row: Option<&Param>, value: &Value) -> Option { }, // A pair of radio buttons over a flag (Relative / Absolute): the ids are "true" and "false". Some(ParamKind::Radio { .. }) if value.is_boolean() => value.as_bool().map(|b| FieldValue::Text(b.to_string())), + // Use the renderer's mode for each spelling, including Normal for unknown names and the effect's default for + // a legacy value that is not text. + Some(ParamKind::Blend { default, .. }) => value + .as_str() + .map(|s| vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(s))) + .or_else(|| default.clone()) + .map(FieldValue::Text), // A custom row's list, and one a key no row has carries through (an export's `artboards: [0, 1]`), stay JSON: a // list of whole numbers would read back as a grid, and one of two or three as a point or colour. Some(ParamKind::Custom(_)) | None if value.is_array() => Some(FieldValue::Json(value.clone())), @@ -298,7 +305,10 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param { // there. Past it, the number typed is read as an integer. const EXACT: i64 = 1 << 53; let start = (*default).max(*min).min(*max); - if -EXACT <= *min && *max <= EXACT { + if let Some(range) = p.ui.slider_range(&p.spec) { + // A slider over the whole numbers of the range, as the framework's range row with no decimals. + Param::new(key, name, ParamKind::range(*range.start(), *range.end(), start as f64, SliderScale::Linear)).decimals(0) + } else if -EXACT <= *min && *max <= EXACT { Param::new(key, name, ParamKind::int(Some(*min), Some(*max), start)) } else { let (min, max) = (*min, *max); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 85bb9503c1..2ac4764bf5 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -712,7 +712,6 @@ impl StackDialog for GraphDataDialog { .ok_label(tl!("Apply")) .ok_enabled(!held.is_waiting()) .accept_stays_open(true) - .enter_confirms(false) // The sheet owns the scroll; the controls above it stay in view. .collection_body(true) .shaped(|dialog| dialog.initial_focus(Initial::Default)) @@ -1015,6 +1014,41 @@ mod tests { assert!(app.dialogs().is_some_and(|d| d.with(|host| host.is_open::()))); } + /// Enter in the entry box and in the sheet moves the picked cell down and applies nothing. Enter in a field that + /// does not use it is Apply: the graph is redrawn and the window stays open. + #[test] + fn enter_moves_in_the_entry_box_and_the_sheet_and_applies_elsewhere() { + let (mut app, id) = app_with(",a,b\nQ1,1,2\nQ2,3,4\nQ3,5,6", "column"); + let before = data(&mut app, id); + open(&mut app).unwrap(); + set_field(&app, "sel", json!([1, 1])).unwrap(); + let mut h = harness(app); + h.run_steps(4); + // The entry box. + h.get_by_label("Cell Value").click(); + h.run_steps(2); + edit(h.state(), |d| d.entry.text = "9".into()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(read(h.state(), |d| (active(&d.state), cell_of(&d.sheet.grid, 1, 1))), ((2, 1), "9".to_string()), "Enter moves down"); + assert_eq!(data(h.state_mut(), id), before, "Enter in the entry box applies nothing"); + // The sheet. + h.get_by_label("Q1").click(); + h.run_steps(2); + assert_eq!(read(h.state(), |d| active(&d.state)), (1, 0), "the click picks the cell"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(read(h.state(), |d| active(&d.state)), (2, 0), "Enter moves down in the sheet"); + assert_eq!(data(h.state_mut(), id), before, "Enter in the sheet applies nothing"); + // A field that does not use Enter. + h.get_by_label("Column Width").click(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(4); + assert_eq!(data(h.state_mut(), id)["rows"][0][0], json!(9.0), "Enter applies the sheet"); + assert!(h.state().dialogs().is_some_and(|d| d.with(|host| host.is_open::())), "the window stays open"); + } + #[test] fn the_entry_box_writes_its_text_and_moves_the_picked_cell() { let (mut app, id) = app_with(",a,b\nQ1,1,2", "column"); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 1aac4c28b8..6eb690989d 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -361,10 +361,11 @@ impl KinsokuDialog { let rows: Vec> = list.iter().map(|s| PresetRow::item(name_of(s).to_owned(), name_of(s), 0)).collect(); let mut value = list.get(self.index(list.len())).map(|s| name_of(s).to_owned()); let suggestion = new_name(&list, &self.opened); - // PLAN: PresetPicker has no placeholder: an empty list shows an empty name field, not "None". let source = PresetSource::listed(&rows); let refuses = |typed: &str| name_problem(&list, typed); - let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)).field(PickerField::Name); + let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)) + .field(PickerField::Name) + .placeholder(tl!("None")); let out = NamedPresetRow::new(tl!("Kinsoku Set"), picker).suggest_name(suggestion).check_name(NameCheck::of_host(&refuses)).show(ui); self.apply(out.events); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index f39cf6d596..887dbbc202 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -47,6 +47,21 @@ fn cancel(app: &VectorcraftApp) { app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); } +#[test] +fn empty_kinsoku_list_shows_none_in_the_preset_picker() { + let mut fixture = craft::ui::testing::Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); + fixture.room(egui::vec2(800.0, 600.0)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + open(&mut app).unwrap(); + fixture.settle(); + + let picker = fixture.by_label("Kinsoku Set").expect("Kinsoku Set picker"); + assert_eq!(fixture.tree().value_of(picker.node), Some("None")); + assert!(picked(&app).is_empty(), "the caption does not select a set"); +} + /// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its /// categories edited in their fields and Add putting in a character by its code point; nothing /// changes until OK, which sets them as one undo step; Cancel leaves them. diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index f45d77ab38..a76bdedd7a 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -35,7 +35,7 @@ use craft::ui::pickers::Select; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::sections::Section; -use craft::ui::text::{LinkMode, LinkedFields, NumberField}; +use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; use super::host::open_held; use crate::VectorcraftApp; @@ -329,6 +329,7 @@ impl DocumentSettings for VcNewDocument { let captions = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))]; let out = LinkedFields::<4>::new(bleed.clone(), Bind::given(parts), Bind::bound(&mut linked)) .mode(LinkMode::Equal) + .layout(LinkedLayout::Columns) .captions(captions) .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) .lengths(lengths) @@ -877,6 +878,39 @@ mod tests { assert_eq!(fields(&app)["name"], json!("Untitled-2")); } + /// The four Bleed fields stay inside the dialog in a 1280 by 900 window; in one row, Right ran past the dialog's + /// right edge. + #[test] + fn bleed_fields_stay_inside_the_dialog() { + let mut app = app(); + open(&mut app); + let ctx = ctx(&app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + // Each frame gives the app's input once, as the hosts do. + let frame = |app: &mut VectorcraftApp, i: u32| { + let mut raw = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() }; + app.adopt_context(&ctx); + app.raw_input(&ctx, &mut raw); + craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out)); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + out.textures_delta.clear(); + out + }; + (0..3).for_each(|i| drop(frame(&mut app, i))); + let out = frame(&mut app, 3); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: Option<&str>, role: egui::accesskit::Role| { + let found = nodes.iter().find(|(_, n)| n.role() == role && label.is_none_or(|l| n.label() == Some(l))); + let (_, n) = found.unwrap_or_else(|| panic!("no {role:?} {label:?}")); + n.bounds().expect("bounds") + }; + let dialog = bounds(None, egui::accesskit::Role::Dialog); + for side in ["Top", "Bottom", "Left", "Right"] { + let field = bounds(Some(side), egui::accesskit::Role::SpinButton); + assert!(dialog.x0 <= field.x0 && field.x1 <= dialog.x1, "Bleed {side} {field:?} stays inside the dialog {dialog:?}"); + } + } + /// More Settings edits only the artboard layout, spacing and columns, and creates nothing. #[test] fn more_settings_is_a_popup_holding_only_the_artboard_layout() { diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 119228b39f..04e86b346d 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -15,7 +15,10 @@ use std::sync::Arc; +use craft::ui::buttons::Button; +use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::dialog::DialogResult; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesTab, PropertyRow}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value, json}; @@ -599,8 +602,6 @@ fn seed_editors(fields: &mut DialogFields) { } } -// PLAN: the stop list is a Select over the stops and the buttons are egui buttons: the List and button -// components' signatures are not in the bundle. /// The Add, Delete Tab and Clear All Tabs buttons, which also keep the editors and the stop they edit in step. fn tabs_buttons(unit: Unit) -> Param { Param::custom("tabs", tl!("Tabs"), move |ui, fields, _| { @@ -608,10 +609,10 @@ fn tabs_buttons(unit: Unit) -> Param { let (rows, _, _) = tab_rows(fields); let can_add = new_tab_position(&rows, unit).is_some(); let (mut add, mut delete, mut clear) = (false, false, false); - let line = ui.horizontal(|ui| { - add = ui.add_enabled(can_add, egui::Button::new(tl!("Add"))).clicked(); - delete = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Delete Tab"))).clicked(); - clear = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Clear All Tabs"))).clicked(); + let line = Row::new().show(ui, |ui, _| { + add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui)); + delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui)); + clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui)); }); if add { add_tab(fields, unit); @@ -621,7 +622,7 @@ fn tabs_buttons(unit: Unit) -> Param { clear_tabs(fields); } seed_editors(fields); - line.response + line.output }) .companions(["__tabSel", "__tabEdited", "__tabShown", "__tabAlign", "__tabPosition", "__tabLeader", "__tabAlignOn"]) } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 72fb260ee2..64176e93ac 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -5,12 +5,16 @@ // PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). -use craft::ui::contract::{Bind, FieldLabelRole, Show as _, ShowContainer as _, SideLabel}; +use craft::behavior::ColumnWidth; +use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::DialogId; use craft::ui::display::Text; use craft::ui::form::Field; +use craft::ui::layout::GridFit; +use craft::ui::layout_components::Grid; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; +use craft::ui::runtime::measure; use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft::ui::text::{NumberField, NumberOutput}; use craft::ui::value_drag::SliderScale; @@ -30,6 +34,10 @@ use crate::VectorcraftApp; /// sends 180° less the threshold: 150° sends `object.path.simplify`'s default of 30°. pub(crate) const ANGLE_THRESHOLD: f64 = 150.0; +/// Split Into Grid's two columns, each as wide as its fields: the rows on the left, the columns on the right. The +/// grid keeps both columns in a narrow dialog. +const AXES: [ColumnWidth; 2] = [ColumnWidth::Content; 2]; + /// Simplify's tolerance when the dialog opens from the menu, in points. const DEFAULT_TOLERANCE: f64 = 1.0; @@ -175,7 +183,7 @@ pub(crate) fn split_fields(width: f64, height: f64) -> DialogFields { fn cell(ui: &mut egui::Ui, label: &'static str, name: String, describes: bool, value: f64, lengths: Option) -> Option { let role = if describes { FieldLabelRole::Describes } else { FieldLabelRole::Names }; let mut edited = None; - Field::new(label).side(SideLabel::new().role(role)).show(ui, |ui, _| { + Field::new(label).side(SideLabel::new().role(role)).id_salt(name.as_str()).show(ui, |ui, _| { let bind = Bind::given(Some(value)); let out: NumberOutput = match lengths { Some(l) => NumberField::length(name.clone(), bind, l).show(ui), @@ -194,41 +202,45 @@ fn split_grid(ui: &mut egui::Ui, f: &mut DialogFields, lengths: LengthUnits) -> ("rows", tl!("Rows:"), tl!("Height:"), "rowGutter", "totalHeight", 2.0), ("columns", tl!("Columns:"), tl!("Width:"), "columnGutter", "totalWidth", 2.0), ]; - egui::Grid::new("split-grid") - .num_columns(2) - .show(ui, |ui| { - for (number, label, _, _, _, default) in axes { - let n = f.number(number).unwrap_or(default); - if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { - f.set(number, v); - } + // The grid can run its body twice in a pass, so the body edits a copy, kept only from the run that takes effect. + let before = f.clone(); + let mut edited = None; + let shown = Grid::new(&AXES).fit(GridFit::Fixed).id_salt("split-grid").show(ui, |ui, _| { + let mut f = before.clone(); + for (number, label, _, _, _, default) in axes { + let n = f.number(number).unwrap_or(default); + if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { + f.set(number, v); } - ui.end_row(); - for (number, _, label, gutter, total, default) in axes { - let n = f.number(number).unwrap_or(default).max(1.0); - let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); - let size = (f.number(total).unwrap_or(0.0) - gaps) / n; - if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) { - f.set(total, n * v + gaps); - } + } + for (number, _, label, gutter, total, default) in axes { + let n = f.number(number).unwrap_or(default).max(1.0); + let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); + let size = (f.number(total).unwrap_or(0.0) - gaps) / n; + if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) { + f.set(total, n * v + gaps); } - ui.end_row(); - for (_, axis, _, gutter, _, _) in axes { - let label = tl!("Gutter:"); - if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { - f.set(gutter, v); - } + } + for (_, axis, _, gutter, _, _) in axes { + let label = tl!("Gutter:"); + if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { + f.set(gutter, v); } - ui.end_row(); - for (_, axis, _, _, total, _) in axes { - let label = tl!("Total:"); - if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { - f.set(total, v); - } + } + for (_, axis, _, _, total, _) in axes { + let label = tl!("Total:"); + if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { + f.set(total, v); } - ui.end_row(); - }) - .response + } + if measure::effect(ui.ctx(), "Split Into Grid's fields edit their values") { + edited = Some(f); + } + }); + if let Some(edited) = edited { + *f = edited; + } + shown.output } /// Split Into Grid's rows: the grid and Add Guides. diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index 1afd7dafbf..bed5ab085b 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -482,7 +482,6 @@ impl StackDialog for GridDialog { .opened(Bind::bound(&mut self.open)) .ok_enabled(finish || !self.held.is_waiting()) .accept_stays_open(true) - .enter_confirms(false) .show(ui, |ui, form, draft| { if finish { form.request_close_as(CloseReason::Activated); diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 954aaac274..3a69a42763 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -1,7 +1,7 @@ //! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced), //! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image //! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither, -//! transparency and matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options +//! transparency and its dither, matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options //! ([`super::psd_options`]). Fields //! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the //! dialog's. @@ -43,6 +43,8 @@ const IMAGE_MAP_LABELS: [&str; 3] = ["None", "Client-side (.html)", "Server-side /// Matte param values and their labels (`Other`: a colour). const MATTES: [&str; 3] = ["none", "white", "black"]; const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"]; +/// The Transparency Dither labels, in [`Dither::ALL`] order. +const TRANSPARENCY_DITHER_LABELS: [&str; 4] = ["No Transparency Dither", "Diffusion", "Pattern", "Noise"]; /// JPEG quality on the dialog's 0–10 scale: the band each step falls in. const QUALITY_BANDS: [&str; 11] = ["Low", "Low", "Low", "Medium", "Medium", "Medium", "High", "High", "Maximum", "Maximum", "Maximum"]; /// WebP compression labels: `lossless` true, then false. @@ -135,6 +137,8 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map { ("dither".into(), json!(p.dither.id())), ("ditherAmount".into(), json!(p.dither_amount)), ("transparency".into(), json!(p.transparency)), + ("transparencyDither".into(), json!(p.transparency_dither.id())), + ("transparencyDitherAmount".into(), json!(p.transparency_dither_amount)), ("matte".into(), json!(MATTES[1])), ("interlaced".into(), json!(false)), ]); @@ -345,7 +349,8 @@ fn webp_rows() -> Vec { } /// The PNG-8 and GIF Options rows: the palette (reduction, colours, dither and amount), -/// transparency and matte, interlacing. +/// transparency and matte, interlacing, and Transparency Dither with the amount Diffusion uses +/// (both disabled while Transparency is off, keeping their values). fn palette_rows() -> Vec { let dithering = Dither::ALL.iter().copied().filter(|d| *d != Dither::None).map(Dither::id); vec![ @@ -355,6 +360,11 @@ fn palette_rows() -> Vec { Param::new("ditherAmount", tl!("Dither Amount:"), ParamKind::int(Some(0), Some(100), 100)).enabled_when_in("dither", dithering), color_choice("matte", tl!("Matte:"), &MATTES, &MATTE_LABELS, |_| 0), check("transparency", tl!("Transparency"), true), + choice("transparencyDither", tl!("Transparency Dither:"), &Dither::ALL.map(Dither::id), &TRANSPARENCY_DITHER_LABELS) + .enabled_when("transparency", true), + Param::new("transparencyDitherAmount", tl!("Transparency Dither Amount:"), ParamKind::int(Some(0), Some(100), 100)) + .visible_when("transparencyDither", Dither::Diffusion.id()) + .enabled_when("transparency", true), check("interlaced", tl!("Interlaced"), false), ] } diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index c65dc15f45..60bf25a04a 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -54,17 +54,22 @@ impl LivePreview { if !app.session.in_interaction() { return app.run(cmd, params); } - let v = app.session.preview(cmd, ¶ms).map_err(|e| e.to_string())?; - let r = app.session.commit_interaction().map(|_| Value::Null).map_err(|e| e.to_string()); - if r.is_ok() - && let Some(w) = v.get("warning").and_then(Value::as_str) - { - app.status(w.to_string()); + let result = app.session.preview(cmd, ¶ms).and_then(|answer| { + app.session.commit_interaction()?; + Ok(answer) + }); + let answer = match result { + Ok(answer) => answer, + Err(error) => { + self.cancel(app); + return Err(error.to_string()); + } + }; + if let Some(warning) = answer.get("warning").and_then(Value::as_str) { + app.status(warning.to_string()); } - if r.is_ok() { - crate::plugin_runs::show_notice(app, cmd, &v); - } - r + crate::plugin_runs::show_notice(app, cmd, &answer); + Ok(Value::Null) } /// Cancel: rolls a shown preview back. @@ -106,6 +111,31 @@ mod tests { } } + #[test] + fn refused_confirmation_restores_the_art_and_ends_the_preview() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + let original = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + let mut preview = LivePreview::default(); + let fill = json!({"color": "#00a000"}); + assert!(matches!(preview.run(&mut app, true, "Fill Color", "paint.setFill", &fill), Some(Ok(_)))); + assert_ne!(app.session.doc().unwrap().doc, original); + assert!(preview.commit(&mut app, "paint.setFill", json!({"color": true})).is_err()); + assert!(!app.session.in_interaction(), "the refused edit left no open interaction"); + assert_eq!(app.session.doc().unwrap().doc, original); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + let mut next = LivePreview::default(); + assert!(matches!(next.run(&mut app, true, "Next Fill", "paint.setFill", &fill), Some(Ok(_)))); + next.commit(&mut app, "paint.setFill", fill).unwrap(); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Next Fill"); + } + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts /// from it; the status bar shows the warning of the typing's preview that keeping it applied. #[test] diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index c219fe1eed..e9c0760844 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1621,6 +1621,12 @@ fn preview_params(d: &Fields) -> Option<(bool, &'static str, Value)> { }) } +/// The Limit to Library key (`"document"` or a library id) of `parent` when it is a Recolor Artwork +/// dialog that limits to a library: the library a Color Picker over it shows in its swatches view. +pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: DialogId) -> Option { + dialogs.with(|host| host.get_by_id::(parent).map(|d| d.fields.str("limitTo"))).filter(|limit| !limit.is_empty()) +} + /// Runs the open dialog's live preview with `(on, command, params)`. fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; @@ -1851,10 +1857,7 @@ impl RecolorDialog { let mut preview = self.fields.bool("preview"); let footer = ResetFooter::new(ui, None, true); let RecolorDialog { fields, feed, filed, ends, row_menu, .. } = self; - // PLAN: Enter is not OK here: a form whose OK stays open closes on Enter without reporting it as its OK - // (form_dialogs/form.rs:429, :534), which would close a held dialog unanswered; the forms owner makes - // `FormDialog` report Enter as the pick of OK when `accept_stays_open` is on. - let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).enter_confirms(false).ok_enabled(!waiting); + let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).ok_enabled(!waiting); if art { form = form.preview(Some(Bind::bound(&mut preview))); } diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index a773d34093..b254285a5b 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -103,6 +103,11 @@ impl Recolor { self } + /// The widget that has the keyboard focus. + pub(crate) fn focused(&self) -> Option { + self.fixture.focused() + } + /// Sets `field` as `ui.dialog.set` does, before the next frame; a refused value leaves the /// dialog as it was. pub(crate) fn set(&mut self, field: &str, value: Value) -> Result<(), String> { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a20c8c720b..edc9953497 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -175,8 +175,13 @@ impl Rows<'_> { self.defaults.get(key).and_then(Value::as_f64).unwrap_or(0.0) } - fn range(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32, unit: UnitKind) -> Param { - Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).unit(unit).resettable() + fn range(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32, unit: UnitKind) -> Param { + self.plain(key, label, range, decimals).unit(unit) + } + + /// A slider over a number shown with no unit after it, such as a count. + fn plain(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32) -> Param { + Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).resettable() } fn degrees(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32) -> Param { @@ -273,7 +278,7 @@ fn object_rows(data: &Data, rows: &Rows, effect: &str, place: Place) -> Vec Param { let defaults = bevel_defaults(); let keys: Vec = defaults.keys().cloned().collect(); Param::custom("__bevelHeading", c3("Bevel"), move |ui, fields, _| { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(c3("Bevel")).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if pressed(ui, tl!("Reset"), differs_from(fields, &defaults), None) { - defaults.iter().for_each(|(k, v)| set_value(fields, k, v)); - } - }); - }) - .response + let mut reset = false; + let changed = differs_from(fields, &defaults); + let shown = crate::panels::section(c3("Bevel")) + .id_salt("bevel") + .controls(|ui, _| reset = pressed(ui, tl!("Reset"), changed, None)) + .show(ui, |_, _| {}); + if reset { + defaults.iter().for_each(|(k, v)| set_value(fields, k, v)); + } + shown.output.response }) .companions(keys) .full_width() @@ -413,7 +419,7 @@ fn differs_from(fields: &DialogFields, defaults: &serde_json::Map /// Revolve's Rotation page: shape, view and the advanced settings. fn revolve_rows(rows: &Rows, effect: &str, place: Place) -> Vec { - let mut advanced = vec![rows.range("segments", tl!("Segments"), (8.0, 128.0), 0, UnitKind::Pixels)]; + let mut advanced = vec![rows.plain("segments", tl!("Segments"), (8.0, 128.0), 0)]; if place == Place::Dialog { advanced.push(rows.flag("__showAxis", tl!("Show axis"))); } diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 53f7a888fe..f0529ee590 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -406,6 +406,39 @@ fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() { assert_eq!(doc(&h), before); } +/// The Bevel heading is a section named Bevel that holds its Reset, on its own line between Cap and Bevel Shape. +#[test] +fn the_bevel_heading_is_a_section_between_cap_and_bevel_shape() { + use craft::ui::contract::Role; + let mut h = drawn(SQUARE, EXTRUDE); + h.set("__page", json!("object")); + let (cap, reset, shape) = (h.target("Cap").rect, h.target("Reset").rect, h.target("Bevel Shape").rect); + let tree = h.fixture.tree(); + let section = h.fixture.by_role(Role::GROUP).into_iter().find(|t| tree.name_of(t.node) == Some("Bevel")).map(|t| t.rect); + assert!(section.is_some_and(|s| s.contains_rect(reset)), "a section named Bevel holds Reset: {section:?} {reset:?}"); + assert!(reset.top() >= cap.bottom(), "Reset is below Cap: {cap:?} {reset:?}"); + assert!(shape.top() >= reset.bottom(), "Bevel Shape is below Reset: {reset:?} {shape:?}"); + h.cancel(); +} + +/// The bevel's Repeat and Revolve's Segments are counts: their rows show no unit after the number, while Taper, a +/// share, shows its percent sign. +#[test] +fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { + use craft::ui::patterns::form_dialogs::DialogFields; + use craft::ui::runtime::env::UnitKind; + let app = VectorcraftApp::new(Session::new(), crate::Services::default()); + let unit = |effect: &str, page: &str, key: &str| { + let data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new()); + let mut fields = DialogFields::new(); + fields.set("__page", FieldValue::Text(page.into())); + super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) + }; + assert_eq!(unit(EXTRUDE, "object", "bevelRepeat"), Some(None)); + assert_eq!(unit(REVOLVE, "rotation", "segments"), Some(None)); + assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); +} + #[test] fn reset_all_keeps_map_art_and_its_options() { let mut h = drawn(SQUARE, CLASSIC_EXTRUDE); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 5713d3d27e..6576e17c73 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -422,7 +422,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } // PLAN: assumed TileGrid::show_items(ui, &source, &mut |key, _| tile) as the framework's stories call it; // the checks arrive as `CollectionEvent::Item(key, TilePartEvent::Check { .. })` in `response.events`. - let grid = TileGrid::new("Artboards").checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { + let grid = TileGrid::new(tl!("Artboards")).checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { let on = boards.get(*i).copied().unwrap_or(false); let mut tile = Tile::new(menus.names.get(*i).cloned().unwrap_or_default()).check(if on { ToggleState::On } else { ToggleState::Off }); if let Some(file) = files.get(*i).cloned().flatten() { diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 8227766b4a..200b91f458 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,27 +247,31 @@ fn legacy_ai_saves_the_artboards_checked_in_its_picker() { assert_eq!(boards_in(&dialog(&mut app)), Some(vec![true, false, true, false])); } -/// The legacy picker's note and its count of checked artboards are in the window's accessibility tree, and the count -/// follows the checks. +/// The legacy picker's note, grid name and count are announced. The count follows the checks and +/// the grid name follows the interface language. #[test] -fn legacy_ai_names_its_note_and_artboard_count_in_the_accessibility_tree() { +fn legacy_ai_announces_its_note_grid_name_and_artboard_count() { let (mut app, _, _) = desktop("art.ai"); app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80})).unwrap(); save_as(&mut app, "file.saveAs"); set(&mut app, "aiVersion", json!("7")); - let labels = |app: &mut VectorcraftApp| -> Vec { + let labels = |app: &mut VectorcraftApp, role: Option| -> Vec { frame(app); let ctx = app.ui_ctx.clone().unwrap(); - let out = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.ui(ui)); + let out = crate::testing::app_frame(app, &ctx, egui::RawInput::default()); let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + nodes.iter().filter(|(_, node)| role.is_none_or(|role| node.role() == role)).filter_map(|(_, node)| node.label()).map(str::to_owned).collect() }; - let shown = labels(&mut app); + let shown = labels(&mut app, None); assert!(shown.iter().any(|l| l.starts_with("A legacy .ai file holds one artboard")), "{shown:?}"); assert!(shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); set(&mut app, "boards", json!([true, false])); - let shown = labels(&mut app); + let shown = labels(&mut app, None); assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + + app.session.prefs.interface_language = "fr".into(); + let shown = labels(&mut app, Some(egui::accesskit::Role::ListBox)); + assert!(shown.iter().any(|label| label == "Plans de travail"), "{shown:?}"); } #[test] diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 571d0b4489..f41ee64794 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1015,3 +1015,23 @@ fn save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones() { assert!(!is_open(&app), "{bad}"); } } + +/// The number and length fields of the sections that name them: the page range, the bleed sides and the font +/// subset threshold. +#[test] +fn the_range_bleed_and_subset_fields_are_named() { + let (mut app, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + let sections: [(&str, &[&str]); 3] = + [("general", &["Range"]), ("marks", &["Offset", "Top", "Bottom", "Left", "Right"]), ("advanced", &["Subset fonts below"])]; + for (section, expected) in sections { + set_field(&app, "section", json!(section)); + pump(&mut app); + let ctx = app.ui_ctx.clone().expect("a UI context"); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let names = super::super::tests_print::field_names(&out); + for name in expected { + assert!(names.iter().any(|n| n == name), "{section}: {name} in {names:?}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index f01bc521ee..f85cdfe558 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -374,9 +374,10 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map, mut menu: Optio let one = rows.len() == 1; let first = settings_format(&rows); let shown = Stack::new().show(ui, |ui, _| { - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + // The buttons end at the right edge; a column too narrow for them puts them on more lines. + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(tl!("Formats:")).shade(Shade::Muted).show(ui); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { for (id, label) in PLATFORMS { if Button::new(tl!(label)).selected(preset == id).id_salt(id).show(ui).clicked() { platform = Some(id); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..7e15614537 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -32,16 +32,18 @@ use std::path::Path; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Outcome as _, Show as _}; +use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id, }; use craft::ui::display::Text; +use craft::ui::layout_components::Stack; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; +use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; @@ -65,6 +67,8 @@ pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a /// The note the file dialog shows when the person picked more files than a script is given. const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; +/// The height of the Script File Access prompt's list of picked files before it scrolls, in points. +const PICKED_LIST_HEIGHT: f32 = 120.0; /// The warning before a script runs. One type per question, so the host's per-type results never /// mix the three questions of this area. @@ -82,6 +86,11 @@ crate::dialogs::confirm::wrapped_dialog!(CloseQuestion, StandardPrompt, CLOSE_KI /// The tag of the warning: the params `script.run` takes once the warning is answered. struct RunWarning { params: Value, + /// The automation roots in force when asked: the script runs under them, and under any in force + /// when the warning is answered. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the script runs as automation. + automated: bool, } /// What a script's `alert`, `confirm` or `prompt` dialog answers with. @@ -353,7 +362,12 @@ impl StackDialog for ScriptFiles { } let rows = |ui: &mut Ui| paths.iter().for_each(|path| drop(Text::new(shown_text(path, false)).show(ui))); if paths.len() > 1 { - egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, rows); + Stack::new() + .label(tl!("Picked files")) + .scroll(Scroll::vertical()) + .room_height(PICKED_LIST_HEIGHT) + .id_salt("script-picked") + .show(ui, |ui, _| rows(ui)); } else { rows(ui); } @@ -473,7 +487,7 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result() + && let Some(RunWarning { params, scope, automated }) = answer.take_tag::() { let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; - if let Err(e) = stored.and_then(|()| app.run("script.run", params).map(drop)) { + let run = |app: &mut VectorcraftApp| app.run("script.run", params).map(drop); + let automated = automated || app.automation_asked(); + if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) { app.status(e); } } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1eeec2d52d..c45284ba5a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -213,6 +213,85 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// Drop Shadow's, Inner Glow's and Outer Glow's Mode is a blend-mode menu of every mode the effect draws, opening on the +/// effect's default, in the dialog and in the Appearance panel's editor (the same rows over the stored values, where a +/// mode in another spelling shows as its menu entry). Picking Multiply in a glow's dialog stores `multiply`, and a mode +/// the menu lacks is refused as it is set. +#[test] +fn shadow_and_glow_dialogs_pick_mode_from_a_blend_mode_menu() { + use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, ParamKind}; + let modes: Vec = vectorcraft_doc::color::BlendMode::ALL.into_iter().map(vectorcraft_effects::blend_mode_id).collect(); + for (effect, default) in [("stylize.dropShadow", "multiply"), ("stylize.innerGlow", "screen"), ("stylize.outerGlow", "screen")] { + let mut app = app(); + for editing in [false, true] { + let cx = super::effect_params::EffectCx::new(&app, effect, editing); + let rows = super::effect_params::effect_params(&cx, &DialogFields::new()); + let row = rows.iter().find(|p| p.key == "mode").unwrap_or_else(|| panic!("{effect}: a Mode row")); + let ParamKind::Blend { modes: listed, default: shown, .. } = &row.kind else { panic!("{effect}: Mode is {:?}", row.kind) }; + let listed: Vec = listed.iter().map(|(entry, _)| entry.key.clone()).collect(); + assert_eq!(listed, modes, "{effect}"); + assert_eq!(shown.as_deref(), Some(default), "{effect}"); + let stored = serde_json::Map::from_iter([("mode".to_string(), json!("Color Burn"))]); + let fields = super::form::fields_of(&rows, &stored); + assert_eq!(fields.get("mode"), Some(&FieldValue::from("colorBurn")), "{effect}"); + } + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(default), "{effect}"); + let (dialog, ctx) = (top(&app).0, app.ui_ctx.clone().expect("a window app")); + let refused = app.dialogs().expect("a window app").with(|h| h.set_json_field(&ctx, dialog, "mode", json!("multipy"))); + assert!(refused.is_err(), "{effect}: a mode the menu lacks"); + let want = if default == "multiply" { "colorBurn" } else { "multiply" }; + let mode = if default == "multiply" { "Color Burn" } else { "Multiply" }; + let params = match effect { + "stylize.dropShadow" => json!({"field": "mode", "value": mode}), + "stylize.innerGlow" => json!({"dialog": dialog.value(), "fields": [{"field": "mode", "value": mode}]}), + _ => json!({"dialog": dialog.value().to_string(), "fields": [{"field": "mode", "value": mode}]}), + }; + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", params); + assert_eq!(fields(&app)["mode"], json!(want)); + frame(&mut app, vec![]); + assert!(confirm(&mut app), "{effect}"); + let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert_eq!(n.appearance.effects[0].params["mode"], json!(want), "{effect}"); + } +} + +/// Confirming an untouched legacy mode keeps the file's value and does not add an undo step. +/// Choosing a different mode updates the stored value. +#[test] +fn unchanged_effect_dialog_preserves_legacy_blend_modes() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let effect = "stylize.dropShadow"; + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null})).unwrap(); + for (old_mode, shown_mode) in [(Value::Null, "multiply"), (json!("multipy"), "normal")] { + app.session.replay("effect.setParams", &json!({"ids": [id], "index": 0, "item": null, "params": {"mode": old_mode}})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(shown_mode)); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params.get("mode"), Some(&old_mode)); + assert_eq!(state.history.undo.len(), before); + + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + let ctx = app.ui_ctx.clone().expect("a window app"); + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "mode", "value": "Screen"})); + frame(&mut app, vec![]); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params["mode"], json!("screen")); + assert_eq!(state.history.undo.len(), before + 1); + } +} + /// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's dialog open on the /// converted color, and OK without editing it keeps the color. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_accessibility.rs b/crates/ui-egui/src/dialogs/tests_accessibility.rs index 524c3ddcfc..0a060089d6 100644 --- a/crates/ui-egui/src/dialogs/tests_accessibility.rs +++ b/crates/ui-egui/src/dialogs/tests_accessibility.rs @@ -1,4 +1,5 @@ -//! The Split Into Grid dialog names its row and column fields with their axis, read from the access tree of the window. +//! The Split Into Grid dialog names its row and column fields with their axis and lays them out in two columns, read +//! from the access tree of the window. use egui::accesskit::Role; use serde_json::json; @@ -27,3 +28,24 @@ fn split_into_grid_names_row_and_column_fields_with_context() { assert!(names.contains(&name), "{name} among the text inputs: {names:?}"); } } + +/// Split Into Grid lays its fields out as a grid: the columns' fields stand right of the rows' fields on the same +/// lines, and Add Guides stands below the last of them. +#[test] +fn split_into_grid_lays_out_its_fields_above_add_guides() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap(); + app.run("select.all", json!({})).unwrap(); + assert!(super::object_dialogs::open_from_menu(&mut app, "object.path.splitIntoGrid")); + settle(&mut app); + let out = frame(&mut app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let rect = |name: &str| { + let node = update.nodes.iter().map(|(_, node)| node).find(|node| node.label() == Some(name)); + node.and_then(|node| node.bounds()).unwrap_or_else(|| panic!("{name} has a rect")) + }; + let (rows, columns, guides) = (rect("Rows: Total:"), rect("Columns: Total:"), rect("Add Guides")); + assert!(columns.x0 > rows.x1, "the columns' fields stand right of the rows' fields: {rows:?} {columns:?}"); + assert!(columns.y0 < rows.y1 && rows.y0 < columns.y1, "the two Total fields share a line: {rows:?} {columns:?}"); + assert!(guides.y0 >= rows.y1.max(columns.y1), "Add Guides stands below the grid: {guides:?} {rows:?} {columns:?}"); +} diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 775b3e1374..90af85ee0c 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -147,6 +147,46 @@ fn define_grid_loads_and_saves_presets() { assert_eq!(app.session.prefs.perspective_presets.len(), 2); } +/// Enter pressed in the field that has the focus, then the passes that run the filed answer and close the dialog. +fn enter(app: &mut VectorcraftApp) { + let ctx = window(app); + let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + crate::tests::synthetic::key_frame(app, &ctx, vec![key(true)]); + crate::tests::synthetic::key_frame(app, &ctx, vec![key(false)]); + frame(app); + frame(app); +} + +#[test] +fn enter_is_ok_in_define_grid_and_save_grid_as_preset() { + let mut app = app(); + // Define Grid: Enter in the focused field defines the grid and closes the dialog. + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "angle", json!(30)).unwrap(); + frame(&mut app); + frame(&mut app); + assert!(window(&app).memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + enter(&mut app); + assert_eq!(kind(&app), None, "Enter closes Define Grid"); + assert!((grid(&app).viewing_angle() - 30.0).abs() < 1e-9, "Enter defines the grid"); + // Save Grid as Preset: Enter in the name field saves the preset and closes the dialog. + app.run("ui.savePerspectivePreset", json!({})).unwrap(); + frame(&mut app); + frame(&mut app); + assert!(window(&app).memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + enter(&mut app); + assert_eq!(kind(&app), None, "Enter closes Save Grid as Preset"); + assert_eq!(app.session.prefs.perspective_presets.len(), 1, "Enter saves the preset"); + // A name the presets refuse: Enter files it, the refusal shows, and the dialog stays. + app.run("ui.savePerspectivePreset", json!({})).unwrap(); + set(&mut app, "name", json!("[2P-Normal View]")).unwrap(); + frame(&mut app); + frame(&mut app); + enter(&mut app); + assert_eq!(kind(&app).as_deref(), Some(super::perspective_grid::KIND), "a refused name keeps the dialog open"); + assert_eq!(app.session.prefs.perspective_presets.len(), 1); +} + #[test] fn the_presets_manager_creates_edits_and_deletes_presets() { use super::perspective_presets::{self, Action}; diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index 166961be91..37b5555966 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -87,6 +87,21 @@ fn labels_units_sections_text_and_lists_come_from_the_manifest() { assert_eq!(rows.iter().filter(|p| p.key == "angles").count(), 1); } +#[test] +fn a_slider_widget_makes_a_whole_number_range_row_of_an_int_parameter() { + use craft::ui::patterns::form_dialogs::ParamKind; + let manifest = r#"{"id":"test.ui.fields.slider","name":"Slide","version":"1","kind":"filter","params":{ + "count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"}, + "plain":{"type":"int","min":1,"max":20,"default":4}}}"#; + let parsed = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap(); + let rows = super::form::plugin_params(&parsed, &Map::new()); + let kind = |key: &str| &rows.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("no row for {key}")).kind; + assert!(matches!(kind("count"), ParamKind::Range { min, max, .. } if (*min, *max) == (1.0, 20.0)), "an int slider is a range row"); + assert!(matches!(kind("plain"), ParamKind::Int { .. }), "an int without the key stays a number field"); + // The slider's value reaches the plug-in as a whole number. + assert_eq!(super::form::typed_number(7.0), json!(7)); +} + #[test] fn visible_when_shows_a_parameter_only_while_its_condition_holds() { let id = "test.ui.fields.visible"; diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f4e4136188..5fa18d848b 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -538,3 +538,40 @@ fn a_spot_inks_icon_converts_it_to_process_and_back() { pump(&mut app); assert_eq!(inks(&app), json!([{"name": "Gold", "print": true, "convertToProcess": false}])); } + +/// The names screen readers give the number and text fields in `out`'s accessibility tree: a field's own +/// name, else the text of a label it is labeled by, else "". +pub(super) fn field_names(out: &egui::FullOutput) -> Vec { + use egui::accesskit::Role; + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let text_of = |id| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + nodes + .iter() + .filter(|(_, n)| matches!(n.role(), Role::TextInput | Role::SpinButton)) + .map(|(_, n)| n.label().map(str::to_string).or_else(|| n.labelled_by().iter().find_map(|l| text_of(*l))).unwrap_or_default()) + .collect() +} + +/// Every number and length field of the dialog's sections has a name that tells it from the others in its row. +#[test] +fn every_number_and_length_field_is_named() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + let sections: [(&str, &[&str]); 4] = [ + ("General", &["Copies", "Range", "Width", "Height", "Overlap", "Tile Range", "Gutter", "Scale 1", "Scale 2"]), + ("Marks and Bleed", &["Offset", "Top", "Bottom", "Left", "Right"]), + ("Graphics", &["Flatness"]), + ("Advanced", &["Unprintable margin"]), + ]; + for (section, expected) in sections { + set(&mut app, "section", json!(section)); + pump(&mut app); + let ctx = ctx(&app); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let names = field_names(&out); + for name in expected { + assert!(names.iter().any(|n| n == name), "{section}: {name} in {names:?}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/tests_raster_formats.rs b/crates/ui-egui/src/dialogs/tests_raster_formats.rs index c56f69a7f0..be2d65a5cf 100644 --- a/crates/ui-egui/src/dialogs/tests_raster_formats.rs +++ b/crates/ui-egui/src/dialogs/tests_raster_formats.rs @@ -89,6 +89,62 @@ fn a_cmyk_document_exports_cmyk_by_default() { } } +/// GIF and PNG-8 Options start with No Transparency Dither at amount 100 and send the chosen +/// method and amount, which change the file of partly transparent art. +#[test] +fn palette_options_send_the_transparency_dither() { + let (mut app, written) = app(1); + app.run("transparency.set", json!({"opacity": 40})).unwrap(); + let export = |app: &mut VectorcraftApp, format: &str, sets: &[(&str, serde_json::Value)]| { + app.run("file.exportAs", json!({"format": format})).unwrap(); + confirm(app); + let d = fields(app); + assert_eq!((d.text("transparencyDither"), d.number("transparencyDitherAmount")), (Some("none"), Some(100.0)), "{format}"); + for (k, v) in sets { + set(app, k, v.clone()); + } + frame(app); + try_confirm(app).unwrap_or_else(|e| panic!("{format}: {e}")); + written.borrow().last().unwrap().1.clone() + }; + for format in ["gif", "png8"] { + let none = export(&mut app, format, &[]); + let diffusion = export(&mut app, format, &[("transparencyDither", json!("diffusion")), ("transparencyDitherAmount", json!(100))]); + assert_ne!(diffusion, none, "{format}"); + assert_eq!(export(&mut app, format, &[("transparencyDither", json!("diffusion")), ("transparencyDitherAmount", json!(0))]), none, "{format}"); + assert_ne!(export(&mut app, format, &[("transparencyDither", json!("pattern"))]), none, "{format}"); + // With Transparency off the rows keep their values and change nothing. + let opaque = export(&mut app, format, &[("transparency", json!(false))]); + assert_eq!(export(&mut app, format, &[("transparencyDither", json!("noise")), ("transparency", json!(false))]), opaque, "{format}"); + } +} + +/// The Transparency Dither row and Diffusion's amount row are named in the accessibility tree, +/// the amount row shows only for Diffusion, and both are disabled while Transparency is off. +#[test] +fn palette_options_name_the_transparency_dither_controls() { + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png8"})).unwrap(); + confirm(&mut app); + let names = |app: &mut VectorcraftApp| -> Vec { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter(|(_, n)| n.role() != egui::accesskit::Role::Label).filter_map(|(_, n)| n.label().map(str::to_owned)).collect() + }; + let named = |shown: &[String], name: &str| shown.iter().any(|n| n == name); + let shown = names(&mut app); + assert!(named(&shown, "Transparency Dither"), "{shown:?}"); + assert!(!named(&shown, "Transparency Dither Amount"), "only Diffusion has an amount: {shown:?}"); + set(&mut app, "transparencyDither", json!("diffusion")); + let shown = names(&mut app); + assert!(named(&shown, "Transparency Dither Amount"), "{shown:?}"); + set(&mut app, "transparency", json!(false)); + assert!(try_set(&mut app, "transparencyDither", json!("noise")).is_err(), "disabled without Transparency"); + assert!(try_set(&mut app, "transparencyDitherAmount", json!(50)).is_err(), "disabled without Transparency"); + assert_eq!(fields(&app).text("transparencyDither"), Some("diffusion"), "kept"); +} + #[test] fn text_export_options_write_the_stories() { let (mut app, written) = app(1); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 544985b8d2..8a73810d89 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -837,18 +837,25 @@ fn big_tiff_tags(bytes: &[u8]) -> Vec<(u16, u16, u32, u16)> { } /// Frames of the app's own window (`app.ui_ctx`, where its dialogs are) with the accessibility -/// tree, input events and a clock; each frame runs the dialog layer's pump after it. +/// tree, input events and a clock; each frame runs the dialog layer's pump after it. The window is +/// 1280 by 900 unless `sized` gives another size. #[derive(Default)] pub(super) struct Window { time: f64, + size: Option, } impl Window { + /// A window of `size` instead of the default 1280 by 900. + fn sized(size: egui::Vec2) -> Self { + Self { size: Some(size), ..Self::default() } + } + fn run(&mut self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { let ctx = app.ui_ctx.clone().expect("a test app has a window"); ctx.enable_accesskit(); self.time += 0.1; - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, self.size.unwrap_or(egui::vec2(1280.0, 900.0))); let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; // The window's frame with the app's frame input, as the hosts run it: the controls' commands reach the app. let out = crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)); @@ -1429,3 +1436,82 @@ fn an_artboard_name_stays_with_its_document() { assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]); assert!(log.borrow().is_empty(), "renaming must not export"); } + +/// In a window of the default size and in one of the app's least size, every control of the dialog stays between its +/// sides, the format rows stay in the right column, and in the default window the Formats heading's buttons end at +/// the column's right edge. +#[test] +fn the_format_rows_fit_the_right_column_at_the_default_and_least_window_sizes() { + let rows = json!([ + {"scale": "1x", "suffix": "", "format": "png"}, + {"scale": "2x", "suffix": "@2x-long-suffix", "format": "jpg", "quality": 100}, + {"scale": "100w", "format": "pdf"}, + ]); + // The default window, then the least size the desktop app's window takes. + for (size, default) in [(egui::vec2(1280.0, 900.0), true), (egui::vec2(800.0, 500.0), false)] { + let (mut app, _) = app(2, false); + let mut w = Window::sized(size); + w.run(&mut app, vec![]); + open(&mut app); + set(&mut app, "formats", rows.clone()); + w.run(&mut app, vec![]); + let out = w.run(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let rect = |n: &egui::accesskit::Node| { + n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + }; + let find = |label: &str, role: Role| { + nodes + .iter() + .find(|(_, n)| n.label() == Some(label) && n.role() == role) + .and_then(|(_, n)| rect(n)) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let Some((dialog_id, dialog)) = nodes.iter().find(|(_, n)| n.role() == Role::Dialog) else { panic!("no dialog at {size:?}") }; + let dialog = rect(dialog).expect("the dialog's bounds"); + // The Export to: section spans the right column. + let column = find("Export to:", Role::Group); + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let mut under = vec![*dialog_id]; + while let Some(id) = under.pop() { + let Some(n) = by_id.get(&id) else { continue }; + under.extend(n.children().iter().copied()); + if let Some(r) = rect(n) { + assert!( + r.left() >= dialog.left() - 0.5 && r.right() <= dialog.right() + 0.5, + "{:?} {:?} at {r:?} is outside the dialog at {dialog:?} in a {size:?} window", + n.role(), + n.label() + ); + } + } + // Each control with how many of it the three rows show. + let format_rows = [ + ("Formats:", Role::Label, 1), + ("iOS", Role::Button, 1), + ("Android", Role::Button, 1), + ("Format Presets", Role::Button, 1), + ("Format Settings", Role::Button, 1), + ("Scale", Role::ComboBox, 3), + ("Suffix", Role::TextInput, 3), + ("Format", Role::ComboBox, 3), + ("Remove", Role::Button, 3), + ("+ Add Scale", Role::Button, 1), + ]; + for (label, role, count) in format_rows { + let shown: Vec<_> = nodes.iter().filter(|(_, n)| n.label() == Some(label) && n.role() == role).collect(); + assert_eq!(shown.len(), count, "{role:?} {label:?} in a {size:?} window"); + for (_, n) in shown { + let r = rect(n).expect("bounds"); + assert!( + r.left() >= column.left() - 0.5 && r.right() <= column.right() + 0.5, + "{label} at {r:?} is outside the column at {column:?} in a {size:?} window" + ); + } + } + if default { + let gear = find("Format Settings", Role::Button); + assert!((gear.right() - column.right()).abs() <= 0.5, "the gear at {gear:?} ends at the column's edge {column:?}"); + } + } +} diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 49308002f9..3ca925ed6a 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -391,6 +391,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Presentation Mode fits each floating window it shows to the main window: back in their // floating windows, those views fit their windows again. let presenting = presenting(app); + let restoring = !presenting && app.canvas.windows.presented.is_some(); if presenting { let is_floating = current.is_some_and(|k| floating(app, &k)); let shown = app.canvas.windows.presented.get_or_insert_default(); @@ -421,9 +422,15 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { return; } let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); - app.canvas.windows.current = current; let ctx = ui.ctx().clone(); let os_windows = WindowHost::of(&ctx).viewports_available(); + if restoring && !os_windows && raise.is_some() { + // egui raises every reappearing area in this pass, preserving their old order. Repeat + // the current window's raise next frame, when the other windows no longer request it. + ctx.request_repaint(); + } else { + app.canvas.windows.current = current; + } // An OS window's place is in desktop points: the main window's own origin shifts it. let origin = if os_windows { ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO).to_vec2() diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 5e519cf80b..99a979b982 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -417,23 +417,36 @@ fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { #[test] fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { - let mut app = app_with(2); - let ctx = crate::testing::ui_context(); - frame(&mut app, &ctx, vec![]); - app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - // Where the two windows overlap: document 1's title bar, over document 0's body. - let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("document.activate", json!({"index": 0})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - click(&mut app, &ctx, overlap); - assert_eq!(app.session.active_index(), Some(0), "document 0's window is in front where they overlap"); + for change_during_presentation in [false, true] { + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Where the two windows overlap: document 1's title bar, over document 0's body. + let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); + // Cover both an unchanged current document and one chosen while the windows are hidden. + if !change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + if change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, overlap); + assert_eq!( + app.session.active_index(), + Some(0), + "document 0's window is in front (changed during presentation: {change_during_presentation})" + ); + } } /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks diff --git a/crates/ui-egui/src/fields.rs b/crates/ui-egui/src/fields.rs index f5eb2e33f2..a2f0e728d9 100644 --- a/crates/ui-egui/src/fields.rs +++ b/crates/ui-egui/src/fields.rs @@ -44,6 +44,15 @@ pub fn blend_entries() -> Vec> { framework_blend_entries(&entries, |entry| mode_label(entry.key)) } +/// The modes of an effect's blend-mode row. The entries use the stored IDs and translated names. +/// The framework uses each mode's key metadata to separate the existing groups. +pub fn effect_blend_modes() -> Vec<(BlendKeyEntry, Label)> { + blend_table() + .into_iter() + .map(|(mode, shortcut)| (BlendKeyEntry::new(vectorcraft_effects::blend_mode_id(mode), shortcut), mode_label(mode))) + .collect() +} + /// `mode`'s name in the interface language. fn mode_label(mode: BlendMode) -> Label { Label::from(crate::i18n::t(mode.label())) diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index cc5e2dda5a..b07e126478 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -511,7 +511,7 @@ impl StackDialog for FindFontDialog { .map_or_else(String::new, |f| format!("{} {} ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"])) }; let row_text = |at: usize| shown.get(at).and_then(|&i| rows.get(i)).map_or_else(String::new, |r| row_label(&r.family, &r.style)); - let out = Dialog::new(tl!("Find Font").to_string()).buttons(buttons).show(ui, |ui, _| { + let out = Dialog::new(tl!("Find Font").to_string()).buttons(buttons).close_on_enter(true).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { crate::panels::section(heading.clone()).show(ui, |ui, _| { let docs = Lines { len: count, text: &doc_text }; @@ -1463,6 +1463,28 @@ mod tests { assert_eq!(row(&app)["status"], "missing"); } + /// Enter in the field that has the focus is Done: the dialog closes, and no Find or Change runs. + #[test] + fn enter_is_done() { + let mut app = new_app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Inter"})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let is_open = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::().is_some()); + open(&mut app); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + assert!(is_open(&app)); + assert!(ctx.memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + let undo = app.session.active().unwrap().history.undo.len(); + let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![key(true)]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![key(false)]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + assert!(!is_open(&app), "Enter closes Find Font"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "Enter changes no font"); + } + /// Another document in front, and pattern editing entered and canceled, each give the list of /// the document in front as it is then. #[test] diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index e0e4c32a32..cd0362187a 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -37,6 +37,9 @@ fn the_document_filter_lists_the_families_the_documents_type_uses() { app.run("object.lock", serde_json::json!({})).unwrap(); app.run("text.create", serde_json::json!({"x": 20, "y": 150, "text": "Missing", "font": "Missing Family 7059"})).unwrap(); let db = vectorcraft_text::FontDb::global(); + // Tests running alongside register composite fonts and load fonts in the process-wide database; + // their changes wait until this test ends, so both listings of every family are the same. + let _steady = vectorcraft_text::test_fonts::steady_fonts(db); let used_by_doc = super::document_families(db, &app.session.active().unwrap().doc); let mut names: Vec<_> = used_by_doc.iter().cloned().collect(); names.sort(); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 87f76147b6..e17017d95b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7929,6 +7929,35 @@ variable-list-end {0}, {1} {0} i {1} @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` +@msg only a filter declares `writes` només un filtre declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` inclou `{shown}` dues vegades +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` inclou `{shown}`, que `inputs` no inclou +@msg `writes` needs `api` {WRITES_API} or later `writes` requereix `api` {WRITES_API} o posterior +@msg `writes` needs the permission `doc.write` `writes` requereix el permís `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} no és text, ni una imatge ni una instància de símbol +@msg the text of type given as `truncated` can't be changed no es pot canviar el text d’un text donat com a `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries ha de ser una llista d’un màxim de {MAX_INPUT_RUNS} entrades +@msg type needs at least one run el text necessita almenys un tram +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de text (límit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paràgrafs (límit {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output més de {MAX_INPUT_TEXT_TOTAL} bytes de text en tota la sortida +@msg unknown key '{k}' clau desconeguda '{k}' +@msg must be a list of 6 numbers ha de ser una llista de 6 nombres +@msg a number is out of range (limit ±{MAX_COORD}) un nombre és fora de l’interval (límit ±{MAX_COORD}) +@msg flattens the object to a line or a point redueix l’objecte a una línia o un punt +@msg an object flattened to a line or a point can't be placed again un objecte reduït a una línia o un punt no es pot tornar a col·locar +@msg must be a number from 0 to 1 ha de ser un nombre de 0 a 1 +@msg must be the name of a symbol ha de ser el nom d’un símbol +@msg '{shown}' is not a symbol in this document '{shown}' no és un símbol d’aquest document +@msg a run must be {{"text", "style", "inline"?}} un tram ha de ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` conté el caràcter d’un gràfic en línia +@msg inline graphics can't be added, removed, reordered or changed els gràfics en línia no es poden afegir, eliminar, reordenar ni canviar +@msg the characters of threaded type can't be changed els caràcters del text enllaçat no es poden canviar +@msg the characters of type with ruby can't be changed els caràcters del text amb rubí no es poden canviar +@msg expected {count} paragraph styles, one per paragraph s’esperaven {count} estils de paràgraf, un per paràgraf +@msg the document has no Kinsoku set named '{shown}' el document no té cap conjunt Kinsoku anomenat '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters ha de tenir 1-{MAX_FAMILY} caràcters imprimibles Read the objects it is given, and the document's settings, artboards, layers and swatches Llegir els objectes que rep, i la configuració, els taulers, les capes i les mostres del document @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` ha de llistar seccions diferents: settings, artboards, layers o swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` és per a un filtre, o un efecte dinàmic amb `commands`, amb `api` 3 o posterior i el permís `doc.read` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 13129a99a0..2433a0b12e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7542,6 +7542,35 @@ axis Y Axis osa Y @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` +@msg only a filter declares `writes` `writes` deklaruje pouze filtr +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance +@msg `writes` lists `{shown}` twice `writes` uvádí `{shown}` dvakrát +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` uvádí `{shown}`, který `inputs` neuvádí +@msg `writes` needs `api` {WRITES_API} or later `writes` vyžaduje `api` {WRITES_API} nebo vyšší +@msg `writes` needs the permission `doc.write` `writes` vyžaduje oprávnění `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} není text, obraz ani instance symbolu +@msg the text of type given as `truncated` can't be changed text objektu předaného jako `truncated` nelze změnit +@msg must be a list of at most {MAX_INPUT_RUNS} entries musí být seznam nejvýše {MAX_INPUT_RUNS} položek +@msg type needs at least one run text potřebuje alespoň jeden úsek +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtů textu (limit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} odstavců (limit {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output více než {MAX_INPUT_TEXT_TOTAL} bajtů textu v celém výstupu +@msg unknown key '{k}' neznámý klíč '{k}' +@msg must be a list of 6 numbers musí být seznam 6 čísel +@msg a number is out of range (limit ±{MAX_COORD}) číslo je mimo rozsah (limit ±{MAX_COORD}) +@msg flattens the object to a line or a point zplošťuje objekt na čáru nebo bod +@msg an object flattened to a line or a point can't be placed again objekt zploštělý na čáru nebo bod nelze znovu umístit +@msg must be a number from 0 to 1 musí být číslo od 0 do 1 +@msg must be the name of a symbol musí být název symbolu +@msg '{shown}' is not a symbol in this document '{shown}' není symbol v tomto dokumentu +@msg a run must be {{"text", "style", "inline"?}} úsek musí být {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` obsahuje znak vložené grafiky +@msg inline graphics can't be added, removed, reordered or changed vloženou grafiku nelze přidávat, odebírat, přeřazovat ani měnit +@msg the characters of threaded type can't be changed znaky zřetězeného textu nelze změnit +@msg the characters of type with ruby can't be changed znaky textu s ruby nelze změnit +@msg expected {count} paragraph styles, one per paragraph očekáváno {count} stylů odstavců, jeden na každý odstavec +@msg the document has no Kinsoku set named '{shown}' dokument nemá sadu Kinsoku s názvem '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters musí mít 1-{MAX_FAMILY} tisknutelných znaků Read the objects it is given, and the document's settings, artboards, layers and swatches Číst objekty, které dostane, a nastavení, pracovní plochy, vrstvy a vzorky dokumentu @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musí uvádět různé oddíly: settings, artboards, layers nebo swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` je pro filtr nebo živý efekt s `commands`, s `api` 3 nebo vyšším a s oprávněním `doc.read` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 94df1eb83e..4fbda43ec7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -722,6 +722,35 @@ liquify-list-end {0}, {1} {0} og {1} @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` +@msg only a filter declares `writes` kun et filter angiver `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance +@msg `writes` lists `{shown}` twice `writes` angiver `{shown}` to gange +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` angiver `{shown}`, som `inputs` ikke angiver +@msg `writes` needs `api` {WRITES_API} or later `writes` kræver `api` {WRITES_API} eller nyere +@msg `writes` needs the permission `doc.write` `writes` kræver tilladelsen `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} er hverken tekst, et billede eller en symbolforekomst +@msg the text of type given as `truncated` can't be changed teksten i et tekstobjekt givet som `truncated` kan ikke ændres +@msg must be a list of at most {MAX_INPUT_RUNS} entries skal være en liste med højst {MAX_INPUT_RUNS} elementer +@msg type needs at least one run tekst skal have mindst ét tekststykke +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte tekst (grænse {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} afsnit (grænse {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mere end {MAX_INPUT_TEXT_TOTAL} byte tekst i hele outputtet +@msg unknown key '{k}' ukendt nøgle '{k}' +@msg must be a list of 6 numbers skal være en liste med 6 tal +@msg a number is out of range (limit ±{MAX_COORD}) et tal er uden for området (grænse ±{MAX_COORD}) +@msg flattens the object to a line or a point gør objektet fladt til en linje eller et punkt +@msg an object flattened to a line or a point can't be placed again et objekt, der er gjort fladt til en linje eller et punkt, kan ikke placeres igen +@msg must be a number from 0 to 1 skal være et tal fra 0 til 1 +@msg must be the name of a symbol skal være navnet på et symbol +@msg '{shown}' is not a symbol in this document '{shown}' er ikke et symbol i dette dokument +@msg a run must be {{"text", "style", "inline"?}} et tekststykke skal være {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` indeholder tegnet for en indlejret grafik +@msg inline graphics can't be added, removed, reordered or changed indlejrede grafikker kan ikke tilføjes, fjernes, omarrangeres eller ændres +@msg the characters of threaded type can't be changed tegnene i sammenkædet tekst kan ikke ændres +@msg the characters of type with ruby can't be changed tegnene i tekst med ruby kan ikke ændres +@msg expected {count} paragraph styles, one per paragraph forventede {count} afsnitsstile, én pr. afsnit +@msg the document has no Kinsoku set named '{shown}' dokumentet har intet Kinsoku-sæt med navnet '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters skal være 1-{MAX_FAMILY} tegn, der kan udskrives Read the objects it is given, and the document's settings, artboards, layers and swatches Læse de objekter, den får, og dokumentets indstillinger, tegneflader, lag og farveprøver @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` skal angive forskellige afsnit: settings, artboards, layers eller swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` er til et filter eller en live-effekt med `commands`, ved `api` 3 eller senere og med tilladelsen `doc.read` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0fb57437c4..7d788abf48 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7125,6 +7125,35 @@ axis Y Axis Y-Achse @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` +@msg only a filter declares `writes` nur ein Filter deklariert `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance +@msg `writes` lists `{shown}` twice `writes` führt `{shown}` doppelt auf +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` führt `{shown}` auf, das `inputs` nicht aufführt +@msg `writes` needs `api` {WRITES_API} or later `writes` erfordert `api` {WRITES_API} oder höher +@msg `writes` needs the permission `doc.write` `writes` erfordert die Berechtigung `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} ist weder Text noch ein Bild noch eine Symbolinstanz +@msg the text of type given as `truncated` can't be changed der Text eines als `truncated` übergebenen Textobjekts kann nicht geändert werden +@msg must be a list of at most {MAX_INPUT_RUNS} entries muss eine Liste mit höchstens {MAX_INPUT_RUNS} Einträgen sein +@msg type needs at least one run Text braucht mindestens einen Abschnitt +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} Byte Text (Grenze {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} Absätze (Grenze {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mehr als {MAX_INPUT_TEXT_TOTAL} Byte Text in der gesamten Ausgabe +@msg unknown key '{k}' unbekannter Schlüssel '{k}' +@msg must be a list of 6 numbers muss eine Liste von 6 Zahlen sein +@msg a number is out of range (limit ±{MAX_COORD}) eine Zahl liegt außerhalb des Bereichs (Grenze ±{MAX_COORD}) +@msg flattens the object to a line or a point macht das Objekt zu einer Linie oder einem Punkt +@msg an object flattened to a line or a point can't be placed again ein zu einer Linie oder einem Punkt zusammengefallenes Objekt kann nicht neu platziert werden +@msg must be a number from 0 to 1 muss eine Zahl von 0 bis 1 sein +@msg must be the name of a symbol muss der Name eines Symbols sein +@msg '{shown}' is not a symbol in this document '{shown}' ist kein Symbol in diesem Dokument +@msg a run must be {{"text", "style", "inline"?}} ein Abschnitt muss {{"text", "style", "inline"?}} sein +@msg `text` holds the character of an inline graphic `text` enthält das Zeichen einer eingebundenen Grafik +@msg inline graphics can't be added, removed, reordered or changed eingebundene Grafiken können nicht hinzugefügt, entfernt, umgeordnet oder geändert werden +@msg the characters of threaded type can't be changed die Zeichen von verkettetem Text können nicht geändert werden +@msg the characters of type with ruby can't be changed die Zeichen von Text mit Ruby können nicht geändert werden +@msg expected {count} paragraph styles, one per paragraph {count} Absatzformate erwartet, eines pro Absatz +@msg the document has no Kinsoku set named '{shown}' das Dokument hat keinen Kinsoku-Satz namens '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters muss 1-{MAX_FAMILY} druckbare Zeichen haben Read the objects it is given, and the document's settings, artboards, layers and swatches Die Objekte lesen, die es erhält, sowie die Einstellungen, Zeichenflächen, Ebenen und Farbfelder des Dokuments @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` muss verschiedene Abschnitte aufführen: settings, artboards, layers oder swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gilt für einen Filter oder einen Live-Effekt mit `commands`, mit `api` 3 oder höher und der Berechtigung `doc.read` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3bd10eceb1..2e7c180df4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7532,6 +7532,35 @@ axis Y Axis Άξονας Y @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` +@msg only a filter declares `writes` μόνο ένα φίλτρο δηλώνει `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance το `writes` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance +@msg `writes` lists `{shown}` twice το `writes` αναφέρει το `{shown}` δύο φορές +@msg `writes` lists `{shown}`, which `inputs` doesn't list το `writes` αναφέρει το `{shown}`, το οποίο δεν αναφέρει το `inputs` +@msg `writes` needs `api` {WRITES_API} or later το `writes` απαιτεί `api` {WRITES_API} ή νεότερο +@msg `writes` needs the permission `doc.write` το `writes` απαιτεί το δικαίωμα `doc.write` +@msg {_1} is not type, an image or a symbol instance το {_1} δεν είναι κείμενο, εικόνα ή στιγμιότυπο συμβόλου +@msg the text of type given as `truncated` can't be changed το κείμενο ενός αντικειμένου κειμένου που δόθηκε ως `truncated` δεν μπορεί να αλλάξει +@msg must be a list of at most {MAX_INPUT_RUNS} entries πρέπει να είναι λίστα με έως {MAX_INPUT_RUNS} στοιχεία +@msg type needs at least one run το κείμενο χρειάζεται τουλάχιστον ένα τμήμα +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte κειμένου (όριο {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} παράγραφοι (όριο {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output περισσότερα από {MAX_INPUT_TEXT_TOTAL} byte κειμένου σε όλη την έξοδο +@msg unknown key '{k}' άγνωστο κλειδί '{k}' +@msg must be a list of 6 numbers πρέπει να είναι λίστα 6 αριθμών +@msg a number is out of range (limit ±{MAX_COORD}) ένας αριθμός είναι εκτός εύρους (όριο ±{MAX_COORD}) +@msg flattens the object to a line or a point συμπιέζει το αντικείμενο σε γραμμή ή σημείο +@msg an object flattened to a line or a point can't be placed again ένα αντικείμενο που συμπιέστηκε σε γραμμή ή σημείο δεν μπορεί να τοποθετηθεί ξανά +@msg must be a number from 0 to 1 πρέπει να είναι αριθμός από 0 έως 1 +@msg must be the name of a symbol πρέπει να είναι το όνομα ενός συμβόλου +@msg '{shown}' is not a symbol in this document το '{shown}' δεν είναι σύμβολο σε αυτό το έγγραφο +@msg a run must be {{"text", "style", "inline"?}} ένα τμήμα πρέπει να είναι {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic το `text` περιέχει τον χαρακτήρα ενός ενσωματωμένου γραφικού +@msg inline graphics can't be added, removed, reordered or changed τα ενσωματωμένα γραφικά δεν μπορούν να προστεθούν, να αφαιρεθούν, να αναδιαταχθούν ή να αλλάξουν +@msg the characters of threaded type can't be changed οι χαρακτήρες συνδεδεμένου κειμένου δεν μπορούν να αλλάξουν +@msg the characters of type with ruby can't be changed οι χαρακτήρες κειμένου με ruby δεν μπορούν να αλλάξουν +@msg expected {count} paragraph styles, one per paragraph αναμένονταν {count} στυλ παραγράφων, ένα ανά παράγραφο +@msg the document has no Kinsoku set named '{shown}' το έγγραφο δεν έχει σύνολο Kinsoku με όνομα '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters πρέπει να έχει 1-{MAX_FAMILY} εκτυπώσιμους χαρακτήρες Read the objects it is given, and the document's settings, artboards, layers and swatches Ανάγνωση των αντικειμένων που του δίνονται, καθώς και των ρυθμίσεων, των πινάκων σχεδίασης, των επιπέδων και των δειγμάτων χρωμάτων του εγγράφου @msg `context` must list distinct sections: settings, artboards, layers or swatches το `context` πρέπει να απαριθμεί διαφορετικές ενότητες: settings, artboards, layers ή swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` το `context` ισχύει για φίλτρο ή ζωντανό εφέ με `commands`, με `api` 3 ή νεότερο και το δικαίωμα `doc.read` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7e71c1c191..37eea18b4c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7518,6 +7518,35 @@ axis Y Axis Eje Y @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` +@msg only a filter declares `writes` solo un filtro declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` incluye `{shown}` dos veces +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` incluye `{shown}`, que `inputs` no incluye +@msg `writes` needs `api` {WRITES_API} or later `writes` requiere `api` {WRITES_API} o posterior +@msg `writes` needs the permission `doc.write` `writes` requiere el permiso `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} no es texto, ni una imagen ni una instancia de símbolo +@msg the text of type given as `truncated` can't be changed no se puede cambiar el texto de un objeto de texto dado como `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries debe ser una lista de {MAX_INPUT_RUNS} entradas como máximo +@msg type needs at least one run el texto necesita al menos un tramo +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (límite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} párrafos (límite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output más de {MAX_INPUT_TEXT_TOTAL} bytes de texto en toda la salida +@msg unknown key '{k}' clave desconocida '{k}' +@msg must be a list of 6 numbers debe ser una lista de 6 números +@msg a number is out of range (limit ±{MAX_COORD}) un número está fuera de rango (límite ±{MAX_COORD}) +@msg flattens the object to a line or a point reduce el objeto a una línea o un punto +@msg an object flattened to a line or a point can't be placed again un objeto reducido a una línea o un punto no se puede volver a colocar +@msg must be a number from 0 to 1 debe ser un número de 0 a 1 +@msg must be the name of a symbol debe ser el nombre de un símbolo +@msg '{shown}' is not a symbol in this document '{shown}' no es un símbolo de este documento +@msg a run must be {{"text", "style", "inline"?}} un tramo debe ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contiene el carácter de un gráfico en línea +@msg inline graphics can't be added, removed, reordered or changed los gráficos en línea no se pueden añadir, quitar, reordenar ni cambiar +@msg the characters of threaded type can't be changed los caracteres del texto enlazado no se pueden cambiar +@msg the characters of type with ruby can't be changed los caracteres del texto con ruby no se pueden cambiar +@msg expected {count} paragraph styles, one per paragraph se esperaban {count} estilos de párrafo, uno por párrafo +@msg the document has no Kinsoku set named '{shown}' el documento no tiene ningún conjunto de kinsoku llamado '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters debe tener 1-{MAX_FAMILY} caracteres imprimibles Read the objects it is given, and the document's settings, artboards, layers and swatches Leer los objetos que recibe, y los ajustes, las mesas de trabajo, las capas y las muestras del documento @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` debe enumerar secciones distintas: settings, artboards, layers o swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` es para un filtro, o un efecto dinámico con `commands`, con `api` 3 o posterior y el permiso `doc.read` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index cc6e0d2fd2..c95d681244 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7609,6 +7609,35 @@ axis Y Axis Y-akseli @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` +@msg only a filter declares `writes` vain suodatin voi määrittää `writes`-avaimen +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance +@msg `writes` lists `{shown}` twice `writes` luettelee kohteen `{shown}` kahdesti +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` luettelee kohteen `{shown}`, jota `inputs` ei luettele +@msg `writes` needs `api` {WRITES_API} or later `writes` edellyttää `api`-tasoa {WRITES_API} tai uudempaa +@msg `writes` needs the permission `doc.write` `writes` edellyttää käyttöoikeutta `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} ei ole teksti, kuva eikä symbolin ilmentymä +@msg the text of type given as `truncated` can't be changed `truncated`-merkinnällä annetun tekstiobjektin tekstiä ei voi muuttaa +@msg must be a list of at most {MAX_INPUT_RUNS} entries on oltava luettelo, jossa on enintään {MAX_INPUT_RUNS} kohdetta +@msg type needs at least one run tekstissä on oltava vähintään yksi tekstijakso +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} tavua tekstiä (raja {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} kappaletta (raja {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output yli {MAX_INPUT_TEXT_TOTAL} tavua tekstiä koko tulosteessa +@msg unknown key '{k}' tuntematon avain '{k}' +@msg must be a list of 6 numbers on oltava 6 luvun luettelo +@msg a number is out of range (limit ±{MAX_COORD}) luku on alueen ulkopuolella (raja ±{MAX_COORD}) +@msg flattens the object to a line or a point litistää objektin viivaksi tai pisteeksi +@msg an object flattened to a line or a point can't be placed again viivaksi tai pisteeksi litistynyttä objektia ei voi sijoittaa uudelleen +@msg must be a number from 0 to 1 on oltava luku väliltä 0-1 +@msg must be the name of a symbol on oltava symbolin nimi +@msg '{shown}' is not a symbol in this document '{shown}' ei ole symboli tässä dokumentissa +@msg a run must be {{"text", "style", "inline"?}} tekstijakson on oltava {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` sisältää upotetun grafiikan merkin +@msg inline graphics can't be added, removed, reordered or changed upotettuja grafiikoita ei voi lisätä, poistaa, järjestää uudelleen eikä muuttaa +@msg the characters of threaded type can't be changed ketjutetun tekstin merkkejä ei voi muuttaa +@msg the characters of type with ruby can't be changed ruby-merkintöjä sisältävän tekstin merkkejä ei voi muuttaa +@msg expected {count} paragraph styles, one per paragraph odotettiin {count} kappaletyyliä, yksi kutakin kappaletta kohden +@msg the document has no Kinsoku set named '{shown}' dokumentissa ei ole Kinsoku-joukkoa nimeltä '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters siinä on oltava 1-{MAX_FAMILY} tulostettavaa merkkiä Read the objects it is given, and the document's settings, artboards, layers and swatches Lukea sille annetut objektit sekä asiakirjan asetukset, piirtoalustat, tasot ja värimallit @msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-avaimen on lueteltava eri osiot: settings, artboards, layers tai swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` on suodattimelle tai reaaliaikaiselle tehosteelle, jolla on `commands`, tasolla `api` 3 tai uudempi ja käyttöoikeudella `doc.read` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6bcf110355..efab0b71ea 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7539,6 +7539,35 @@ axis Y Axis Axe Y @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` +@msg only a filter declares `writes` seul un filtre déclare `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance +@msg `writes` lists `{shown}` twice `writes` mentionne `{shown}` deux fois +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` mentionne `{shown}`, que `inputs` ne mentionne pas +@msg `writes` needs `api` {WRITES_API} or later `writes` nécessite `api` {WRITES_API} ou plus +@msg `writes` needs the permission `doc.write` `writes` nécessite l’autorisation `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} n’est ni du texte, ni une image, ni une instance de symbole +@msg the text of type given as `truncated` can't be changed le texte d’un objet texte fourni comme `truncated` ne peut pas être modifié +@msg must be a list of at most {MAX_INPUT_RUNS} entries doit être une liste d’au plus {MAX_INPUT_RUNS} entrées +@msg type needs at least one run le texte doit compter au moins un segment +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} octets de texte (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraphes (limite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output plus de {MAX_INPUT_TEXT_TOTAL} octets de texte sur l’ensemble de la sortie +@msg unknown key '{k}' clé inconnue '{k}' +@msg must be a list of 6 numbers doit être une liste de 6 nombres +@msg a number is out of range (limit ±{MAX_COORD}) un nombre est hors limites (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point réduit l’objet à une ligne ou à un point +@msg an object flattened to a line or a point can't be placed again un objet réduit à une ligne ou à un point ne peut pas être replacé +@msg must be a number from 0 to 1 doit être un nombre de 0 à 1 +@msg must be the name of a symbol doit être le nom d’un symbole +@msg '{shown}' is not a symbol in this document '{shown}' n’est pas un symbole de ce document +@msg a run must be {{"text", "style", "inline"?}} un segment doit être {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contient le caractère d’un graphique incorporé +@msg inline graphics can't be added, removed, reordered or changed les graphiques incorporés ne peuvent pas être ajoutés, supprimés, réordonnés ni modifiés +@msg the characters of threaded type can't be changed les caractères d’un texte lié ne peuvent pas être modifiés +@msg the characters of type with ruby can't be changed les caractères d’un texte avec ruby ne peuvent pas être modifiés +@msg expected {count} paragraph styles, one per paragraph {count} styles de paragraphe attendus, un par paragraphe +@msg the document has no Kinsoku set named '{shown}' le document n’a aucun jeu de kinsoku nommé '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters doit compter 1-{MAX_FAMILY} caractères imprimables Read the objects it is given, and the document's settings, artboards, layers and swatches Lire les objets qui lui sont transmis, ainsi que les paramètres, les plans de travail, les calques et les nuances du document @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` doit lister des sections distinctes parmi settings, artboards, layers et swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` est réservé à un filtre, ou à un effet dynamique avec `commands`, avec `api` 3 ou plus et l’autorisation `doc.read` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 986e007efc..082e4c8e03 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6702,6 +6702,35 @@ arrowhead Feather पंख @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है +@msg only a filter declares `writes` केवल फ़िल्टर `writes` घोषित करता है +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें +@msg `writes` lists `{shown}` twice `writes` में `{shown}` दो बार सूचीबद्ध है +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` में `{shown}` सूचीबद्ध है, जो `inputs` में सूचीबद्ध नहीं है +@msg `writes` needs `api` {WRITES_API} or later `writes` के लिए `api` {WRITES_API} या बाद का स्तर आवश्यक है +@msg `writes` needs the permission `doc.write` `writes` के लिए अनुमति `doc.write` आवश्यक है +@msg {_1} is not type, an image or a symbol instance {_1} न टेक्स्ट है, न इमेज, न सिंबल इंस्टेंस +@msg the text of type given as `truncated` can't be changed `truncated` के रूप में दिए गए टेक्स्ट ऑब्जेक्ट का टेक्स्ट बदला नहीं जा सकता +@msg must be a list of at most {MAX_INPUT_RUNS} entries अधिकतम {MAX_INPUT_RUNS} प्रविष्टियों की सूची होनी चाहिए +@msg type needs at least one run टेक्स्ट में कम से कम एक रन होना चाहिए +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) टेक्स्ट के {bytes} बाइट (सीमा {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} अनुच्छेद (सीमा {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output पूरे आउटपुट में {MAX_INPUT_TEXT_TOTAL} बाइट से अधिक टेक्स्ट +@msg unknown key '{k}' अज्ञात कुंजी '{k}' +@msg must be a list of 6 numbers 6 संख्याओं की सूची होनी चाहिए +@msg a number is out of range (limit ±{MAX_COORD}) एक संख्या सीमा से बाहर है (सीमा ±{MAX_COORD}) +@msg flattens the object to a line or a point ऑब्जेक्ट को एक रेखा या बिंदु में चपटा कर देता है +@msg an object flattened to a line or a point can't be placed again रेखा या बिंदु में चपटे हुए ऑब्जेक्ट को फिर से रखा नहीं जा सकता +@msg must be a number from 0 to 1 0 से 1 तक की संख्या होनी चाहिए +@msg must be the name of a symbol किसी सिंबल का नाम होना चाहिए +@msg '{shown}' is not a symbol in this document '{shown}' इस दस्तावेज़ में कोई सिंबल नहीं है +@msg a run must be {{"text", "style", "inline"?}} रन {{"text", "style", "inline"?}} होना चाहिए +@msg `text` holds the character of an inline graphic `text` में इनलाइन ग्राफ़िक का वर्ण है +@msg inline graphics can't be added, removed, reordered or changed इनलाइन ग्राफ़िक जोड़े, हटाए, पुनः क्रमित या बदले नहीं जा सकते +@msg the characters of threaded type can't be changed थ्रेडेड टेक्स्ट के वर्ण बदले नहीं जा सकते +@msg the characters of type with ruby can't be changed रूबी वाले टेक्स्ट के वर्ण बदले नहीं जा सकते +@msg expected {count} paragraph styles, one per paragraph {count} पैराग्राफ़ स्टाइल अपेक्षित थे, हर पैराग्राफ़ के लिए एक +@msg the document has no Kinsoku set named '{shown}' दस्तावेज़ में '{shown}' नाम का कोई किनसोकू सेट नहीं है +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} प्रिंट करने योग्य वर्ण होने चाहिए Read the objects it is given, and the document's settings, artboards, layers and swatches उसे दिए गए ऑब्जेक्ट्स, और डॉक्यूमेंट की सेटिंग्स, आर्टबोर्ड्स, लेयर्स और स्वॉचेस पढ़ना @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` में अलग-अलग सेक्शन होने चाहिए: settings, artboards, layers या swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` केवल फ़िल्टर, या `commands` वाले लाइव इफ़ेक्ट के लिए है, `api` 3 या उसके बाद और अनुमति `doc.read` के साथ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ec8a60deaf..669e5723c9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7527,6 +7527,35 @@ axis Y Axis Y tengely @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges +@msg only a filter declares `writes` `writes` kulcsot csak szűrő adhat meg +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance a `writes` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket +@msg `writes` lists `{shown}` twice a `writes` kétszer sorolja fel ezt: `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list a `writes` felsorolja ezt: `{shown}`, de az `inputs` nem sorolja fel +@msg `writes` needs `api` {WRITES_API} or later a `writes` használatához `api` {WRITES_API} vagy újabb szükséges +@msg `writes` needs the permission `doc.write` a `writes` használatához a(z) `doc.write` engedély szükséges +@msg {_1} is not type, an image or a symbol instance {_1} nem szöveg, nem kép és nem szimbólumpéldány +@msg the text of type given as `truncated` can't be changed a `truncated` jelöléssel átadott szövegobjektum szövege nem módosítható +@msg must be a list of at most {MAX_INPUT_RUNS} entries legfeljebb {MAX_INPUT_RUNS} elemű lista legyen +@msg type needs at least one run a szövegnek legalább egy szakaszra van szüksége +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bájt szöveg (korlát: {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} bekezdés (korlát: {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output több mint {MAX_INPUT_TEXT_TOTAL} bájt szöveg a teljes kimenetben +@msg unknown key '{k}' ismeretlen kulcs: '{k}' +@msg must be a list of 6 numbers 6 számból álló lista legyen +@msg a number is out of range (limit ±{MAX_COORD}) egy szám a tartományon kívül esik (korlát: ±{MAX_COORD}) +@msg flattens the object to a line or a point vonallá vagy ponttá lapítja az objektumot +@msg an object flattened to a line or a point can't be placed again a vonallá vagy ponttá lapított objektum nem helyezhető el újra +@msg must be a number from 0 to 1 0 és 1 közötti szám legyen +@msg must be the name of a symbol egy szimbólum neve legyen +@msg '{shown}' is not a symbol in this document '{shown}' nem szimbólum ebben a dokumentumban +@msg a run must be {{"text", "style", "inline"?}} egy szakasz formája {{"text", "style", "inline"?}} legyen +@msg `text` holds the character of an inline graphic a `text` egy szövegközi grafika karakterét tartalmazza +@msg inline graphics can't be added, removed, reordered or changed szövegközi grafikák nem adhatók hozzá, nem távolíthatók el, nem rendezhetők át és nem módosíthatók +@msg the characters of threaded type can't be changed a láncolt szöveg karakterei nem módosíthatók +@msg the characters of type with ruby can't be changed a rubyt tartalmazó szöveg karakterei nem módosíthatók +@msg expected {count} paragraph styles, one per paragraph {count} bekezdésstílus volt várható, bekezdésenként egy +@msg the document has no Kinsoku set named '{shown}' a dokumentumban nincs '{shown}' nevű Kinsoku-készlet +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} nyomtatható karakter legyen Read the objects it is given, and the document's settings, artboards, layers and swatches Olvashatja a kapott objektumokat, valamint a dokumentum beállításait, rajztábláit, rétegeit és színmintáit @msg `context` must list distinct sections: settings, artboards, layers or swatches a `context` csak különböző szakaszokat sorolhat fel: settings, artboards, layers vagy swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` a `context` szűrőhöz vagy `commands` kulccsal rendelkező élő effektushoz való, `api` 3 vagy újabb mellett, a(z) `doc.read` engedéllyel diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3b3069e023..725ef12327 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -604,6 +604,35 @@ @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` +@msg only a filter declares `writes` hanya filter yang mendeklarasikan `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance +@msg `writes` lists `{shown}` twice `writes` mencantumkan `{shown}` dua kali +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` mencantumkan `{shown}`, yang tidak dicantumkan `inputs` +@msg `writes` needs `api` {WRITES_API} or later `writes` memerlukan `api` {WRITES_API} atau lebih baru +@msg `writes` needs the permission `doc.write` `writes` memerlukan izin `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} bukan teks, gambar, atau instans simbol +@msg the text of type given as `truncated` can't be changed teks dari objek teks yang diberikan sebagai `truncated` tidak dapat diubah +@msg must be a list of at most {MAX_INPUT_RUNS} entries harus berupa daftar berisi paling banyak {MAX_INPUT_RUNS} entri +@msg type needs at least one run teks memerlukan setidaknya satu potongan +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte teks (batas {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraf (batas {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output lebih dari {MAX_INPUT_TEXT_TOTAL} byte teks di seluruh keluaran +@msg unknown key '{k}' kunci tidak dikenal '{k}' +@msg must be a list of 6 numbers harus berupa daftar 6 angka +@msg a number is out of range (limit ±{MAX_COORD}) sebuah angka di luar rentang (batas ±{MAX_COORD}) +@msg flattens the object to a line or a point memipihkan objek menjadi garis atau titik +@msg an object flattened to a line or a point can't be placed again objek yang dipipihkan menjadi garis atau titik tidak dapat ditempatkan lagi +@msg must be a number from 0 to 1 harus berupa angka dari 0 sampai 1 +@msg must be the name of a symbol harus berupa nama simbol +@msg '{shown}' is not a symbol in this document '{shown}' bukan simbol di dokumen ini +@msg a run must be {{"text", "style", "inline"?}} potongan harus berupa {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` berisi karakter grafik sebaris +@msg inline graphics can't be added, removed, reordered or changed grafik sebaris tidak dapat ditambahkan, dihapus, diurutkan ulang, atau diubah +@msg the characters of threaded type can't be changed karakter teks beruntun tidak dapat diubah +@msg the characters of type with ruby can't be changed karakter teks dengan ruby tidak dapat diubah +@msg expected {count} paragraph styles, one per paragraph diharapkan {count} gaya paragraf, satu per paragraf +@msg the document has no Kinsoku set named '{shown}' dokumen tidak memiliki set Kinsoku bernama '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters harus berupa 1-{MAX_FAMILY} karakter yang dapat dicetak Read the objects it is given, and the document's settings, artboards, layers and swatches Membaca objek yang diberikan kepadanya, serta pengaturan, artboard, lapisan, dan sampel warna dokumen @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` harus mencantumkan bagian yang berbeda: settings, artboards, layers, atau swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` untuk filter, atau efek langsung dengan `commands`, pada `api` 3 atau lebih baru dengan izin `doc.read` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8e7959999c..d00eb9be50 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7164,6 +7164,35 @@ axis Y Axis Asse Y @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` +@msg only a filter declares `writes` solo un filtro dichiara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` elenca `{shown}` due volte +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` elenca `{shown}`, che `inputs` non elenca +@msg `writes` needs `api` {WRITES_API} or later `writes` richiede `api` {WRITES_API} o successivo +@msg `writes` needs the permission `doc.write` `writes` richiede l’autorizzazione `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} non è testo, né un’immagine né un’istanza di simbolo +@msg the text of type given as `truncated` can't be changed il testo di un oggetto di testo fornito come `truncated` non può essere modificato +@msg must be a list of at most {MAX_INPUT_RUNS} entries deve essere un elenco di al massimo {MAX_INPUT_RUNS} voci +@msg type needs at least one run il testo richiede almeno un segmento +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte di testo (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragrafi (limite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output più di {MAX_INPUT_TEXT_TOTAL} byte di testo nell’intero output +@msg unknown key '{k}' chiave sconosciuta '{k}' +@msg must be a list of 6 numbers deve essere un elenco di 6 numeri +@msg a number is out of range (limit ±{MAX_COORD}) un numero è fuori intervallo (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point riduce l’oggetto a una linea o a un punto +@msg an object flattened to a line or a point can't be placed again un oggetto ridotto a una linea o a un punto non può essere ricollocato +@msg must be a number from 0 to 1 deve essere un numero da 0 a 1 +@msg must be the name of a symbol deve essere il nome di un simbolo +@msg '{shown}' is not a symbol in this document '{shown}' non è un simbolo di questo documento +@msg a run must be {{"text", "style", "inline"?}} un segmento deve essere {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contiene il carattere di una grafica in linea +@msg inline graphics can't be added, removed, reordered or changed le grafiche in linea non possono essere aggiunte, rimosse, riordinate o modificate +@msg the characters of threaded type can't be changed i caratteri del testo concatenato non possono essere modificati +@msg the characters of type with ruby can't be changed i caratteri del testo con ruby non possono essere modificati +@msg expected {count} paragraph styles, one per paragraph attesi {count} stili paragrafo, uno per paragrafo +@msg the document has no Kinsoku set named '{shown}' il documento non ha alcun set kinsoku denominato '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters deve avere 1-{MAX_FAMILY} caratteri stampabili Read the objects it is given, and the document's settings, artboards, layers and swatches Leggere gli oggetti che riceve, e le impostazioni, le tavole da disegno, i livelli e i campioni del documento @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` deve elencare sezioni distinte: settings, artboards, layers o swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` vale per un filtro, o un effetto dinamico con `commands`, con `api` 3 o successiva e l’autorizzazione `doc.read` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d14fc0f723..8dba701981 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7239,6 +7239,35 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です +@msg only a filter declares `writes` `writes` を宣言できるのはフィルターだけです +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください +@msg `writes` lists `{shown}` twice `writes` に `{shown}` が 2 回指定されています +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` に指定された `{shown}` は `inputs` に指定されていません +@msg `writes` needs `api` {WRITES_API} or later `writes` には `api` {WRITES_API} 以上が必要です +@msg `writes` needs the permission `doc.write` `writes` には権限 `doc.write` が必要です +@msg {_1} is not type, an image or a symbol instance {_1} はテキスト、画像、シンボルインスタンスのいずれでもありません +@msg the text of type given as `truncated` can't be changed `truncated` として渡されたテキストの文字列は変更できません +@msg must be a list of at most {MAX_INPUT_RUNS} entries {MAX_INPUT_RUNS} 項目以下のリストにしてください +@msg type needs at least one run テキストには 1 つ以上のランが必要です +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) テキストが {bytes} バイトあります (上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落が {paragraphs} 個あります (上限 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 出力全体のテキストが {MAX_INPUT_TEXT_TOTAL} バイトを超えています +@msg unknown key '{k}' 不明なキー '{k}' +@msg must be a list of 6 numbers 6 つの数値のリストにしてください +@msg a number is out of range (limit ±{MAX_COORD}) 数値が範囲外です (上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point オブジェクトが線または点につぶれます +@msg an object flattened to a line or a point can't be placed again 線または点につぶれたオブジェクトは配置し直せません +@msg must be a number from 0 to 1 0 から 1 までの数値にしてください +@msg must be the name of a symbol シンボルの名前にしてください +@msg '{shown}' is not a symbol in this document '{shown}' はこのドキュメントのシンボルではありません +@msg a run must be {{"text", "style", "inline"?}} ランは {{"text", "style", "inline"?}} にしてください +@msg `text` holds the character of an inline graphic `text` にインライングラフィックの文字が含まれています +@msg inline graphics can't be added, removed, reordered or changed インライングラフィックは追加、削除、並べ替え、変更できません +@msg the characters of threaded type can't be changed スレッドテキストの文字は変更できません +@msg the characters of type with ruby can't be changed ルビのあるテキストの文字は変更できません +@msg expected {count} paragraph styles, one per paragraph 段落スタイルは段落ごとに 1 つ、計 {count} 個必要です +@msg the document has no Kinsoku set named '{shown}' ドキュメントに '{shown}' という名前の禁則処理セットはありません +@msg must be 1-{MAX_FAMILY} printable characters 印刷可能な 1-{MAX_FAMILY} 文字にしてください Read the objects it is given, and the document's settings, artboards, layers and swatches 渡されたオブジェクトと、ドキュメントの設定、アートボード、レイヤー、スウォッチの読み取り @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` には重複しないセクションを指定してください: settings、artboards、layers、swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` は、`api` 3 以降で権限 `doc.read` を持つフィルターまたは `commands` のあるライブ効果専用です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1991d156eb..0a29222b28 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9647,6 +9647,35 @@ axis Y Axis Y ღერძი @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` +@msg only a filter declares `writes` `writes`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance +@msg `writes` lists `{shown}` twice `writes`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes`-ში ჩამოთვლილია `{shown}`, რომელიც `inputs`-ში არ არის ჩამოთვლილი +@msg `writes` needs `api` {WRITES_API} or later `writes`-ს სჭირდება `api` {WRITES_API} ან უფრო ახალი +@msg `writes` needs the permission `doc.write` `writes`-ს სჭირდება ნებართვა `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} არც ტექსტია, არც გამოსახულება და არც სიმბოლოს ეგზემპლარი +@msg the text of type given as `truncated` can't be changed `truncated`-ად გადაცემული ტექსტური ობიექტის ტექსტის შეცვლა შეუძლებელია +@msg must be a list of at most {MAX_INPUT_RUNS} entries უნდა იყოს სია მაქსიმუმ {MAX_INPUT_RUNS} ჩანაწერით +@msg type needs at least one run ტექსტს სჭირდება მინიმუმ ერთი მონაკვეთი +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) ტექსტის {bytes} ბაიტი (ლიმიტი {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} აბზაცი (ლიმიტი {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output მთელ გამონატანში {MAX_INPUT_TEXT_TOTAL} ბაიტზე მეტი ტექსტია +@msg unknown key '{k}' უცნობი გასაღები '{k}' +@msg must be a list of 6 numbers უნდა იყოს 6 რიცხვის სია +@msg a number is out of range (limit ±{MAX_COORD}) რიცხვი დიაპაზონს გარეთაა (ლიმიტი ±{MAX_COORD}) +@msg flattens the object to a line or a point ობიექტს ხაზად ან წერტილად აბრტყელებს +@msg an object flattened to a line or a point can't be placed again ხაზად ან წერტილად გაბრტყელებული ობიექტის ხელახლა განთავსება შეუძლებელია +@msg must be a number from 0 to 1 უნდა იყოს რიცხვი 0-დან 1-მდე +@msg must be the name of a symbol უნდა იყოს სიმბოლოს სახელი +@msg '{shown}' is not a symbol in this document '{shown}' ამ დოკუმენტში სიმბოლო არ არის +@msg a run must be {{"text", "style", "inline"?}} მონაკვეთი უნდა იყოს {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` შეიცავს ტექსტში ჩასმული გრაფიკის სიმბოლოს +@msg inline graphics can't be added, removed, reordered or changed ტექსტში ჩასმული გრაფიკის დამატება, წაშლა, გადალაგება ან შეცვლა შეუძლებელია +@msg the characters of threaded type can't be changed დაკავშირებული ტექსტის სიმბოლოების შეცვლა შეუძლებელია +@msg the characters of type with ruby can't be changed რუბის მქონე ტექსტის სიმბოლოების შეცვლა შეუძლებელია +@msg expected {count} paragraph styles, one per paragraph მოსალოდნელი იყო აბზაცის {count} სტილი, თითო აბზაცზე ერთი +@msg the document has no Kinsoku set named '{shown}' დოკუმენტს არ აქვს Kinsoku-ის ნაკრები სახელით '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters უნდა შედგებოდეს 1-{MAX_FAMILY} დასაბეჭდი სიმბოლოსგან Read the objects it is given, and the document's settings, artboards, layers and swatches მიღებული ობიექტების და დოკუმენტის პარამეტრების, სამუშაო დაფების, შრეებისა და ფერის ნიმუშების წაკითხვა @msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-ში განსხვავებული სექციები უნდა იყოს: settings, artboards, layers ან swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` განკუთვნილია ფილტრისთვის ან `commands`-ის მქონე ცოცხალი ეფექტისთვის, `api` 3-ზე ან უფრო ახალზე, ნებართვით `doc.read` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 005f8284ea..78dc8d7b97 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7136,6 +7136,35 @@ axis Y Axis Y축 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 +@msg only a filter declares `writes` 필터만 `writes`를 선언할 수 있습니다 +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 +@msg `writes` lists `{shown}` twice `writes`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes`에 나열된 `{shown}`이(가) `inputs`에는 없습니다 +@msg `writes` needs `api` {WRITES_API} or later `writes`에는 `api` {WRITES_API} 이상이 필요합니다 +@msg `writes` needs the permission `doc.write` `writes`에는 `doc.write` 권한이 필요합니다 +@msg {_1} is not type, an image or a symbol instance {_1}은(는) 문자, 이미지, 심볼 인스턴스가 아닙니다 +@msg the text of type given as `truncated` can't be changed `truncated`로 전달된 문자 개체의 텍스트는 변경할 수 없습니다 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 항목이 최대 {MAX_INPUT_RUNS}개인 목록이어야 합니다 +@msg type needs at least one run 문자에는 런이 하나 이상 있어야 합니다 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 텍스트 {bytes}바이트(한도 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 단락 {paragraphs}개(한도 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 출력 전체의 텍스트가 {MAX_INPUT_TEXT_TOTAL}바이트를 넘습니다 +@msg unknown key '{k}' 알 수 없는 키 '{k}' +@msg must be a list of 6 numbers 숫자 6개의 목록이어야 합니다 +@msg a number is out of range (limit ±{MAX_COORD}) 숫자가 범위를 벗어났습니다(한도 ±{MAX_COORD}) +@msg flattens the object to a line or a point 개체를 선이나 점으로 납작하게 만듭니다 +@msg an object flattened to a line or a point can't be placed again 선이나 점으로 납작해진 개체는 다시 배치할 수 없습니다 +@msg must be a number from 0 to 1 0에서 1 사이의 숫자여야 합니다 +@msg must be the name of a symbol 심볼 이름이어야 합니다 +@msg '{shown}' is not a symbol in this document '{shown}'은(는) 이 문서의 심볼이 아닙니다 +@msg a run must be {{"text", "style", "inline"?}} 런은 {{"text", "style", "inline"?}} 형식이어야 합니다 +@msg `text` holds the character of an inline graphic `text`에 인라인 그래픽 문자가 들어 있습니다 +@msg inline graphics can't be added, removed, reordered or changed 인라인 그래픽은 추가, 제거, 순서 변경, 수정할 수 없습니다 +@msg the characters of threaded type can't be changed 연결된 문자의 글자는 변경할 수 없습니다 +@msg the characters of type with ruby can't be changed 루비가 있는 문자의 글자는 변경할 수 없습니다 +@msg expected {count} paragraph styles, one per paragraph 단락마다 하나씩 단락 스타일 {count}개가 필요합니다 +@msg the document has no Kinsoku set named '{shown}' 문서에 '{shown}'(이)라는 긴소쿠 세트가 없습니다 +@msg must be 1-{MAX_FAMILY} printable characters 인쇄 가능한 문자 1-{MAX_FAMILY}자여야 합니다 Read the objects it is given, and the document's settings, artboards, layers and swatches 전달받은 개체와 문서의 설정, 아트보드, 레이어, 견본 읽기 @msg `context` must list distinct sections: settings, artboards, layers or swatches `context`에는 서로 다른 섹션을 나열해야 합니다: settings, artboards, layers 또는 swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context`는 `api` 3 이상이고 `doc.read` 권한이 있는 필터 또는 `commands`가 있는 라이브 효과에만 쓸 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 731173eea6..bbe1681764 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -567,6 +567,35 @@ liquify-list-end {0}, {1} {0} en {1} @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` +@msg only a filter declares `writes` alleen een filter declareert `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` noemt een onbekende objectsoort `{shown}`: gebruik type, image of symbolInstance +@msg `writes` lists `{shown}` twice `writes` noemt `{shown}` twee keer +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` noemt `{shown}`, dat `inputs` niet noemt +@msg `writes` needs `api` {WRITES_API} or later `writes` vereist `api` {WRITES_API} of hoger +@msg `writes` needs the permission `doc.write` `writes` vereist de machtiging `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} is geen tekst, afbeelding of symboolinstantie +@msg the text of type given as `truncated` can't be changed de tekst van een tekstobject dat als `truncated` is doorgegeven, kan niet worden gewijzigd +@msg must be a list of at most {MAX_INPUT_RUNS} entries moet een lijst van ten hoogste {MAX_INPUT_RUNS} items zijn +@msg type needs at least one run tekst heeft ten minste één tekstreeks nodig +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes tekst (limiet {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} alinea's (limiet {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output meer dan {MAX_INPUT_TEXT_TOTAL} bytes tekst in de hele uitvoer +@msg unknown key '{k}' onbekende sleutel '{k}' +@msg must be a list of 6 numbers moet een lijst van 6 getallen zijn +@msg a number is out of range (limit ±{MAX_COORD}) een getal valt buiten het bereik (limiet ±{MAX_COORD}) +@msg flattens the object to a line or a point drukt het object plat tot een lijn of een punt +@msg an object flattened to a line or a point can't be placed again een object dat tot een lijn of een punt is platgedrukt, kan niet opnieuw worden geplaatst +@msg must be a number from 0 to 1 moet een getal van 0 tot 1 zijn +@msg must be the name of a symbol moet de naam van een symbool zijn +@msg '{shown}' is not a symbol in this document '{shown}' is geen symbool in dit document +@msg a run must be {{"text", "style", "inline"?}} een tekstreeks moet {{"text", "style", "inline"?}} zijn +@msg `text` holds the character of an inline graphic `text` bevat het teken van een inline afbeelding +@msg inline graphics can't be added, removed, reordered or changed inline afbeeldingen kunnen niet worden toegevoegd, verwijderd, anders geordend of gewijzigd +@msg the characters of threaded type can't be changed de tekens van gekoppelde tekst kunnen niet worden gewijzigd +@msg the characters of type with ruby can't be changed de tekens van tekst met ruby kunnen niet worden gewijzigd +@msg expected {count} paragraph styles, one per paragraph {count} alineastijlen verwacht, één per alinea +@msg the document has no Kinsoku set named '{shown}' het document heeft geen Kinsoku-set met de naam '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters moet uit 1-{MAX_FAMILY} afdrukbare tekens bestaan Read the objects it is given, and the document's settings, artboards, layers and swatches De objecten lezen die het krijgt, en de instellingen, tekengebieden, lagen en stalen van het document @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` moet verschillende secties noemen: settings, artboards, layers of swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` is voor een filter, of een live-effect met `commands`, bij `api` 3 of later en met de machtiging `doc.read` diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9152459071..be22f98247 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7397,6 +7397,35 @@ axis Y Axis Oś Y @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` +@msg only a filter declares `writes` tylko filtr deklaruje `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance +@msg `writes` lists `{shown}` twice `writes` wymienia `{shown}` dwa razy +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` wymienia `{shown}`, którego nie wymienia `inputs` +@msg `writes` needs `api` {WRITES_API} or later `writes` wymaga `api` {WRITES_API} lub nowszego +@msg `writes` needs the permission `doc.write` `writes` wymaga uprawnienia `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} nie jest tekstem, obrazem ani wystąpieniem symbolu +@msg the text of type given as `truncated` can't be changed nie można zmienić tekstu obiektu tekstowego przekazanego jako `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries musi być listą co najwyżej {MAX_INPUT_RUNS} pozycji +@msg type needs at least one run tekst potrzebuje co najmniej jednego fragmentu +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtów tekstu (limit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} akapitów (limit {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output ponad {MAX_INPUT_TEXT_TOTAL} bajtów tekstu w całym wyniku +@msg unknown key '{k}' nieznany klucz '{k}' +@msg must be a list of 6 numbers musi być listą 6 liczb +@msg a number is out of range (limit ±{MAX_COORD}) liczba spoza zakresu (limit ±{MAX_COORD}) +@msg flattens the object to a line or a point spłaszcza obiekt do linii lub punktu +@msg an object flattened to a line or a point can't be placed again obiektu spłaszczonego do linii lub punktu nie można ponownie umieścić +@msg must be a number from 0 to 1 musi być liczbą od 0 do 1 +@msg must be the name of a symbol musi być nazwą symbolu +@msg '{shown}' is not a symbol in this document '{shown}' nie jest symbolem w tym dokumencie +@msg a run must be {{"text", "style", "inline"?}} fragment musi mieć postać {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` zawiera znak grafiki w wierszu +@msg inline graphics can't be added, removed, reordered or changed grafik w wierszu nie można dodawać, usuwać, zmieniać ich kolejności ani modyfikować +@msg the characters of threaded type can't be changed nie można zmienić znaków tekstu wątkowego +@msg the characters of type with ruby can't be changed nie można zmienić znaków tekstu z ruby +@msg expected {count} paragraph styles, one per paragraph oczekiwano {count} stylów akapitowych, po jednym na akapit +@msg the document has no Kinsoku set named '{shown}' dokument nie ma zestawu kinsoku o nazwie '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters musi mieć 1-{MAX_FAMILY} drukowalnych znaków Read the objects it is given, and the document's settings, artboards, layers and swatches Odczytywać obiekty, które otrzymuje, oraz ustawienia, obszary kompozycji, warstwy i próbki dokumentu @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musi wymieniać różne sekcje: settings, artboards, layers lub swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` dotyczy filtra albo efektu na żywo z `commands`, z `api` 3 lub nowszym i z uprawnieniem `doc.read` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b49b217c8f..a2be19bf7e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7441,6 +7441,35 @@ axis Y Axis Eixo Y @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` +@msg only a filter declares `writes` somente um filtro declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance +@msg `writes` lists `{shown}` twice `writes` lista `{shown}` duas vezes +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` lista `{shown}`, que `inputs` não lista +@msg `writes` needs `api` {WRITES_API} or later `writes` exige `api` {WRITES_API} ou posterior +@msg `writes` needs the permission `doc.write` `writes` exige a permissão `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} não é texto, nem uma imagem, nem uma instância de símbolo +@msg the text of type given as `truncated` can't be changed o texto de um objeto de texto fornecido como `truncated` não pode ser alterado +@msg must be a list of at most {MAX_INPUT_RUNS} entries deve ser uma lista de no máximo {MAX_INPUT_RUNS} entradas +@msg type needs at least one run o texto precisa de pelo menos um trecho +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} parágrafos (limite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mais de {MAX_INPUT_TEXT_TOTAL} bytes de texto em toda a saída +@msg unknown key '{k}' chave desconhecida '{k}' +@msg must be a list of 6 numbers deve ser uma lista de 6 números +@msg a number is out of range (limit ±{MAX_COORD}) um número está fora do intervalo (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point achata o objeto em uma linha ou um ponto +@msg an object flattened to a line or a point can't be placed again um objeto achatado em uma linha ou um ponto não pode ser posicionado de novo +@msg must be a number from 0 to 1 deve ser um número de 0 a 1 +@msg must be the name of a symbol deve ser o nome de um símbolo +@msg '{shown}' is not a symbol in this document '{shown}' não é um símbolo deste documento +@msg a run must be {{"text", "style", "inline"?}} um trecho deve ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contém o caractere de um gráfico em linha +@msg inline graphics can't be added, removed, reordered or changed gráficos em linha não podem ser adicionados, removidos, reordenados nem alterados +@msg the characters of threaded type can't be changed os caracteres de texto encadeado não podem ser alterados +@msg the characters of type with ruby can't be changed os caracteres de texto com ruby não podem ser alterados +@msg expected {count} paragraph styles, one per paragraph eram esperados {count} estilos de parágrafo, um por parágrafo +@msg the document has no Kinsoku set named '{shown}' o documento não tem um conjunto Kinsoku chamado '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters deve ter 1-{MAX_FAMILY} caracteres imprimíveis Read the objects it is given, and the document's settings, artboards, layers and swatches Ler os objetos que recebe, e as configurações, as mesas de trabalho, as camadas e as amostras do documento @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` deve listar seções distintas: settings, artboards, layers ou swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` é para um filtro, ou um efeito dinâmico com `commands`, com `api` 3 ou posterior e a permissão `doc.read` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index eec9216b69..e722b4e782 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7164,6 +7164,35 @@ axis Y Axis Ось Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` +@msg only a filter declares `writes` `writes` может объявлять только фильтр +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance в `writes` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance +@msg `writes` lists `{shown}` twice в `writes` `{shown}` указано дважды +@msg `writes` lists `{shown}`, which `inputs` doesn't list в `writes` указано `{shown}`, которого нет в `inputs` +@msg `writes` needs `api` {WRITES_API} or later для `writes` нужен `api` {WRITES_API} или выше +@msg `writes` needs the permission `doc.write` для `writes` нужно разрешение `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} не является ни текстом, ни изображением, ни экземпляром символа +@msg the text of type given as `truncated` can't be changed текст текстового объекта, переданного как `truncated`, изменить нельзя +@msg must be a list of at most {MAX_INPUT_RUNS} entries должно быть списком не более чем из {MAX_INPUT_RUNS} элементов +@msg type needs at least one run у текста должен быть хотя бы один фрагмент +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байт текста (предел {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} абзацев (предел {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output более {MAX_INPUT_TEXT_TOTAL} байт текста во всём выводе +@msg unknown key '{k}' неизвестный ключ '{k}' +@msg must be a list of 6 numbers должно быть списком из 6 чисел +@msg a number is out of range (limit ±{MAX_COORD}) число вне диапазона (предел ±{MAX_COORD}) +@msg flattens the object to a line or a point сплющивает объект в линию или точку +@msg an object flattened to a line or a point can't be placed again объект, сплющенный в линию или точку, нельзя разместить заново +@msg must be a number from 0 to 1 должно быть числом от 0 до 1 +@msg must be the name of a symbol должно быть именем символа +@msg '{shown}' is not a symbol in this document '{shown}' не является символом этого документа +@msg a run must be {{"text", "style", "inline"?}} фрагмент должен иметь вид {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` содержит символ встроенной в строку графики +@msg inline graphics can't be added, removed, reordered or changed встроенную в строку графику нельзя добавлять, удалять, переупорядочивать или изменять +@msg the characters of threaded type can't be changed знаки связанного текста изменить нельзя +@msg the characters of type with ruby can't be changed знаки текста с руби изменить нельзя +@msg expected {count} paragraph styles, one per paragraph ожидалось стилей абзацев: {count}, по одному на абзац +@msg the document has no Kinsoku set named '{shown}' в документе нет набора kinsoku с именем '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters должно содержать 1-{MAX_FAMILY} печатаемых символов Read the objects it is given, and the document's settings, artboards, layers and swatches Читать переданные ему объекты, а также параметры, монтажные области, слои и образцы документа @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` должен перечислять разные разделы: settings, artboards, layers или swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` допустим только для фильтра или динамического эффекта с `commands`, с `api` 3 или выше и с разрешением `doc.read` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a4184199a4..2c9b16b092 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7542,6 +7542,35 @@ axis Y Axis Y-axel @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` +@msg only a filter declares `writes` bara ett filter anger `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance +@msg `writes` lists `{shown}` twice `writes` anger `{shown}` två gånger +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` anger `{shown}`, som `inputs` inte anger +@msg `writes` needs `api` {WRITES_API} or later `writes` kräver `api` {WRITES_API} eller senare +@msg `writes` needs the permission `doc.write` `writes` kräver behörigheten `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} är varken text, en bild eller en symbolinstans +@msg the text of type given as `truncated` can't be changed texten i ett textobjekt som getts som `truncated` kan inte ändras +@msg must be a list of at most {MAX_INPUT_RUNS} entries måste vara en lista med högst {MAX_INPUT_RUNS} poster +@msg type needs at least one run text behöver minst ett textavsnitt +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte text (gräns {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} stycken (gräns {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mer än {MAX_INPUT_TEXT_TOTAL} byte text i hela utdatan +@msg unknown key '{k}' okänd nyckel '{k}' +@msg must be a list of 6 numbers måste vara en lista med 6 tal +@msg a number is out of range (limit ±{MAX_COORD}) ett tal ligger utanför intervallet (gräns ±{MAX_COORD}) +@msg flattens the object to a line or a point plattar till objektet till en linje eller en punkt +@msg an object flattened to a line or a point can't be placed again ett objekt som plattats till en linje eller en punkt kan inte placeras igen +@msg must be a number from 0 to 1 måste vara ett tal från 0 till 1 +@msg must be the name of a symbol måste vara namnet på en symbol +@msg '{shown}' is not a symbol in this document '{shown}' är ingen symbol i det här dokumentet +@msg a run must be {{"text", "style", "inline"?}} ett textavsnitt måste vara {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` innehåller tecknet för en grafik i texten +@msg inline graphics can't be added, removed, reordered or changed grafik i texten kan inte läggas till, tas bort, ordnas om eller ändras +@msg the characters of threaded type can't be changed tecknen i länkad text kan inte ändras +@msg the characters of type with ruby can't be changed tecknen i text med ruby kan inte ändras +@msg expected {count} paragraph styles, one per paragraph {count} styckestilar förväntades, en per stycke +@msg the document has no Kinsoku set named '{shown}' dokumentet har ingen Kinsoku-uppsättning med namnet '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters måste vara 1-{MAX_FAMILY} utskrivbara tecken Read the objects it is given, and the document's settings, artboards, layers and swatches Läsa objekten den får, och dokumentets inställningar, ritytor, lager och färgrutor @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` måste ange olika avsnitt: settings, artboards, layers eller swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gäller ett filter eller en liveeffekt med `commands`, med `api` 3 eller senare och behörigheten `doc.read` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6f1d616aca..81accf43c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7614,6 +7614,35 @@ axis Y Axis Y ekseni @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir +@msg only a filter declares `writes` `writes` yalnızca bir filtrede bildirilebilir +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın +@msg `writes` lists `{shown}` twice `writes` `{shown}` değerini iki kez listeliyor +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` `{shown}` değerini listeliyor, ancak `inputs` listelemiyor +@msg `writes` needs `api` {WRITES_API} or later `writes` için `api` {WRITES_API} veya üstü gerekir +@msg `writes` needs the permission `doc.write` `writes` için `doc.write` izni gerekir +@msg {_1} is not type, an image or a symbol instance {_1} metin, görüntü veya sembol örneği değil +@msg the text of type given as `truncated` can't be changed `truncated` olarak verilen metin nesnesinin metni değiştirilemez +@msg must be a list of at most {MAX_INPUT_RUNS} entries en fazla {MAX_INPUT_RUNS} girişli bir liste olmalıdır +@msg type needs at least one run metnin en az bir parçası olmalıdır +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bayt metin (sınır {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraf (sınır {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output çıktının tamamında {MAX_INPUT_TEXT_TOTAL} bayttan fazla metin +@msg unknown key '{k}' bilinmeyen anahtar '{k}' +@msg must be a list of 6 numbers 6 sayılık bir liste olmalıdır +@msg a number is out of range (limit ±{MAX_COORD}) bir sayı aralık dışında (sınır ±{MAX_COORD}) +@msg flattens the object to a line or a point nesneyi bir çizgiye veya noktaya yassılaştırıyor +@msg an object flattened to a line or a point can't be placed again bir çizgiye veya noktaya yassılaşmış nesne yeniden yerleştirilemez +@msg must be a number from 0 to 1 0 ile 1 arasında bir sayı olmalıdır +@msg must be the name of a symbol bir sembolün adı olmalıdır +@msg '{shown}' is not a symbol in this document '{shown}' bu belgede bir sembol değil +@msg a run must be {{"text", "style", "inline"?}} bir parça {{"text", "style", "inline"?}} biçiminde olmalıdır +@msg `text` holds the character of an inline graphic `text` satır içi bir grafiğin karakterini içeriyor +@msg inline graphics can't be added, removed, reordered or changed satır içi grafikler eklenemez, kaldırılamaz, yeniden sıralanamaz veya değiştirilemez +@msg the characters of threaded type can't be changed zincirli metnin karakterleri değiştirilemez +@msg the characters of type with ruby can't be changed ruby içeren metnin karakterleri değiştirilemez +@msg expected {count} paragraph styles, one per paragraph her paragraf için bir tane olmak üzere {count} paragraf stili bekleniyordu +@msg the document has no Kinsoku set named '{shown}' belgede '{shown}' adlı Kinsoku seti yok +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} yazdırılabilir karakter olmalıdır Read the objects it is given, and the document's settings, artboards, layers and swatches Kendisine verilen nesneleri ve belgenin ayarlarını, çalışma yüzeylerini, katmanlarını ve renk örneklerini okuma @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` farklı bölümleri listelemelidir: settings, artboards, layers veya swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` yalnızca `api` 3 veya sonrasında, `doc.read` izniyle bir filtre ya da `commands` içeren bir canlı efekt içindir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 89c20c44a5..e1700dbb94 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7146,6 +7146,35 @@ axis Y Axis Вісь Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` +@msg only a filter declares `writes` `writes` може оголошувати лише фільтр +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance в `writes` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance +@msg `writes` lists `{shown}` twice в `writes` `{shown}` указано двічі +@msg `writes` lists `{shown}`, which `inputs` doesn't list в `writes` указано `{shown}`, якого немає в `inputs` +@msg `writes` needs `api` {WRITES_API} or later для `writes` потрібен `api` {WRITES_API} або новіший +@msg `writes` needs the permission `doc.write` для `writes` потрібен дозвіл `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} не є ні текстом, ні зображенням, ні екземпляром символу +@msg the text of type given as `truncated` can't be changed текст текстового об’єкта, переданого як `truncated`, змінити не можна +@msg must be a list of at most {MAX_INPUT_RUNS} entries має бути списком щонайбільше з {MAX_INPUT_RUNS} елементів +@msg type needs at least one run текст повинен мати щонайменше один фрагмент +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байтів тексту (межа {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} абзаців (межа {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output понад {MAX_INPUT_TEXT_TOTAL} байтів тексту в усьому виводі +@msg unknown key '{k}' невідомий ключ '{k}' +@msg must be a list of 6 numbers має бути списком із 6 чисел +@msg a number is out of range (limit ±{MAX_COORD}) число поза діапазоном (межа ±{MAX_COORD}) +@msg flattens the object to a line or a point сплющує об’єкт у лінію чи точку +@msg an object flattened to a line or a point can't be placed again об’єкт, сплющений у лінію чи точку, не можна розмістити знову +@msg must be a number from 0 to 1 має бути числом від 0 до 1 +@msg must be the name of a symbol має бути назвою символу +@msg '{shown}' is not a symbol in this document '{shown}' не є символом цього документа +@msg a run must be {{"text", "style", "inline"?}} фрагмент має мати вигляд {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` містить знак вбудованої в рядок графіки +@msg inline graphics can't be added, removed, reordered or changed вбудовану в рядок графіку не можна додавати, вилучати, переставляти чи змінювати +@msg the characters of threaded type can't be changed знаки пов’язаного тексту змінити не можна +@msg the characters of type with ruby can't be changed знаки тексту з рубі змінити не можна +@msg expected {count} paragraph styles, one per paragraph очікувалося стилів абзаців: {count}, по одному на абзац +@msg the document has no Kinsoku set named '{shown}' у документі немає набору kinsoku з назвою '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters має містити 1-{MAX_FAMILY} друкованих символів Read the objects it is given, and the document's settings, artboards, layers and swatches Читати передані йому об’єкти, а також параметри, монтажні області, шари та зразки документа @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` має перелічувати різні розділи: settings, artboards, layers або swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` дозволено лише для фільтра або динамічного ефекту з `commands`, з `api` 3 або вище та з дозволом `doc.read` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d358d49544..278a8c10e9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7193,6 +7193,35 @@ axis Y Axis Trục Y @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` +@msg only a filter declares `writes` chỉ bộ lọc mới khai báo `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance +@msg `writes` lists `{shown}` twice `writes` liệt kê `{shown}` hai lần +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` liệt kê `{shown}`, nhưng `inputs` không liệt kê +@msg `writes` needs `api` {WRITES_API} or later `writes` cần `api` {WRITES_API} trở lên +@msg `writes` needs the permission `doc.write` `writes` cần quyền `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} không phải là văn bản, hình ảnh hay thực thể ký hiệu +@msg the text of type given as `truncated` can't be changed không thể thay đổi văn bản của đối tượng văn bản được đưa vào dưới dạng `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries phải là danh sách có tối đa {MAX_INPUT_RUNS} mục +@msg type needs at least one run văn bản cần ít nhất một đoạn chạy +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte văn bản (giới hạn {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} đoạn văn (giới hạn {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output hơn {MAX_INPUT_TEXT_TOTAL} byte văn bản trên toàn bộ đầu ra +@msg unknown key '{k}' khóa không xác định '{k}' +@msg must be a list of 6 numbers phải là danh sách gồm 6 số +@msg a number is out of range (limit ±{MAX_COORD}) một số nằm ngoài phạm vi (giới hạn ±{MAX_COORD}) +@msg flattens the object to a line or a point làm dẹt đối tượng thành một đường hoặc một điểm +@msg an object flattened to a line or a point can't be placed again không thể đặt lại một đối tượng đã bị dẹt thành đường hoặc điểm +@msg must be a number from 0 to 1 phải là một số từ 0 đến 1 +@msg must be the name of a symbol phải là tên của một ký hiệu +@msg '{shown}' is not a symbol in this document '{shown}' không phải là ký hiệu trong tài liệu này +@msg a run must be {{"text", "style", "inline"?}} một đoạn chạy phải có dạng {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` chứa ký tự của một đồ họa nội dòng +@msg inline graphics can't be added, removed, reordered or changed không thể thêm, xóa, sắp xếp lại hoặc thay đổi đồ họa nội dòng +@msg the characters of threaded type can't be changed không thể thay đổi ký tự của văn bản chuỗi +@msg the characters of type with ruby can't be changed không thể thay đổi ký tự của văn bản có ruby +@msg expected {count} paragraph styles, one per paragraph cần {count} kiểu đoạn văn, mỗi đoạn một kiểu +@msg the document has no Kinsoku set named '{shown}' tài liệu không có bộ Kinsoku nào tên '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters phải có 1-{MAX_FAMILY} ký tự in được Read the objects it is given, and the document's settings, artboards, layers and swatches Đọc các đối tượng được trao cho nó, cùng các thiết lập, bảng vẽ, lớp và mẫu màu của tài liệu @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` phải liệt kê các phần khác nhau: settings, artboards, layers hoặc swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` dành cho bộ lọc, hoặc hiệu ứng trực tiếp có `commands`, ở `api` 3 trở lên và có quyền `doc.read` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c48a32148a..ae265a4fc7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7374,6 +7374,35 @@ axis Y Axis Y 轴 @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` +@msg only a filter declares `writes` 只有滤镜才能声明 `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance +@msg `writes` lists `{shown}` twice `writes` 列出了两次 `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` 列出了 `{shown}`,但 `inputs` 未列出它 +@msg `writes` needs `api` {WRITES_API} or later `writes` 需要 `api` {WRITES_API} 或更高 +@msg `writes` needs the permission `doc.write` `writes` 需要权限 `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} 不是文字、图像或符号实例 +@msg the text of type given as `truncated` can't be changed 作为 `truncated` 给出的文字对象的文本不能更改 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 必须是最多 {MAX_INPUT_RUNS} 个条目的列表 +@msg type needs at least one run 文字至少需要一个文本段 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文本 {bytes} 字节(上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落 {paragraphs} 个(上限 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整个输出中的文本超过 {MAX_INPUT_TEXT_TOTAL} 字节 +@msg unknown key '{k}' 未知键 '{k}' +@msg must be a list of 6 numbers 必须是 6 个数字的列表 +@msg a number is out of range (limit ±{MAX_COORD}) 有数字超出范围(上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point 会把对象压扁成一条线或一个点 +@msg an object flattened to a line or a point can't be placed again 已压扁成线或点的对象无法重新放置 +@msg must be a number from 0 to 1 必须是 0 到 1 之间的数字 +@msg must be the name of a symbol 必须是符号的名称 +@msg '{shown}' is not a symbol in this document '{shown}' 不是此文档中的符号 +@msg a run must be {{"text", "style", "inline"?}} 文本段必须是 {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` 含有随文图形的字符 +@msg inline graphics can't be added, removed, reordered or changed 随文图形不能添加、删除、重新排序或更改 +@msg the characters of threaded type can't be changed 串接文本的字符不能更改 +@msg the characters of type with ruby can't be changed 带注音的文字的字符不能更改 +@msg expected {count} paragraph styles, one per paragraph 应有 {count} 个段落样式,每个段落一个 +@msg the document has no Kinsoku set named '{shown}' 文档中没有名为 '{shown}' 的 Kinsoku 集 +@msg must be 1-{MAX_FAMILY} printable characters 必须是 1-{MAX_FAMILY} 个可打印字符 Read the objects it is given, and the document's settings, artboards, layers and swatches 读取交给它的对象,以及文档的设置、画板、图层和色板 @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` 必须列出互不相同的部分:settings、artboards、layers 或 swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` 仅适用于 `api` 3 或更高、具有权限 `doc.read` 的滤镜或带 `commands` 的实时效果 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 58c451afd6..7d83822f05 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7195,6 +7195,35 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` +@msg only a filter declares `writes` 只有濾鏡才能宣告 `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance +@msg `writes` lists `{shown}` twice `writes` 列出了兩次 `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` 列出了 `{shown}`,但 `inputs` 未列出它 +@msg `writes` needs `api` {WRITES_API} or later `writes` 需要 `api` {WRITES_API} 或更高 +@msg `writes` needs the permission `doc.write` `writes` 需要權限 `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} 不是文字、影像或符號範例 +@msg the text of type given as `truncated` can't be changed 以 `truncated` 提供的文字物件,其文字無法變更 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 必須是最多 {MAX_INPUT_RUNS} 個項目的清單 +@msg type needs at least one run 文字至少需要一個文字段 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文字 {bytes} 位元組(上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落 {paragraphs} 個(上限 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整個輸出中的文字超過 {MAX_INPUT_TEXT_TOTAL} 位元組 +@msg unknown key '{k}' 未知的鍵 '{k}' +@msg must be a list of 6 numbers 必須是 6 個數字的清單 +@msg a number is out of range (limit ±{MAX_COORD}) 有數字超出範圍(上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point 會把物件壓扁成一條線或一個點 +@msg an object flattened to a line or a point can't be placed again 已壓扁成線或點的物件無法重新放置 +@msg must be a number from 0 to 1 必須是 0 到 1 之間的數字 +@msg must be the name of a symbol 必須是符號的名稱 +@msg '{shown}' is not a symbol in this document '{shown}' 不是此文件中的符號 +@msg a run must be {{"text", "style", "inline"?}} 文字段必須是 {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` 含有行內圖形的字元 +@msg inline graphics can't be added, removed, reordered or changed 行內圖形無法新增、移除、重新排序或變更 +@msg the characters of threaded type can't be changed 串連文字的字元無法變更 +@msg the characters of type with ruby can't be changed 含注音的文字,其字元無法變更 +@msg expected {count} paragraph styles, one per paragraph 應有 {count} 個段落樣式,每個段落一個 +@msg the document has no Kinsoku set named '{shown}' 文件中沒有名為 '{shown}' 的 Kinsoku 集 +@msg must be 1-{MAX_FAMILY} printable characters 必須是 1-{MAX_FAMILY} 個可列印字元 Read the objects it is given, and the document's settings, artboards, layers and swatches 讀取交給它的物件,以及文件的設定、工作區域、圖層和色票 @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` 必須列出互不相同的部分:settings、artboards、layers 或 swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` 僅適用於 `api` 3 或更高、具有權限 `doc.read` 的濾鏡或帶 `commands` 的即時效果 diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 6a6c34a5e6..30b6edfb49 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -207,6 +207,39 @@ mod tests { assert!(appearance.contains(" String { + let last = icon.rsplit(" f32 { + icon.split(r#"fill-opacity=""#).nth(1).and_then(|s| s.split('"').next()).and_then(|v| v.parse().ok()).unwrap_or(1.0) + }; + let icons = [("butt", svg("dc-cap-butt")), ("round", svg("dc-cap-round")), ("square", svg("dc-cap-square"))]; + let butt_end = end_line(&icons[0].1); + assert!(butt_end.starts_with('M') && butt_end.contains('V'), "the butt cap icon ends with a vertical end-of-path line: {butt_end}"); + for (name, icon) in &icons { + assert_eq!(end_line(icon), butt_end, "the {name} cap icon marks the end of the path where the butt cap icon does"); + assert!(stroke_opacity(icon) < 1.0, "the {name} cap icon's stroke is lighter than its end-of-path line"); + } + // The stroke bar, everything before the end-of-path line, shows each cap differently. + let bar = |icon: &str| -> String { icon.rsplit_once(", /// Messages waiting for the dialog that shows them. pub(crate) told: dialogs::host::Told, + /// The Type tool's pending edit, kept even when the dialog closes without a prompt answer. + pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 0ce4ff457a..5291000751 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -83,14 +83,14 @@ pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke}; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; -pub(crate) use labels::{holds_plugin_commands, lists_plugin}; +pub(crate) use labels::{holds_plugin_commands, item_shortcut_in, lists_plugin}; pub(crate) use model::{MAC_LABELS, home_key, home_showing}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; -pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; +pub(crate) use state::{command_shortcuts, why_off}; pub(crate) use submenus::PATH_EFFECTS; pub use tree::{Listed, menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index bce650899b..3957d294b6 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -1,9 +1,10 @@ use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; -use super::state::{hidden_when_disabled, shortcut_of}; +use super::state::{command_shortcuts, hidden_when_disabled}; use super::tree::menu_tree; use super::ui_commands::UI_COMMANDS; use super::{Node, Value, VectorcraftApp, unbound}; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; +use vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES; /// Label for toggles whose text flips (Outline/Preview, Hide/Show …). pub fn dynamic_label(app: &VectorcraftApp, id: &str, label: &str) -> String { @@ -99,6 +100,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), None => label.into(), }, + // Repeat Pathfinder is named after the Shape Mode or Pathfinder operation that ran last. + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => format!("Repeat {name}"), + None => label.into(), + }, // Apply Last Filter and Last Filter… are named after the filter that ran last. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => format!("Apply {name}"), @@ -129,6 +135,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some(text) } +/// The Pathfinder panel's name for the Shape Mode or Pathfinder operation that ran last. +fn last_pathfinder_label(app: &VectorcraftApp) -> Option<&'static str> { + app.last_pathfinder.as_deref().and_then(crate::panels::pathfinder::operation_label) +} + /// Does the menu item `id` show a name that is user, file or system data rather than an interface /// label: a recent file, a saved view, a font, a user library or preset, a custom workspace, a /// plug-in, an SVG filter, a script of the Scripts folder? Such names are shown as they are, never @@ -201,6 +212,10 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } None => crate::i18n::tr_id(lang, id, label).to_string(), }, + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => fmt(tl!("Repeat {name}"), &[("name", tl!(name))]), + None => crate::i18n::tr_id(lang, id, label).to_string(), + }, // The filter's name is the plug-in's own text, never translated. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => fmt(tl!("Apply {filter}"), &[("filter", &name)]), @@ -250,11 +265,18 @@ pub(super) fn spelling_item_label(id: &str, p: &Value) -> Option { /// The shortcut a menu item shows: its command's (items without params), a panel's for the /// Window menu's `window.panel {panel}` items, an effect's for the Effect menu's items, or a filter -/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. +/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. Settings' first page shows +/// Preferences' shortcut. pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option { + item_shortcut_in(&command_shortcuts(app), id, p) +} + +/// [`item_shortcut`] with each entry's command looked up in `chord` ([`command_shortcuts`]). +pub(crate) fn item_shortcut_in(chord: &dyn Fn(&CommandRef) -> Option, id: &str, p: &Value) -> Option { let field = |name: &str| p.get(name).and_then(Value::as_str); let key = match (id, field("panel")) { ("window.panel", Some(panel)) => format!("panel:{panel}"), + ("edit.preferences", _) if field("category") == PREF_CATEGORIES.first().copied() => id.to_string(), ("effect.dialog" | "effect.apply", _) => format!("effect:{}", field("effect")?), ("plugin.dialog", _) => format!("plugin:{}", field("id")?), // The Artboard tool's canvas menu passes the point its Paste goes to. @@ -265,7 +287,7 @@ pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option _ if p.is_null() => id.to_string(), _ => return None, }; - shortcut_of(app, &key) + chord(&crate::keymap::command_of(&key)) } /// Labels only the canvas context menu ([`context_items`]) shows, so the catalog tests can insist diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 421b763038..f00174b4ac 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -485,7 +485,8 @@ impl Build<'_> { match id { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. - "window.panel" => { + // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. + "window.panel" | "edit.preferences" if !params.is_null() => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 62fbc97da3..b9004c1ebb 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -1,12 +1,13 @@ //! The macOS menu bar on craft-menu's native menu: installed once, polled and run before the UI //! each frame, and synced after it. +use craft::keymap::{Chord, CommandRef}; use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac, mac_layout}; use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder}; use crate::VectorcraftApp; use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label}; -use crate::menus::unbound; +use crate::menus::{command_shortcuts, item_shortcut_in, unbound}; /// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its /// translation of the labels the layout writes itself. @@ -56,16 +57,20 @@ pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { app.services.native_menu = Some(menu); } -/// The menus with each item's title, and whether it is on and checked, as they are now: AppKit's items show their own, -/// where the in-window bar reads them from the command states. Read here and not from the model, which is built before -/// the frame's input: a drag released or an Escape in this frame already shows. +/// The menus with each item's title, shortcut, and whether it is on and checked, as they are now: AppKit's items show +/// their own, where the in-window bar reads them from the command states. Read here and not from the model, which is +/// built before the frame's input: a drag released or an Escape in this frame already shows. Each item's shortcut is +/// the one the menus show for it ([`crate::menus::item_shortcut`]), else its command's chord in the keymap, the user's +/// set included, as the in-window bar's rows show it. It is also the item's key equivalent. The model's own shortcuts +/// (Window rows, Settings' first page) are read again here: the model built before the window's first keymap has none. fn stated(app: &VectorcraftApp) -> MenuBar { - fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, nodes: &mut [Node]) { + fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, chord: &dyn Fn(&CommandRef) -> Option, nodes: &mut [Node]) { for node in nodes { match node { Node::Item(it) if unbound(&it.command.id) => it.enabled = false, Node::Item(it) => { let (id, params) = (it.command.id.as_str(), &it.command.params); + it.shortcut = item_shortcut_in(chord, id, params).or_else(|| chord(&it.command)); if let Some((enabled, checked)) = crate::menus::shown_state(app, id, params) { it.enabled = enabled; if let Some(on) = checked { @@ -78,15 +83,16 @@ fn stated(app: &VectorcraftApp) -> MenuBar { it.label = title; } } - Node::Submenu { children, .. } => walk(app, lang, children), + Node::Submenu { children, .. } => walk(app, lang, chord, children), _ => {} } } } let mut bar = app.menus.bar.clone(); let lang = crate::i18n::current(); + let chord = command_shortcuts(app); for menu in &mut bar.menus { - walk(app, lang, &mut menu.children); + walk(app, lang, &chord, &mut menu.children); } bar } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b608e72feb..bce31f0fd0 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -2,7 +2,7 @@ use super::run::{normalize_panel, toolbar_double, toolbar_panel}; use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; use craft::ui::runtime::commands; /// Checked state for toggle items. @@ -190,17 +190,33 @@ pub fn plugin_revision() -> u64 { /// the window's keymap, under the user's set in use (Edit → Keyboard Shortcuts). `None` before the /// window's first frame. pub fn shortcut_of(app: &VectorcraftApp, key: &str) -> Option { - let ctx = app.ui_ctx.as_ref()?; - let command = crate::keymap::command_of(key); - let window = commands::keymap(ctx)?; - let (now, built) = (&*app.shortcut_overrides, window.overrides()); - if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { - return commands::chord(ctx, &command); - } + command_shortcuts(app)(&crate::keymap::command_of(key)) +} + +/// The shortcut each command shows, as [`shortcut_of`] reads it, for a caller that asks for many: the +/// keymap is read once. `None` for every command before the window's first frame. +pub(crate) fn command_shortcuts(app: &VectorcraftApp) -> impl Fn(&CommandRef) -> Option + '_ { + let ctx = app.ui_ctx.as_ref(); + let window = ctx.and_then(commands::keymap); // The window's keymap takes a change of the set (`shortcuts.set`) from its next frame; the set is read until then. - let mut keymap = (*window).clone(); - keymap.set_overrides(now.clone()); - keymap.bindings(&command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + let pending = window.as_ref().and_then(|window| { + let (now, built) = (&*app.shortcut_overrides, window.overrides()); + if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { + return None; + } + let mut keymap = (**window).clone(); + keymap.set_overrides(now.clone()); + Some(keymap) + }); + move |command| { + let ctx = ctx.filter(|_| window.is_some())?; + match &pending { + None => commands::chord(ctx, command), + Some(keymap) => { + keymap.bindings(command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + } + } + } } /// Is a command currently enabled? diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index c1ea0a7b84..2e1ce41559 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -890,15 +890,11 @@ fn not_mac() -> Platforms { fn app_menu() -> Vec { let settings: Vec = vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() - .enumerate() - .map(|(i, page)| { - let mut item = - Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings); - // Only the first page carries Preferences' shortcut. - if i == 0 { - item.shortcut = crate::shortcut_editor::default_command_shortcut("edit.preferences").and_then(crate::keymap::stored::parse_vc); - } - Node::Item(item) + // Only the first page carries Preferences' shortcut, which the menus' model gives it from the keymap. + .map(|page| { + Node::Item( + Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings), + ) }) .collect(); let mut language = vec![cp("Automatic", "app.language", json!({ "lang": "auto" })), Sep]; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 6fa832b29c..7dc1d02803 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -659,19 +659,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", "", "{}"), ( @@ -1526,7 +1526,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", diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs index 9089ede4f2..f9b8f00543 100644 --- a/crates/ui-egui/src/original_editor.rs +++ b/crates/ui-egui/src/original_editor.rs @@ -54,6 +54,12 @@ pub(crate) fn reset(app: &mut VectorcraftApp) { app.original_editor.choice = Choice::default(); } +/// `prefs.reset`: the saved choice goes back to the default, and the next Preferences shows it. +pub(crate) fn reset_saved(app: &mut VectorcraftApp) { + app.ui.original_editor = Choice::default(); + reset(app); +} + pub(crate) fn cancel(app: &mut VectorcraftApp) { open(app); } @@ -262,6 +268,32 @@ mod tests { assert!(app.ui.original_editor.path.is_none()); } + /// `prefs.reset` of every category or of File Handling, alone or as a batch step, resets the + /// saved choice; a reset of another category keeps it. + #[test] + fn prefs_reset_resets_the_saved_choice_with_file_handling() { + let (mut app, picker) = app(); + prefs_dialog::cancel(&mut app); + let mine = editor("prefs-reset"); + let chosen = |app: &mut VectorcraftApp| { + prefs_dialog::open(app, Some("File Handling")); + choose(app, &picker, Some(&mine)).unwrap(); + prefs_dialog::confirm(app).unwrap(); + assert!(app.ui.original_editor.path.is_some()); + }; + chosen(&mut app); + app.run("prefs.reset", json!({"category": "General"})).unwrap(); + assert!(app.ui.original_editor.path.is_some(), "General keeps the choice"); + app.run("prefs.reset", json!({"category": "File Handling"})).unwrap(); + assert!(app.ui.original_editor.path.is_none(), "File Handling resets it"); + chosen(&mut app); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("command.batch", json!({"commands": [{"command": "prefs.reset", "params": {}}]})).unwrap(); + assert!(app.ui.original_editor.path.is_none(), "every category, as a batch step"); + prefs_dialog::open(&mut app, Some("File Handling")); + assert!(app.original_editor.choice.path.is_none(), "Preferences shows the default"); + } + #[test] #[cfg(not(target_arch = "wasm32"))] fn original_editor_routing_and_errors() { diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index dce3c4aa7b..678f797822 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use craft::behavior::{Axis, DockSide, IconId}; use craft::ui::buttons::IconButton; -use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, Tracked}; +use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked}; use craft::ui::docking::{ ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions, @@ -155,6 +155,12 @@ fn rail_owner_among(toolbars: impl Iterator, id: &str) -> Option Workspace { + builtin_workspace(fronts, 1) +} + +/// [`default_workspace`] with the Tools panel laying its tools out in `tools_steps` columns, as a +/// built-in workspace defines it. +pub(crate) fn builtin_workspace(fronts: &[&str], tools_steps: u16) -> Workspace { let mut placed: Vec = Vec::new(); let mut group = |ids: &[&str]| { let fresh: Vec = ids.iter().filter(|id| registered(id) && !placed.iter().any(|p| p == *id)).map(|id| (*id).to_owned()).collect(); @@ -168,7 +174,7 @@ pub(crate) fn default_workspace(fronts: &[&str]) -> Workspace { if !icons.is_empty() { columns.push(Column::new(icons).with_iconic(true)); } - let tools = Column::new(vec![Group::new(vec![crate::toolbar::TOOLS.to_owned()], 0)]).with_steps(1); + let tools = Column::new(vec![Group::new(vec![crate::toolbar::TOOLS.to_owned()], 0)]).with_steps(tools_steps); let centre = Node::split(Axis::X, BESIDE_DOCK, Node::tabs(vec![CANVAS.to_owned()], 0), Node::dock(DockEdge::End, columns)); let root = Node::split(Axis::X, BESIDE_DOCK, Node::dock(DockEdge::Start, vec![tools]), centre); Workspace::new(Layout::new(Some(root), Vec::new())) @@ -267,7 +273,7 @@ fn dock_columns(layout: &Layout) -> Vec<&Column> { } /// The columns of the dock on `edge`, from the window edge inwards; none when that edge has no dock. -fn edge_columns(layout: &Layout, edge: DockEdge) -> &[Column] { +pub(crate) fn edge_columns(layout: &Layout, edge: DockEdge) -> &[Column] { let dock = layout.dock_path(edge).and_then(|path| node_at(layout.root.as_ref()?, &path)); match dock { Some(Node::Dock { columns, .. }) => columns, @@ -1113,14 +1119,18 @@ pub(crate) fn place_floating(app: &mut VectorcraftApp, panel: &str, pos: egui::P } // A rail's window is a stepped column, which the dock fits to the rail's grid; it keeps the steps it had. let steps = is_rail(&id).then(|| column_of(layout, &id).and_then(|(_, column)| column.steps).unwrap_or(1)); - actions.push(match floating_window(layout, &id) { - Some(window) if window.panels().count() == 1 => Action::move_floating(id.clone(), rect), - _ => Action::float(id.clone(), rect), - }); + let ctx = app.ui_ctx.clone(); + match floating_window(layout, &id) { + // An open OS window moves with its window: the dock keeps it where its record says. + Some(window) if window.panels().count() == 1 => { + actions.push(Action::move_floating(id.clone(), rect)); + actions.extend(native_moved(ctx.as_ref(), window, rect)); + } + _ => actions.push(Action::float(id.clone(), rect)), + } if let Some(steps) = steps { actions.push(Action::set_column_steps(id, steps)); } - let ctx = app.ui_ctx.clone(); apply(app, ctx.as_ref(), actions).map(drop) } @@ -1192,9 +1202,10 @@ impl PanelSpecs for Specs { if panel == CANVAS { return spec.canvas(); } + // A toolbar's column is as wide as its grid's steps; every other panel is at least PANEL_MIN_WIDTH wide. let spec = match self.grids.iter().find(|(rail, _)| rail == panel) { Some((_, grid)) => spec.grid(*grid), - None => spec, + None => spec.limits(SizeLimits::at_least(egui::vec2(PANEL_MIN_WIDTH, 0.0))), }; let icon = crate::state::rail_panel(panel).map(|p| p.2).or_else(|| crate::panels::library_panel::parse(panel).map(|_| "library")); match icon { diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 5a2f8ffecb..6516f7132c 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -255,15 +255,31 @@ fn native_tab_group(h: &mut Harness) -> ViewportId { fn a_group_float_of_a_tab_group_resizes_its_native_window() { let mut h = Harness::new(); let viewport = native_tab_group(&mut h); - let id = floating_window(&layout_of(&h.app.ui), "swatches").unwrap().id; + let id = floating_window(layout_of(&h.app.ui), "swatches").unwrap().id; let before = h.host.borrow().windows[&viewport].rect; h.app.run("window.panel.float", json!({"panel": "swatches", "group": true, "width": 400})).unwrap(); h.frames(3); - assert_eq!(floating_window(&layout_of(&h.app.ui), "swatches").unwrap().id, id); + assert_eq!(floating_window(layout_of(&h.app.ui), "swatches").unwrap().id, id); assert_eq!(h.viewport("color"), viewport); assert_eq!(h.host.borrow().windows[&viewport].rect, Rect::from_min_size(before.min, vec2(400.0, before.height()))); } +/// `window.toolbar.float` with x, y moves the OS window a toolbar made with New Toolbar already has. +#[test] +fn floating_a_toolbar_at_a_point_moves_its_native_window() { + let mut h = Harness::new(); + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 240, "y": 160})).unwrap(); + h.frames(3); + let panel = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&h.app.ui, "Mine").unwrap().id); + let viewport = h.viewport(&panel); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(240.0, 160.0)); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 300, "y": 220})).unwrap(); + h.frames(3); + assert_eq!(h.viewport(&panel), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(300.0, 220.0)); +} + #[test] fn keys_typed_in_a_native_window_run_the_main_windows_shortcuts() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index dd996ee1dd..cd2bfb91c9 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -983,3 +983,44 @@ fn cycle_options_rejects_panels_without_sizes() { } assert_eq!(h.layout(), before, "a refusal changes nothing"); } + +/// The width of the body of the panel titled `title` as the last frame drew it. +fn body_width(h: &Harness, title: &str) -> f32 { + h.nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::TabPanel && node.label() == Some(title)) + .and_then(|(_, node)| node.bounds()) + .map(|b| (b.x1 - b.x0) as f32) + .unwrap_or_else(|| panic!("{title}'s body is drawn")) +} + +/// A floating panel's side dragged in past `PANEL_MIN_WIDTH` stops at the minimum. +#[test] +fn a_floating_panel_resized_past_the_panel_minimum_stops_at_it() { + let mut h = Harness::new(); + h.app.run("window.panel.float", json!({"panel": "stroke", "x": 300, "y": 200, "width": 400, "height": 300})).unwrap(); + h.frames(3); + let before = body_width(&h, "Stroke"); + assert!((before - 400.0).abs() < 1.0, "a float wider than the minimum keeps its width: {before}"); + let rect = floating_window(&h.layout(), "stroke").expect("Stroke floats").rect; + // The window's right side is its resize grip; the drag goes 300 pt in, well past the minimum. + let grip = pos2(rect.right() - 1.0, rect.center().y); + h.drag(grip, grip - vec2(300.0, 0.0)); + let after = body_width(&h, "Stroke"); + assert!(after < before - 1.0, "the drag narrowed the window: {before} to {after}"); + assert!(after >= PANEL_MIN_WIDTH - 0.5, "dragged in past the minimum: {after}"); +} + +/// A docked column saved narrower than `PANEL_MIN_WIDTH` is drawn at the minimum. +#[test] +fn a_docked_column_is_never_narrower_than_the_panel_minimum() { + let mut h = Harness::new(); + let mut layout = h.layout(); + let columns = end_dock_mut(&mut layout).expect("the default layout has an end dock"); + for column in columns.iter_mut().filter(|column| !column.iconic) { + column.width = Some(100.0); + } + h.set_layout(layout); + h.frames(3); + assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties")); +} diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 19ab69b734..68e297cd44 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -324,10 +324,18 @@ pub(crate) fn fit_has_art(app: &VectorcraftApp, indices: &[usize]) -> bool { /// isn't selected becomes the only selected one, and the menu's facts are measured. pub(crate) fn right_click(app: &mut VectorcraftApp, p: vectorcraft_geom::Point) { let Some(st) = app.session.active() else { return }; - let (uid, n, hit) = (st.uid, st.doc.artboards.len(), st.doc.artboard_at(p)); + let (n, hit) = (st.doc.artboards.len(), st.doc.artboard_at(p)); if let Some(i) = hit.filter(|i| !picked(app, n).contains(i)) { select(app, i); } + measure_menu(app, p); +} + +/// The canvas menu's facts for the selected artboards, with the menu opened at `p` (a right-click, or the Menu key or +/// Shift+F10, which select nothing). +pub(crate) fn measure_menu(app: &mut VectorcraftApp, p: vectorcraft_geom::Point) { + let Some(st) = app.session.active() else { return }; + let (uid, n) = (st.uid, st.doc.artboards.len()); let all = picked(app, n); let any_empty = vectorcraft_engine::find_command("artboard.deleteEmpty").is_some_and(|c| (c.enabled)(&app.session).is_ok()); let any_art = fit_has_art(app, &all); diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 88ee1d6f6f..87eb9f9880 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -31,13 +31,32 @@ pub struct DocInfoView { } /// A `label: value` row. `label` is shown as given: translate an interface label first, a name -/// stays as it is. -pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { +/// stays as it is. Whether the value was clicked to copy it: a click with no key held, other than +/// the second or third click of a double or triple click. +pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { + let mut clicked = false; Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| { Text::new(label.to_string()).shade(Shade::Muted).show(ui); - // The value can be selected and copied (#8432). - SelectableText::new(label.to_string(), &value).show(ui); + // The value can be selected and copied, and a click copies all of it (#8432). A drag selects + // and a Shift-click extends the selection, so neither copies. + let shown = SelectableText::new(label.to_string(), value).show(ui); + // The click's own position and keys: a move or a key change after the release in the same + // frame leaves the pointer and the held keys elsewhere. A frame with more than one release + // copies nothing, since the click flags below do not say which release they describe. + let area = shown.interact_rect.intersect(ui.clip_rect()); + let primary = egui::PointerButton::Primary; + let release = ui.input(|i| { + let mut releases = i.events.iter().filter_map(|e| match e { + egui::Event::PointerButton { pos, button, pressed: false, modifiers } if *button == primary => Some((*pos, *modifiers)), + _ => None, + }); + let release = releases.next().filter(|_| releases.next().is_none()); + let single = i.pointer.button_clicked(primary) && !i.pointer.button_double_clicked(primary) && !i.pointer.button_triple_clicked(primary); + release.filter(|_| single) + }); + clicked = release.is_some_and(|(pos, keys)| keys.is_none() && area.contains(pos) && ui.ctx().layer_id_at(pos) == Some(ui.layer_id())); }); + clicked } /// `document.info` with its categories, fetched again only when the document, the scope or the @@ -64,6 +83,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone(); + let mut copy = None; Stack::new().show(ui, |ui, _| { let sections = i["sections"].as_array().map_or(&[][..], Vec::as_slice); let shown = sections.iter().filter(|s| category.is_empty() || s["id"] == category.as_str()); @@ -92,11 +112,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui); } else { let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); - row(ui, super::label_or_name(label, !named.contains(&k)), shown); + if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) { + copy = Some(shown); + } } } } }); + if let Some(text) = copy { + app.clipboard_out = Some(text); + app.status("Copied the value"); + } } /// A Brushes row's value in the interface language: the brush's type (`Art Brush`), or that the diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index e3baa39a27..e2c724fe2f 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -1,8 +1,9 @@ //! Window → Flattener Preview: what flattening the document would touch (`flattener.preview`), //! highlighted in red over a grey preview of the art. Refresh takes a new snapshot of the //! document; Highlight picks what shows; Overprints, the preset and the options (Show Options in -//! the panel menu) set how it flattens. The preview is a `PreviewPane`: the wheel and the pane's -//! gestures zoom and pan, and a double click fits. +//! the panel menu) set how it flattens. The preview is a `PreviewPane`: a click zooms in about the +//! point clicked and an Alt-click (Option on macOS) zooms out, a drag pans, Ctrl or Cmd with the +//! wheel zooms, and a double click fits. The zoom row under it zooms from the keyboard. //! //! The settings live in `UiState::flattener_preview` (`ui.inspect`); `ui.flattenerPreview` sets //! them and refreshes. The snapshot, the view and the texture live in [`FlattenerPreviewModel`] @@ -10,12 +11,13 @@ use std::sync::Arc; +use craft::behavior::CanvasTransform; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; -use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView}; +use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom}; use craft::ui::pickers::Select; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::runtime::env::Env; @@ -258,6 +260,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// The preview: the whole snapshot rendered once per [`Key`], grey under a highlight with the /// highlighted art in the theme's error colour, in a pane that zooms and pans it. +/// A click zooms in 2× about the point clicked and an Alt-click zooms out 2×, within [`fitting_view`]'s range. fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, h: Highlight, overprints: Overprints) { let FlattenerPreviewModel { shot, renderer, view, drawn, .. } = &mut app.flattener_preview; let Some(shot) = shot.as_ref() else { return }; @@ -282,12 +285,46 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, // At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit. let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height()); let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32); - let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view).aspect(ASPECT).show(ui); - if let Some(v) = out.view { + let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) + .aspect(ASPECT) + .click_centres(false) + .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")) + .show(ui); + *view = match out.clicked { + Some(at) => { + let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 }; + zoomed_about(&out.shown, at, size, out.response.rect.size(), factor) + } + // The view as drawn, so the zoom row steps from what is on screen while the pane fits. + None => out.view.unwrap_or(out.shown), + }; + // The zoom row zooms from the keyboard too. + if let Some(v) = PreviewZoom::new(view).show(ui).view { *view = v; } } +/// `shown` zoomed by `factor` within its zoom range, keeping the point `at` of a picture of `picture` points (from its +/// top-left corner) under the pointer, settled in a well of `well` points. A zoom out to the fit or past it returns +/// to the fitting view. +fn zoomed_about(shown: &PreviewView, at: egui::Pos2, picture: egui::Vec2, well: egui::Vec2, factor: f32) -> PreviewView { + let t = shown.transform; + let fit = PreviewPane::fit_view(picture, well, &shown.range); + let scale = (t.scale * factor).min(*shown.range.end()); + let mut next = shown.clone(); + if scale <= fit.scale { + next.transform = PreviewPane::settled(fit, picture, well); + next.fit = true; + return next; + } + // Where the point lies from the well's center; the new offset keeps it there at the new zoom. + let about = (at.to_vec2() - picture / 2.0) * t.scale + t.offset; + let offset = about - (about - t.offset) * (scale / t.scale); + next.transform = PreviewPane::settled(CanvasTransform::new(scale, offset), picture, well); + next.fit = false; + next +} + /// `visible` of the snapshot at most `px` pixels: in colour without a highlight, else in grey with /// the highlighted art in `color`. fn render( @@ -446,4 +483,95 @@ mod tests { let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); assert_eq!(back.flattener_preview, app.ui.flattener_preview); } + + /// The panel in a fixture, and the preview pane's bounds. + fn shown_pane() -> (std::rc::Rc>, craft::ui::testing::Fixture, egui::Rect) { + let app = std::rc::Rc::new(std::cell::RefCell::new(app())); + let drawn = std::rc::Rc::clone(&app); + let mut fixture = craft::ui::testing::Fixture::new(move |ui| show(&mut drawn.borrow_mut(), ui)); + fixture.settle(); + let pane = fixture.by_label("Flattener Preview").unwrap_or_else(|| panic!("no preview pane")); + (app, fixture, pane.rect) + } + + /// One click at `at` with `modifiers` held, far enough from the last that the two make no double click. + fn click(fixture: &mut craft::ui::testing::Fixture, at: egui::Pos2, modifiers: egui::Modifiers) { + fixture.advance(2.0).hold(modifiers).click_at(at).hold(egui::Modifiers::NONE).idle(1); + } + + fn view(app: &std::rc::Rc>) -> PreviewView { + app.borrow().flattener_preview.view.clone() + } + + #[test] + fn a_click_zooms_in_about_the_point_and_an_alt_click_zooms_out() { + let (app, mut fixture, well) = shown_pane(); + assert!(view(&app).fit); + let at = well.center() + egui::vec2(well.width() * 0.1, well.height() * 0.1); + click(&mut fixture, at, egui::Modifiers::NONE); + let zoomed = view(&app); + assert!(!zoomed.fit, "a click leaves fit"); + // 1 is about the fit: the picture is sized to the well. + assert!(zoomed.transform.scale > 1.5, "a click zooms in: {zoomed:?}"); + // The point clicked stays under the pointer: off center, the picture moved away from the well's center. + assert!(zoomed.transform.offset.x < 0.0 && zoomed.transform.offset.y < 0.0, "{zoomed:?}"); + click(&mut fixture, at, egui::Modifiers::NONE); + let closer = view(&app); + assert!(closer.transform.scale > zoomed.transform.scale * 1.9, "a second click zooms in further"); + click(&mut fixture, at, egui::Modifiers::ALT); + let out = view(&app); + assert!((out.transform.scale - zoomed.transform.scale).abs() < 1e-3, "an Alt-click zooms back out: {out:?}"); + click(&mut fixture, at, egui::Modifiers::ALT); + assert!(view(&app).fit, "an Alt-click to the fit returns to fit"); + } + + #[test] + fn a_click_with_alt_latched_by_the_app_zooms_out() { + let mut app = app(); + let mut frames = craft::ui::testing::Frames::new(); + let mut pane = None; + for _ in 0..60 { + frames.frame(Vec::new(), |ui| show(&mut app, ui)); + let tree = frames.tree(); + pane = tree + .keys() + .into_iter() + .filter(|key| tree.name_of(*key) == Some("Flattener Preview")) + .filter_map(|key| tree.bounds_of(key)) + .max_by(|a, b| a.area().total_cmp(&b.area())); + if pane.is_some() { + break; + } + } + let well = pane.unwrap_or_else(|| panic!("no preview pane")); + let at = well.center(); + let primary = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let click = |frames: &mut craft::ui::testing::Frames, app: &mut VectorcraftApp| { + frames.advance(2.0); + frames.frame(vec![egui::Event::PointerMoved(at), primary(true)], |ui| show(app, ui)); + frames.frame(vec![primary(false)], |ui| show(app, ui)); + frames.idle(1, |ui| show(app, ui)); + }; + click(&mut frames, &mut app); + assert!(!app.flattener_preview.view.fit, "a click zooms in"); + // Alt held for the user by the app (the Modifier Keys panel), with no Alt key down. + frames.latched(craft::keymap::Mods { alt: true, ..Default::default() }); + click(&mut frames, &mut app); + assert!(app.flattener_preview.view.fit, "a click with Alt latched zooms back out to fit"); + } + + #[test] + fn click_zoom_stays_inside_the_zoom_range() { + let (app, mut fixture, well) = shown_pane(); + // Alt-click at fit stays at fit. + click(&mut fixture, well.center(), egui::Modifiers::ALT); + assert!(view(&app).fit, "no zoom below the fit"); + for _ in 0..6 { + click(&mut fixture, well.center(), egui::Modifiers::NONE); + } + let most = view(&app); + assert!(most.transform.scale <= *most.range.end(), "no zoom past the range: {most:?}"); + assert!(!most.can_zoom_in(), "clicks reach the most zoom: {most:?}"); + } } diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 609056dffc..b2131ae600 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -25,7 +25,7 @@ //! gradient behind the active proxy, keeping its placement (`gradient.presets.*`). Hide Presets in //! the panel menu leaves the row out. -use craft::behavior::{EditEvent, IconId, Mixed}; +use craft::behavior::{ColumnWidth, EditEvent, IconId, Mixed}; use craft::color_ui::gradient::stops::AltDrop; use craft::color_ui::ui::DropperButton; use craft::color_ui::ui::gradient::{ColorStop, GradientEditor, GradientStops, StopDrop, StopRef, StopRow, StopRows, StopRules}; @@ -35,7 +35,8 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Checkbox, Radio, RadioGroup, Segmented, Swatch}; use craft::ui::contract::{Bind, EditResponse, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::{Divider, Icon, Shade, Text}; -use craft::ui::layout_components::{Row, Stack}; +use craft::ui::layout::CellAlign; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; @@ -66,6 +67,9 @@ use crate::panel_drag::PanelDrag; /// The Angle field's preset menu, degrees. const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0]; +/// The header's columns: the thumbnail with its swatch menu, and the type buttons with Edit Gradient, each as wide +/// as its content. +const BESIDE: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; /// The Aspect Ratio field's preset menu, percent. const ASPECT_PRESETS: [f64; 9] = [10.0, 25.0, 50.0, 75.0, 100.0, 150.0, 200.0, 300.0, 400.0]; // PLAN: the sheet drops `HIDE_OPTIONS` and `HIDE_PRESETS`, but each key is read by `show`, `menu_states` and `run`; kept as the op.A5 hide-store keys. @@ -171,7 +175,7 @@ pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) { (GradientKind::Diamond, "dc-grad-diamond", tl!("Diamond Gradient")), (GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")), ]); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Type:")).shade(Shade::Muted).show(ui); let pick = Segmented::new(tl!("Type"), lit(kind), &entries).show(ui); if let Some(k) = pick.events.committed() { @@ -309,19 +313,23 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let kind = g.gradient.kind; let hidden = part_hidden(app, HIDE_OPTIONS); // Header: the thumbnail and its swatch menu, the type buttons and Edit Gradient. - Row::new().show(ui, |ui, _| { - fill_box(app, ui, &g, is_grad); - if hidden { + if hidden { + Row::new().show(ui, |ui, _| { + fill_box(app, ui, &g, is_grad); super::proxy(app, ui); - return; - } - Stack::new().show(ui, |ui, _| { - type_row(app, ui); - if Button::new(tl!("Edit Gradient")).show(ui).clicked() { - app.select_tool("gradient"); - } }); - }); + } else { + // The type buttons go beside the thumbnail, level with its top, or under it in a narrow panel. + Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| fill_box(app, ui, &g, is_grad)); + Stack::new().show(ui, |ui, _| { + type_row(app, ui); + if Button::new(tl!("Edit Gradient")).show(ui).clicked() { + app.select_tool("gradient"); + } + }); + }); + } let freeform = is_grad && kind == GradientKind::Freeform; let points = is_grad && edits_points(app, &g); if hidden { @@ -458,7 +466,7 @@ fn method_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr ] .map(|(m, label)| Entry::new(m, label)); let current = g.gradient.method; - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Method:")).shade(Shade::Muted).show(ui); let pick = Select::new(tl!("Method"), Bind::given(current), &methods).enabled(is_grad).show(ui); if let Some(m) = pick.events.committed().filter(|m| **m != current) { @@ -475,7 +483,7 @@ fn spread_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr .map(|(s, label)| Entry::new(s, label)); let current = g.gradient.spread; let presets = number_presets(&REPEAT_PRESETS, ""); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Spread:")).shade(Shade::Muted).show(ui); let pick = Select::new(tl!("Spread"), Bind::given(current), &spreads).enabled(is_grad).show(ui); if let Some(s) = pick.events.committed().filter(|s| **s != current) { @@ -690,34 +698,42 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } }); } - Row::new().show(ui, |ui, _| { - Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); - let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); - let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); - apply_number(app, &opacity.edit, |app, v, phase| { - let Some(i) = sel else { return }; - let mut v2 = stops.clone(); - if let Some(s) = v2.get_mut(i) { - s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; - } - set_stops(app, &v2, Some(i), phase); + // In a narrow panel the row wraps; each caption stays on the line of its field. + Row::new().wrap(true).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); + let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); + let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); + apply_number(app, &opacity.edit, |app, v, phase| { + let Some(i) = sel else { return }; + let mut v2 = stops.clone(); + if let Some(s) = v2.get_mut(i) { + s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; + } + set_stops(app, &v2, Some(i), phase); + }); }); - Text::new(tl!("Location:")).shade(Shade::Muted).show(ui); - let loc = match (mid, stop) { - (Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)), - (None, Some(s)) => percent(s.offset), - _ => 0.0, - }; - let location = - NumberField::new(tl!("Location"), Bind::given(Some(loc))).range(0.0..=100.0).unit("%").enabled(sel.is_some() || mid.is_some()).show(ui); - apply_number(app, &location.edit, |app, v, phase| { - let v = (v / 100.0) as f32; - if let Some(m) = mid { - set_stops(app, &set_midpoint(stops, m, v), None, phase); - } else if let Some(i) = sel { - let (v2, ni) = move_stop(stops, i, v); - set_stops(app, &v2, Some(ni), phase); - } + Row::new().show(ui, |ui, _| { + Text::new(tl!("Location:")).shade(Shade::Muted).show(ui); + let loc = match (mid, stop) { + (Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)), + (None, Some(s)) => percent(s.offset), + _ => 0.0, + }; + let location = NumberField::new(tl!("Location"), Bind::given(Some(loc))) + .range(0.0..=100.0) + .unit("%") + .enabled(sel.is_some() || mid.is_some()) + .show(ui); + apply_number(app, &location.edit, |app, v, phase| { + let v = (v / 100.0) as f32; + if let Some(m) = mid { + set_stops(app, &set_midpoint(stops, m, v), None, phase); + } else if let Some(i) = sel { + let (v2, ni) = move_stop(stops, i, v); + set_stops(app, &v2, Some(ni), phase); + } + }); }); let can_del = sel.is_some() && stops.len() > MIN_STOPS; let delete = IconButton::new(IconId::new("trash-2")).label(tl!("Delete Stop")).tooltip(tl!("Delete Stop")).enabled(can_del).show(ui); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 9a71052c7c..f4b57b8c8b 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -6,6 +6,7 @@ use egui::{Key, Modifiers, Pos2, pos2, vec2}; use vectorcraft_engine::Session; use super::*; +use crate::tests::panel_harness::{Place, Shown, floated}; #[test] fn dropped_colours_recolour_or_add_an_opaque_stop() { @@ -364,6 +365,85 @@ fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() { assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays"); } +// ---------- the panel in the app window ---------- + +/// A selected gradient stop: the panel shows its Color row. +fn select_a_stop(app: &mut VectorcraftApp) { + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); +} + +/// The Gradient panel shown at `place` in the whole app window over a selected rectangle that `setup` paints, drawn +/// in `lang`, with the catalog strings `names` as `lang` shows them. The Gradient Fill box is always asked for, so a +/// docked panel is found by it. +fn shown(lang: &str, place: Place, setup: fn(&mut VectorcraftApp), names: &[&str]) -> Shown { + let mut app = super::super::tests_appearance::app_with_rect(); + setup(&mut app); + let asked: Vec<&str> = names.iter().copied().chain(["Gradient Fill"]).collect(); + floated(app, "gradient", lang, place, &asked) +} + +/// Docked, every control of the panel stays inside its column, with a solid fill (the panel shows its notice) and +/// with a stop selected (its Color row), in languages with longer words. +#[test] +fn the_gradient_panel_stays_inside_its_dock_column() { + for lang in ["en", "fr", "de"] { + for setup in [|_: &mut VectorcraftApp| {}, select_a_stop] { + let panel = shown(lang, Place::Docked, setup, &[]); + let past = panel.past(panel.nodes.clone()); + assert!(past.is_empty(), "past the docked panel in {lang}: {past:?}"); + } + } +} + +/// In a panel at the narrowest panel width the Type, Method, Spread and stop rows wrap: their controls stay inside +/// the panel, except the last type button. The five type buttons are one `Segmented` control, which keeps its +/// segments on one line, so at this width Freeform Gradient reaches 2 pt past the panel's right edge. The test +/// holds that button to the 2 pt until the widget can wrap its segments. +#[test] +fn the_gradient_rows_wrap_in_a_narrow_panel() { + /// How far Freeform Gradient reaches past the panel's right edge at the narrowest width. + const TYPE_OVERFLOW: f32 = 2.0; + let names = [ + "Linear Gradient", + "Radial Gradient", + "Conic Gradient", + "Diamond Gradient", + "Edit Gradient", + "Method", + "Spread", + "Repeats", + "Opacity", + "Location", + "Delete Stop", + ]; + for lang in ["en", "fr"] { + let asked: Vec<&str> = names.iter().copied().chain(["Freeform Gradient"]).collect(); + let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &asked); + let past = panel.past_named(&names); + assert!(past.is_empty(), "past the panel in {lang}: {past:?}"); + for freeform in panel.rects("Freeform Gradient") { + let inside = freeform.left() >= panel.body.left() - 0.5 && freeform.right() <= panel.body.right() + TYPE_OVERFLOW + 0.5; + assert!(inside, "Freeform Gradient at {freeform:?} is more than {TYPE_OVERFLOW} pt past {:?} in {lang}", panel.body); + } + } +} + +/// In a wide panel the rows stay on one line each, and the thumbnail stays level with the top of the type buttons. +#[test] +fn the_gradient_rows_stay_on_one_line_in_a_wide_panel() { + let rows: [&[&str]; 3] = + [&["Method:", "Method"], &["Spread:", "Spread", "Repeats"], &["Opacity:", "Opacity", "Location:", "Location", "Delete Stop"]]; + let names: Vec<&'static str> = rows.iter().flat_map(|row| row.iter().copied()).chain(["Gradient Fill", "Linear Gradient"]).collect(); + let panel = shown("en", Place::Floating(400.0), select_a_stop, &names); + for row in rows { + let middles = panel.middles(row); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{row:?} is not on one line: {middles:?}"); + } + let (thumb, linear) = (panel.rects("Gradient Fill")[0], panel.rects("Linear Gradient")[0]); + assert!((thumb.top() - linear.top()).abs() < 1.0, "the thumbnail {thumb:?} is not level with the type buttons {linear:?}"); +} + /// The paints of the selected object's appearance rows, in stack order. fn row_paints(app: &VectorcraftApp) -> Vec { let st = app.session.active().unwrap(); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 2d4fcad4d5..a1f3dabb97 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -485,9 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .popup(PopupKind::Menu) .pressed(library_panel::any_open::(&app.ui)), FooterAction::new(svg("link-2-off"), tl!("Break Link to Graphic Style")).enabled(linked), - FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style")).enabled(!sel.is_empty()).takes_drops_disabled(true).accepts_drops(ours), + FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style (Alt-click: without asking)")) + .enabled(!sel.is_empty()) + .takes_drops_disabled(true) + .accepts_drops(ours), // A style dropped here is duplicated with or without art selected. - FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style")) + FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style (Alt-click to name it)")) .enabled(selection_len(app) > 0) .takes_drops_disabled(true) .accepts_drops(ours), @@ -1430,4 +1433,22 @@ mod tests { app.session.documents().iter().map(|st| st.doc.graphic_styles.iter().map(|g| g.name.clone()).collect()).collect(); assert!(names.iter().all(|n| n.iter().any(|g| g == "Mine")), "no style is renamed: {names:?}"); } + + /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete + /// deletes without asking. + #[test] + fn the_new_and_delete_buttons_name_their_alt_click() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let mut panel = Panel::new(app(), show); + panel.click_with("New Graphic Style (Alt-click to name it)", Modifiers::ALT); + assert!(open_dialog(&panel.app(), graphic_style_options::KIND).is_some(), "Alt-click on New asks for a name"); + let mut app = app(); + app.session.execute("graphicStyle.new", &json!({"name": "Mine"})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click("Mine"); + panel.click_with("Delete Graphic Style (Alt-click: without asking)", Modifiers::ALT); + let app = panel.app(); + assert!(!names(&app).iter().any(|s| s == "Mine") && confirm::open_question(&app).is_none(), "Alt-click on Delete deletes at once"); + } } diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 80508d9e4e..ddd4fd7887 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -1,9 +1,17 @@ //! History panel: the document's states; click one to go back (or forward) to it. +use std::sync::Arc; + +use craft::behavior::{IconId, Selection, SelectionChange, keyed}; use craft::keymap::CommandRef; -use craft::ui::menu::PanelRow; -use craft::ui::patterns::panels::{HistoryEvent, HistoryFooter, HistoryKey, HistoryPanel, HistoryRow}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, ScrollAnchor, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; +use craft::ui::display::Divider; +use craft::ui::layout_components::Stack; +use craft::ui::list::{List, ListRow, RowInk}; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; +use craft::ui::patterns::panels::{HistoryKey, HistoryRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::sections::{FooterAction, FooterBar}; use egui::Ui; use serde_json::{Value, json}; @@ -69,34 +77,168 @@ fn rows(app: &VectorcraftApp) -> Vec { .collect() } -/// Moves the document to state `target`, stopping at the first step that fails. -fn step_to(app: &mut VectorcraftApp, target: usize) { - let Some(current) = app.session.active().map(|st| st.history.undo.len()) else { return }; - let s = steps_to(current, target); - let (cmd, n) = if s < 0 { ("edit.undo", -s) } else { ("edit.redo", s) }; - for _ in 0..n { - if app.run(cmd, json!({})).is_err() { - break; - } - } +#[derive(Clone)] +struct ContextState { + document: u64, + snapshot: Arc, } +/// The shared collection supplies row focus, keyboard context requests, scrolling and menu +/// dismissal. The app retains the chosen document snapshot and dispatches its history commands. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - let Some(undone) = app.session.active().map(|st| st.history.undo.len()) else { + let state_id = ui.scope_id().with("history-context-state"); + let document = app.session.active().map(|st| st.uid); + let mut context = ui.ctx().data(|d| d.get_temp::(state_id)); + if context.as_ref().is_some_and(|state| document != Some(state.document)) { + craft::ui::runtime::overlay::close_popups(ui.ctx()); + context = None; + } + let Some(st) = app.session.active() else { + ui.ctx().data_mut(|d| d.remove::(state_id)); super::empty_state(ui, "history", tl!("No document"), tl!("Open a document to see its history.")); return; }; + let document = st.uid; + let current = st.history.undo.len(); let rows = rows(app); - // A click on a row moves to its state at once, so the current state is the selected one. - let out = HistoryPanel::new(&rows, Some(HistoryKey::State(undone as u64))) - .footer(HistoryFooter::default().new_document(true)) - .can_delete(|_| false) - .show(ui); - for event in out.events { - match event { - HistoryEvent::Select(HistoryKey::State(n)) => step_to(app, n as usize), - HistoryEvent::NewDocument => crate::menus::invoke(app, "edit.newDocumentFromState", json!({})), - _ => {} + let mut selected = Selection::single(HistoryKey::State(current as u64)); + let mut new_document = false; + let mut target = None; + let mut action = None; + Stack::new() + .fill() + .footer(|ui, _| { + let out = FooterBar::actions([FooterAction::new(IconId::new("new_file"), tl!("Create New Document from Current State"))]).show_footer(ui); + if !ui.is_sizing_pass() { + new_document |= out.picked.is_some(); + } + }) + .show(ui, |ui, _| { + let list = List::::new(tl!("History")) + .id(ui.scope_id().with(("history-rows", document))) + .select(SelectMode::Single) + .arrows_select(false) + .selection(Bind::bound(&mut selected)) + .row_menu() + .sizing(Sizing::Fill) + .scroll_anchor(ScrollAnchor::End); + let out = list.show_items(ui, &keyed(&rows, |row: &HistoryRow| row.key), &mut |_, icx| { + let row = &rows[icx.at]; + let mut item = ListRow::new(row.label.clone()).cells(icx.cells()).state(icx.row.clone()); + if let Some(icon) = row.icon.clone() { + item = item.icon(icon.into()); + } + if row.redo { + item = item.ink(RowInk::Dimmed); + } + item + }); + let requested = out.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => Some(request.key), + _ => None, + }); + if let Some(HistoryKey::State(row)) = requested { + context = app + .session + .active() + .and_then(|st| st.history.state(&st.doc, row as usize)) + .cloned() + .map(|snapshot| ContextState { document, snapshot }); + } else { + for event in &out.events { + if let CollectionEvent::Activate(HistoryKey::State(row)) = event { + target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned(); + } + if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event + && let Some(HistoryKey::State(row)) = keys.last() + && *row as usize != current + { + target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned(); + } + } + } + if let Some(state) = context.as_ref() { + let snapshot = state.snapshot.clone(); + let can_step = app.session.active().is_some_and(|st| !Arc::ptr_eq(&snapshot, &st.doc)); + let shown = Menu::context(tl!("History"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("New Document from State")).enabled(crate::menus::enabled(app, "edit.newDocumentFromState")).show(ui).ran { + action = Some(("edit.newDocumentFromState", snapshot.clone())); + } + if MenuItem::new(tl!("Step to This State")).enabled(can_step).show(ui).ran { + target = Some(snapshot.clone()); + } + Divider::horizontal().show(ui); + if MenuItem::new(tl!("Clear History")).enabled(crate::menus::enabled(app, "edit.clearHistory")).show(ui).ran { + action = Some(("edit.clearHistory", snapshot.clone())); + } + }); + if shown.output.closed.is_some() || action.is_some() || target.is_some() { + context = None; + } + } + }); + ui.ctx().data_mut(|d| { + if let Some(state) = context { + d.insert_temp(state_id, state); + } else { + d.remove::(state_id); + } + }); + if let Some((command, snapshot)) = action { + if command == "edit.newDocumentFromState" { + if let Some(row) = resolve_state(app, snapshot, false) { + crate::menus::invoke(app, command, json!({ "index": row })); + } + } else { + crate::menus::invoke(app, command, json!({})); + } + } + if let Some(target) = target { + step_to_state(app, target); + } + if new_document { + crate::menus::invoke(app, "edit.newDocumentFromState", json!({})); + } +} + +/// Keep the clicked snapshot while pending edits settle: they can add or trim history rows. +fn resolve_state(app: &mut VectorcraftApp, target: Arc, keep_typing: bool) -> Option { + let requests = app.session.finish_tool_edit(); + let failed = requests.is_err(); + crate::canvas::apply_requests(app, requests); + if failed { + return None; + } + if keep_typing && let Err(e) = app.keep_typing() { + app.status(e); + return None; + } + let st = app.session.active()?; + let current = st.history.undo.len(); + let row = if Arc::ptr_eq(&st.doc, &target) { + Some(current) + } else { + st.history + .undo + .iter() + .position(|h| Arc::ptr_eq(&h.doc, &target)) + .or_else(|| st.history.redo.iter().rev().position(|h| Arc::ptr_eq(&h.doc, &target)).map(|i| current + i + 1)) + }; + if row.is_none() { + app.status(tl!("That history state is no longer available.")); + } + row +} + +fn step_to_state(app: &mut VectorcraftApp, target: Arc) { + let Some(row) = resolve_state(app, target, true) else { return }; + let Some(st) = app.session.active() else { return }; + let steps = steps_to(st.history.undo.len(), row); + let (cmd, n) = if steps < 0 { ("edit.undo", -steps) } else { ("edit.redo", steps) }; + for _ in 0..n { + if let Err(e) = app.run(cmd, json!({})) { + app.status(e); + break; } } } @@ -142,6 +284,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option mod tests { use super::*; use crate::i18n::LangExt; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; /// A step named after a style lists the template's translation with the style's name in it as /// the document holds it, also when the name looks like a template, like a step with a row of @@ -259,24 +403,9 @@ mod tests { let mut app = app_with_two_rectangles(); app.session.execute("edit.undo", &json!({})).unwrap(); let source = app.session.active().unwrap().doc.clone(); - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - egui_extras::install_image_loaders(&ctx); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(240.0, 400.0))); - let frame = |app: &mut VectorcraftApp, events: Vec| { - let out = crate::testing::part_frame(app, &ctx, egui::RawInput { events, screen_rect: screen, ..Default::default() }, show); - out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() - }; - frame(&mut app, vec![]); - let nodes = frame(&mut app, vec![]); - // PLAN: the button is named by the framework's words ("Create New Document from Current State"); the name is - // matched by the words it holds. - let button = nodes.iter().map(|(_, n)| n).find(|n| n.label().is_some_and(|l| l.contains("New Document"))).expect("the button"); - let at = button.bounds().expect("its bounds"); - let at = egui::pos2((at.x0 + at.x1) as f32 / 2.0, (at.y0 + at.y1) as f32 / 2.0); - let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); - frame(&mut app, vec![press(false)]); + let mut panel = Panel::new(app, show); + panel.click("Create New Document from Current State"); + let app = panel.app(); assert_eq!(app.session.documents().len(), 2); assert_eq!(app.session.active_index(), Some(1), "the new document is the active one"); let st = app.session.active().unwrap(); @@ -284,4 +413,226 @@ mod tests { assert!(st.is_dirty(), "the new document is unsaved"); assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source), "the source stays at that state"); } + + fn history_harness(app: VectorcraftApp) -> Panel { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(260.0, 400.0)); + panel.frame(); + panel + } + + fn row_menu_harness(app: VectorcraftApp, row: usize) -> Panel { + let mut panel = history_harness(app); + panel.secondary_click_nth(Role::LIST_ITEM, row); + panel + } + + fn focus_previous_state(panel: &mut Panel) { + for _ in 0..4 { + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + if panel.focused_nth(Role::LIST_ITEM, 2) { + break; + } + } + assert!(panel.focused_nth(Role::LIST_ITEM, 2)); + panel.key(egui::Key::ArrowUp, egui::Modifiers::NONE); + assert!(panel.focused_nth(Role::LIST_ITEM, 1)); + assert_eq!(depth(&panel.app()), (2, 0), "moving focus must not step history"); + } + + #[test] + fn keyboard_activation_steps_to_the_focused_state() { + let mut h = history_harness(app_with_two_rectangles()); + focus_previous_state(&mut h); + h.key(egui::Key::Enter, egui::Modifiers::NONE); + h.frame(); + h.frame(); + assert_eq!(depth(&h.app()), (1, 1)); + assert_eq!(h.app().session.active().unwrap().doc.layers[0].children().unwrap().len(), 1); + } + #[test] + fn switching_documents_dismisses_the_row_menu_without_clearing_either_history() { + let mut app = app_with_two_rectangles(); + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); + for x in [10, 60] { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + } + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + let mut h = row_menu_harness(app, 1); + assert!(h.shows("Clear History")); + h.app().session.execute("document.activate", &json!({"index": 1})).unwrap(); + h.frame(); + h.frame(); + assert!(!h.shows("Clear History"), "the other document must not inherit the popup"); + h.app().session.execute("document.activate", &json!({"index": 0})).unwrap(); + h.frame(); + h.frame(); + assert!(!h.shows("Clear History"), "switching back must not revive the popup"); + for st in h.app().session.documents() { + assert_eq!((st.history.undo.len(), st.history.redo.len()), (1, 1)); + } + } + + #[test] + fn keyboard_opens_dismisses_and_activates_the_focused_rows_menu() { + let app = app_with_two_rectangles(); + let source = app.session.active().unwrap().doc.clone(); + let wanted = app.session.active().unwrap().history.undo[1].doc.clone(); + let mut h = history_harness(app); + focus_previous_state(&mut h); + h.key(egui::Key::F10, egui::Modifiers::SHIFT); + h.frame(); + h.frame(); + assert!(h.focused("New Document from State")); + assert_eq!(depth(&h.app()), (2, 0), "opening does not step"); + h.key(egui::Key::Escape, egui::Modifiers::NONE); + h.frame(); + h.frame(); + assert!(!h.shows("New Document from State")); + assert!(h.focused_nth(Role::LIST_ITEM, 1)); + h.key(egui::Key::F10, egui::Modifiers::SHIFT); + h.frame(); + h.frame(); + h.key(egui::Key::Enter, egui::Modifiers::NONE); + h.frame(); + h.frame(); + assert_eq!(h.app().session.documents().len(), 2); + assert_eq!(h.app().session.active().unwrap().doc.layers, wanted.layers); + assert!(Arc::ptr_eq(&h.app().session.documents()[0].doc, &source)); + assert_eq!(h.app().session.documents()[0].history.undo.len(), 2); + } + + #[test] + fn right_clicking_an_earlier_state_opens_its_menu_without_stepping() { + let h = row_menu_harness(app_with_two_rectangles(), 1); + assert!(h.shows("New Document from State")); + assert!(h.shows("Step to This State")); + assert!(h.shows("Clear History")); + assert_eq!(depth(&h.app()), (2, 0)); + } + + #[test] + fn the_row_menu_makes_a_new_document_from_that_snapshot() { + let mut app = app_with_two_rectangles(); + app.session.execute("edit.undo", &json!({})).unwrap(); + let snapshot = app.session.active().unwrap().doc.clone(); + app.session.execute("edit.redo", &json!({})).unwrap(); + let source = app.session.active().unwrap().doc.clone(); + let mut h = row_menu_harness(app, 1); + h.click_menu_item("New Document from State"); + h.frame(); + h.frame(); + let app = h.app(); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.active_index(), Some(1)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers, snapshot.layers, "the historic artwork"); + assert!(st.is_dirty()); + assert_eq!(depth(&app), (0, 0)); + assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source)); + assert_eq!(app.session.documents()[0].history.undo.len(), 2); + } + + #[test] + fn the_row_menu_steps_backward_and_forward_to_the_target() { + for (current, target) in [(2, 0), (0, 2), (1, 1)] { + let mut app = app_with_two_rectangles(); + for _ in current..2 { + app.session.execute("edit.undo", &json!({})).unwrap(); + } + let mut h = row_menu_harness(app, target); + assert_eq!(h.menu_item_enabled("Step to This State"), current != target); + h.click_menu_item("Step to This State"); + h.frame(); + h.frame(); + assert_eq!(depth(&h.app()), (target, 2 - target)); + assert_eq!(h.app().session.active().unwrap().doc.layers[0].children().unwrap().len(), target); + } + } + + #[test] + fn the_row_menu_clears_undo_and_redo_without_changing_art() { + let mut app = app_with_two_rectangles(); + app.session.execute("edit.undo", &json!({})).unwrap(); + let source = app.session.active().unwrap().doc.clone(); + let mut h = row_menu_harness(app, 0); + h.click_menu_item("Clear History"); + h.frame(); + h.frame(); + assert_eq!(depth(&h.app()), (0, 0)); + assert!(std::sync::Arc::ptr_eq(&h.app().session.active().unwrap().doc, &source)); + let mut empty = app_with_two_rectangles(); + empty.session.execute("edit.clearHistory", &json!({})).unwrap(); + let h = row_menu_harness(empty, 0); + assert!(!h.menu_item_enabled("Clear History")); + } + + #[test] + fn stepping_settles_typing_and_follows_the_snapshot_when_rows_shift() { + for (limit, row) in [(10, 0), (2, 1)] { + let mut app = app_with_two_rectangles(); + app.session.active_mut().unwrap().history.limit = limit; + let st = app.session.active().unwrap(); + let wanted = st.history.state(&st.doc, row).unwrap().clone(); + app.session.begin_interaction("Typing").unwrap(); + app.session.preview("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let mut h = row_menu_harness(app, row); + h.click_menu_item("Step to This State"); + h.frame(); + h.frame(); + let app = h.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers, wanted.layers, "limit {limit}, row {row}"); + assert!(st.interaction.is_none()); + assert_eq!(st.history.undo.len(), 0); + } + } + + #[test] + fn copying_a_state_resolves_pending_tool_edits_without_copying_a_neighbor() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + + for (row, finishes_while_open) in [(0, false), (1, false), (0, true), (1, true)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 200})).unwrap(); + // A Shape Builder merge over this many segments computes on another thread. + for k in 0..40 { + app.run("shape.rectangle", json!({"x": k * 10, "y": 0, "width": 20, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap(); + let st = app.session.active_mut().unwrap(); + st.history.limit = 2; + st.history.trim(); + let wanted = st.history.state(&st.doc, row).unwrap().clone(); + let view = app.view_info(); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Move, 15.0, 10.0), view); + app.session.tool_poll(view, true).unwrap(); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, 15.0, 10.0), view); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Up, 15.0, 10.0), view); + assert!(app.session.tool_waiting()); + let mut h = row_menu_harness(app, row); + if finishes_while_open { + let requests = h.app().session.finish_tool_edit(); + crate::canvas::apply_requests(&mut h.app(), requests); + h.frame(); + h.frame(); + } + h.click_menu_item("New Document from State"); + h.frame(); + h.frame(); + let app = h.app(); + assert!(!app.session.tool_waiting()); + if row == 0 { + assert_eq!(app.session.documents().len(), 1, "the pruned snapshot must not copy its neighbor"); + assert_eq!(app.ui.status, "That history state is no longer available."); + } else { + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(app.session.active().unwrap().doc.layers, wanted.layers, "the retained snapshot moved from row 1 to row 0"); + } + } + } } diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index e2096de5d5..31bb7ebd9f 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -230,11 +230,12 @@ fn shifted(mut view: CanvasView, region: DRect) -> CanvasView { view } -/// The `view.setZoom` params for `edited`, a view of the region's frame: the zoom as the status bar -/// shows it (with `print` screen points to an inch at 100%, [`crate::state::print_ppi`]), and the -/// centre back in document units. -fn view_params(edited: &CanvasView, region: DRect, print: Option) -> Value { - json!({"zoom": crate::state::zoom_display_percent(edited.zoom, print), "center": [edited.center.x + region.x0, edited.center.y + region.y0]}) +/// The `view.setZoom` params for `edited`, a canvas view of the region's frame at `ui_scaling`: the +/// zoom as the status bar shows it (with `print` screen points to an inch at 100%, +/// [`crate::state::print_ppi`]), and the centre back in document units. +fn view_params(edited: &CanvasView, region: DRect, print: Option, ui_scaling: f32) -> Value { + let zoom = crate::state::View::zoom_of_canvas(edited, ui_scaling); + json!({"zoom": crate::state::zoom_display_percent(zoom, print), "center": [edited.center.x + region.x0, edited.center.y + region.y0]}) } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -280,7 +281,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && *edited != given { let print = app.print_ppi(); - app.run("view.setZoom", view_params(edited, region, print)).ok(); + let scaling = app.ui_scaling(); + app.run("view.setZoom", view_params(edited, region, print, scaling)).ok(); } } @@ -299,7 +301,29 @@ mod tests { assert_eq!((given.center.x, given.center.y), (210.0, 170.0), "the centre minus the region's corner"); let mut edited = given; edited.center = (100.0, 100.0).into(); - assert_eq!(view_params(&edited, region, None)["center"], json!([90.0, 80.0]), "the edit plus the region's corner"); + assert_eq!(view_params(&edited, region, None, 1.0)["center"], json!([90.0, 80.0]), "the edit plus the region's corner"); + } + + /// At UI Scaling 150% the panel's zoom field shows the zoom `view.setZoom` set, and a zoom typed into it is the + /// zoom the view gets, as at 100%: 200% gives the view the zoom `view.setZoom` gives for 200%. + #[test] + fn the_zoom_field_sets_the_typed_zoom_at_any_ui_scaling() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.prefs.ui_scaling = 1.5; + app.view_mut().unwrap().rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(460.0, 260.0)); + app.run("view.setZoom", json!({"zoom": 200})).unwrap(); + let wanted = app.view().unwrap().zoom; + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + assert!((panel.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling"); + let shown = |panel: &crate::tests::panel_harness::Panel| panel.value("Zoom").unwrap_or_default(); + assert!(shown(&panel).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&panel)); + panel.type_into("Zoom", "200"); + let zoom = panel.app().view().unwrap().zoom; + assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}"); + assert!(shown(&panel).starts_with("200"), "the field shows the typed zoom: {}", shown(&panel)); } /// The panel menu's rows are titled, checked and enabled as the option says, and each row's diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 4262179b3e..b0025b5f82 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -197,6 +197,8 @@ enum Change { Position(usize), /// A checkbox row turned on or off. Toggle(Flag, bool), + /// A row menu's Reset OpenType Features: the panel menu's default. + Reset, } impl Change { @@ -205,6 +207,7 @@ impl Change { Change::Figure(i) => set_figure(f, i), Change::Position(i) => set_position(f, i), Change::Toggle(flag, on) => flag.put(f, on), + Change::Reset => *f = OtFeatures::default(), } } } @@ -286,11 +289,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } Divider::horizontal().show(ui); // A row whose characters differ shows a dash, and a click turns the feature on for all of them. + // A secondary click keeps the text selection and opens that row's menu. for (label, flag) in rows() { - let out = Checkbox::new(Bind::given(mixed(shown_flag(app, flag)))).label(label).show(ui); + let shown = shown_flag(app, flag); + let out = Checkbox::new(Bind::given(mixed(shown))).label(label).show(ui); if let Some(on) = out.events.committed() { change = Some(Change::Toggle(flag, *on)); } + // The row menu's choice is applied with the rest at the end of the pass, so the rows drawn + // after it still read the state the pass started with. + if let Some(c) = Menu::context(label, &out.response).show(ui, |ui, _| feature_row_menu(app, ui, flag, shown)).inner.flatten() { + change = Some(c); + } } let sets = set_entries(app, &st); let opener = Button::new(tl!("Stylistic Sets")).enabled(!sets.is_empty()).show(ui); @@ -304,11 +314,30 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if tracking_drops_ligatures(app) { Text::new(tl!("Ligatures are off while the text is tracked.")).shade(Shade::Muted).show(ui); } - if let Some(c) = change { - edit(app, c); + match change { + // Reset writes the default as the whole feature list, as the panel menu's entry does. + Some(Change::Reset) => set(app, OtFeatures::default()), + Some(c) => edit(app, c), + None => {} } } +/// The menu a secondary click on one feature row opens. Turn Off when the row is on +/// (`shown` is `Some(true)`); Turn On when it is off or mixed, through the same toggle a click +/// uses, so a mixed row turns the feature on for every character the panel acts on. Reset +/// OpenType Features applies the panel menu's default and is enabled on the same condition. +fn feature_row_menu(app: &VectorcraftApp, ui: &mut Ui, flag: Flag, shown: Option) -> Option { + let on = shown == Some(true); + let mut chosen = None; + if MenuItem::new(if on { tl!("Turn Off") } else { tl!("Turn On") }).show(ui).ran { + chosen = Some(Change::Toggle(flag, !on)); + } + if MenuItem::new(tl!("Reset OpenType Features")).enabled(text_style(app).is_some()).show(ui).ran { + chosen = Some(Change::Reset); + } + chosen +} + /// Whether tracking turns off the standard ligatures of any character the panel acts on: one with /// Standard Ligatures on, tracked past [`vectorcraft_text::ligatures_suppressed_by`]'s limit and /// without an explicit `liga` or `clig` tag ([`vectorcraft_text::explicit_ligatures`]). @@ -485,6 +514,7 @@ mod tests { use vectorcraft_doc::NodeId; use super::*; + use crate::tests::panel_harness::Panel; fn selected_text() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -1146,4 +1176,94 @@ mod tests { } } } + + fn row_flag(label: &str) -> Flag { + rows().into_iter().find(|(l, _)| *l == label).unwrap().1 + } + + #[test] + fn right_clicking_an_opentype_row_offers_turn_on_or_turn_off() { + let mut panel = Panel::new(selected_text(), show); + let ids = panel.app().session.active().unwrap().selection.objects.clone(); + let before = features(&panel.app()).to_tags(); + let undo = undo_steps(&panel.app()); + panel.secondary_click("Standard Ligatures"); + assert!(panel.menu_item_enabled("Turn Off")); + assert!(!panel.shows("Turn On")); + assert!(panel.menu_item_enabled("Reset OpenType Features")); + assert_eq!(panel.app().session.active().unwrap().selection.objects, ids); + assert_eq!(features(&panel.app()).to_tags(), before); + assert_eq!(undo_steps(&panel.app()), undo); + panel.click_menu_item("Turn Off"); + panel.secondary_click("Standard Ligatures"); + assert!(panel.menu_item_enabled("Turn On")); + assert!(!panel.shows("Turn Off")); + assert_eq!(panel.app().session.active().unwrap().selection.objects, ids); + } + + #[test] + fn clicking_turn_on_sets_that_feature_in_one_undo_step() { + let off = OtFeatures { ligatures: false, swash: true, ..OtFeatures::default() }; + let mut app = selected_text(); + set(&mut app, off); + let mut by_check = Panel::new(app, show); + by_check.click("Standard Ligatures"); + let mut app = selected_text(); + set(&mut app, off); + let before = features(&app).to_tags(); + let undo = undo_steps(&app); + let mut panel = Panel::new(app, show); + panel.secondary_click("Standard Ligatures"); + panel.click_menu_item("Turn On"); + assert_eq!(undo_steps(&panel.app()), undo + 1); + assert_eq!(features(&panel.app()).to_tags(), features(&by_check.app()).to_tags()); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(features(&panel.app()).to_tags(), before); + } + + #[test] + fn turn_on_preserves_the_mixed_character_range_and_undo_restores_its_runs() { + let mut app = selected_text(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.run("text.create", json!({"x": 0, "y": 20, "text": "abcd"})).unwrap()["id"].clone(); + app.run("text.setRangeStyle", json!({"id": id, "start": 1, "end": 2, "features": ["frac"]})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 1, "end": 3})); + let range = Some((NodeId(id.as_u64().unwrap()), 1, 3)); + assert_eq!(text_editing(&app), range); + assert_eq!(shown_flag(&app, row_flag("Fractions")), None); + let before = run_features(&mut app, &id, 4); + let undo = undo_steps(&app); + let mut panel = Panel::new(app, show); + panel.secondary_click("Fractions"); + assert_eq!(text_editing(&panel.app()), range); + assert_eq!(run_features(&mut panel.app(), &id, 4), before); + panel.click_menu_item("Turn On"); + assert_eq!(run_features(&mut panel.app(), &id, 4), [("a".into(), Value::Null), ("bc".into(), json!(["frac"])), ("d".into(), Value::Null)]); + assert_eq!(undo_steps(&panel.app()), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(run_features(&mut panel.app(), &id, 4), before); + } + + #[test] + fn clicking_reset_opentype_features_clears_the_rows() { + let custom = OtFeatures { ligatures: false, fractions: true, swash: true, ..OtFeatures::default() }; + let mut by_flyout = selected_text(); + set(&mut by_flyout, custom); + run(&mut by_flyout, RESET, &json!({})).unwrap().unwrap(); + let mut app = selected_text(); + set(&mut app, custom); + let before = features(&app).to_tags(); + let undo = undo_steps(&app); + let mut panel = Panel::new(app, show); + panel.secondary_click("Fractions"); + panel.click_menu_item("Reset OpenType Features"); + assert_eq!(undo_steps(&panel.app()), undo + 1); + assert_eq!(features(&panel.app()).to_tags(), features(&by_flyout).to_tags()); + assert_eq!(shown_flag(&panel.app(), row_flag("Standard Ligatures")), Some(true)); + assert_eq!(shown_flag(&panel.app(), row_flag("Fractions")), Some(false)); + assert_eq!(shown_flag(&panel.app(), row_flag("Swash")), Some(false)); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(features(&panel.app()).to_tags(), before); + } } diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 2dd7f1f39f..26102b5311 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -434,19 +434,19 @@ pub(crate) fn alignment_toggles(app: &mut VectorcraftApp, ui: &mut Ui, count: us /// The Control bar's paragraph controls while type is selected or edited (#5372), after its /// Character controls: the Paragraph link, which opens the Paragraph panel in a popover under it, /// and the Align left, Align center and Align right buttons. Always `true`: the bar trims these -/// itself as it narrows. +/// itself as it narrows, the link and the buttons as two members of the type groups' rank, so the +/// buttons leave before the link. pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { if text_style(app).is_none() { return true; } - // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row. - Row::new().show(ui, |ui, _| { + Row::new().fit_rank(crate::chrome::rank::TYPE).show(ui, |ui, _| { let link = crate::panels::option_link(tl!("Paragraph:")).tooltip(tl!("Paragraph options")).show(ui); Popover::new(tl!("Paragraph"), Bind::kept()) .overlay(|overlay| overlay.opened_by(&link.response, Trigger::Click)) .show(ui, |ui, _| show(app, ui)); - alignment_toggles(app, ui, CONTROL_BAR_ALIGNMENTS); }); + Row::new().fit_rank(crate::chrome::rank::TYPE).show(ui, |ui, _| alignment_toggles(app, ui, CONTROL_BAR_ALIGNMENTS)); true } diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 48b324ccf4..0d56471f6d 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -751,7 +751,6 @@ fn bar_names(app: &mut VectorcraftApp) -> Vec { /// #5372: with type selected the Control bar shows a Paragraph section: the Paragraph: link and the /// Align left, Align center and Align right buttons (the justifying four are in the panel the link /// opens); with no type selected it shows none of them. -// PLAN: the trimming order as the bar narrows (toggles out before the link, ch.K30) is chrome-w16's `Row::fit_rank` and is tested with its fixture. #[test] fn the_control_bar_shows_its_paragraph_section_for_selected_type_only() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 8280c4c3d1..d1ee58262d 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -520,6 +520,28 @@ mod tests { assert!(p.app().run("pathfinder.repeat", json!({})).is_err()); } + /// The state the window's menus give the Repeat row, which the panel menu's row reads. + fn repeat_row(p: &Panel) -> Option { + crate::menus::model::refresh(&mut p.app(), p.ctx()); + p.app().menus.states.get(&CommandRef::new("pathfinder.repeat")).cloned() + } + + /// Before an operation has run, the Repeat row reads Repeat Pathfinder and is dimmed; after Unite + /// or Minus Front from the panel it names that operation. + #[test] + fn the_repeat_row_names_the_last_operation() { + let mut p = Panel::new(two_squares(), show); + let command = CommandRef::new("pathfinder.repeat"); + let off = crate::menus::model::off_reason(&p.app(), &command, "Repeat Pathfinder"); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(false).hint(off)), "the plain label, dimmed"); + p.click("Unite"); + select_two_squares(&mut p.app(), 110.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Unite"))); + p.click("Minus Front"); + select_two_squares(&mut p.app(), 210.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Minus Front"))); + } + /// One selected path cannot supply the operands for Unite; the command reports the failure. #[test] fn repeat_with_one_path_keeps_art_and_history() { diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index 15a8dace13..e249c1ea95 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -1,12 +1,9 @@ //! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width. -use serde_json::json; - use super::tests_appearance::app_with_rect; use super::*; -use crate::i18n::Lang; use crate::panel_docking::PANEL_MIN_WIDTH; -use crate::tests::panel_harness::{Panel, ROOM}; +use crate::tests::panel_harness::{Panel, Place, ROOM, floated}; #[test] fn the_arrowhead_row_stays_inside_the_stroke_panel() { @@ -30,62 +27,19 @@ fn the_color_themes_hex_row_stays_inside_a_narrow_panel() { } } -/// Panel `panel` floated `width` wide in the whole app window, drawn in `lang`: the rect of its body, and the rects of -/// the controls named each of `names` (catalog strings, shown in `lang`). -fn floated(panel: &str, lang: &str, width: f32, names: &[&str]) -> (egui::Rect, Vec<(String, Vec)>) { - use egui::accesskit::Role; - const AT: f32 = 520.0; - let mut app = app_with_rect(); - app.session.prefs.interface_language = lang.into(); - app.run("window.panel", json!({ "panel": panel })).unwrap(); - app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(); - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); - let mut nodes = Vec::new(); - for at in 1..=8 { - let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; - let out = crate::testing::app_frame(&mut app, &ctx, input); - nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); - } - // The frames set the language from the preference; the names are looked up in it before English is put back. - let shown: Vec<&str> = names.iter().map(|name| crate::i18n::t(name)).collect(); - crate::i18n::set_current(Lang::EN); - let rect = |node: &egui::accesskit::Node| { - node.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) - }; - // The floating panel's body: the tab panel at the left edge the float asked for. - let body = nodes - .iter() - .filter(|(_, n)| n.role() == Role::TabPanel) - .find_map(|(_, n)| rect(n).filter(|r| (r.left() - AT).abs() < 1.0)) - .unwrap_or_else(|| panic!("{panel} does not float at x {AT}")); - assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for"); - let controls = shown - .into_iter() - .map(|name| { - let found: Vec = nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l == name)).filter_map(|(_, n)| rect(n)).collect(); - assert!(!found.is_empty(), "{panel} shows no {name:?}"); - (name.to_owned(), found) - }) - .collect(); - (body, controls) -} - /// The controls named `names` (catalog strings, shown in `lang`) that reach past either side of panel `panel`, /// floated at the narrowest panel width in the whole app window, each with its rect. fn past_a_narrow_panel(panel: &str, lang: &str, names: &[&str]) -> Vec { - let (body, controls) = floated(panel, lang, PANEL_MIN_WIDTH, names); - let outside = |r: &egui::Rect| r.left() < body.left() - 0.5 || r.right() > body.right() + 0.5; - controls.iter().flat_map(|(name, found)| found.iter().filter(|r| outside(r)).map(move |r| format!("{name} at {r:?}"))).collect() + floated(app_with_rect(), panel, lang, Place::Floating(PANEL_MIN_WIDTH), names).past_named(names) } #[test] fn the_profile_row_stays_on_one_line_in_a_wide_stroke_panel() { - let (_, controls) = floated("stroke", "en", 360.0, &["Profile", "Flip Along", "Flip Across"]); + let names = ["Profile", "Flip Along", "Flip Across"]; + let panel = floated(app_with_rect(), "stroke", "en", Place::Floating(360.0), &names); // The field, its caption, the list and the two buttons share one line, so their middles are level. - let middles: Vec = controls.iter().flat_map(|(_, found)| found.iter().map(|r| r.center().y)).collect(); - assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{controls:?}"); + let middles = panel.middles(&names); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{middles:?}"); } #[test] diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 3ff0fd0191..b418d3d2b4 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -20,7 +20,7 @@ use craft::ui::contract::{ Bind, CollectionEvent, ColumnEvent, ColumnSort, ColumnSpec, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Trigger, Validity, }; -use craft::ui::display::{Icon, Shade, Text}; +use craft::ui::display::{Divider, Icon, Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow}; @@ -278,7 +278,7 @@ struct Picked { has_selection: bool, /// Unbind needs a bound object under the selection, not just any selection. selection_bound: bool, - /// Make Text Dynamic needs exactly one type object: a text variable only drives type. + /// Make Text Dynamic needs one type object without an existing text variable. single_type: bool, /// Make Image Dynamic needs exactly one image object. single_image: bool, @@ -289,7 +289,15 @@ struct Picked { fn picked(st: &vectorcraft_engine::DocState) -> Picked { let selected: Vec = st.selection.objects.iter().map(|i| i.0).collect(); let selection_bound = selected.iter().any(|id| st.doc.variables.bindings.contains_key(&NodeId(*id))); - let single_type = matches!(selected.as_slice(), [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))); + let single_type = match selected.as_slice() { + [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) => st + .doc + .variables + .bindings + .get(&NodeId(*one)) + .is_none_or(|bound| !st.doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text && bound.contains(&v.name))), + _ => false, + }; let single_image = matches!(selected.as_slice(), [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))); let selection_graph = !selected.is_empty() && selected.iter().all(|id| st.doc.node(NodeId(*id)).is_some_and(|n| n.extras().graph.is_some())); Picked { has_selection: !selected.is_empty(), selected, selection_bound, single_type, single_image, selection_graph } @@ -408,6 +416,8 @@ enum Act { Rename(String, String), /// A click on a variable's row. Click(String), + /// A context request highlights its variable without changing the canvas selection. + Highlight(String), /// A double click on a variable's row: Variable Options for it. Options(String), } @@ -422,10 +432,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let rows = cached_rows(&mut app.canvas, st, xml_id); let states = row_states(st); let sort = st.variables_sort; + let doc_uid = st.uid; let (mut acts, mut pressed) = (Vec::new(), None); Stack::new().fill().footer(|ui, _| pressed = footer(ui, &states)).show(ui, |ui, _| { data_set_bar(ui, &rows.sets, &mut acts); - variable_table(ui, &rows.vars, sort, &states, &mut acts); + variable_table(ui, &rows.vars, sort, &states, doc_uid, &mut acts); Text::new(tl!("Data Sets")).role(TypeRole::Heading).show(ui); data_set_list(ui, &rows.sets, &mut acts); }); @@ -442,6 +453,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let bound = rows.vars.iter().find(|v| v.name == name).map(|v| v.bound.clone()).unwrap_or_default(); click_row(app, &name, &bound); } + Act::Highlight(name) => { + app.run("variable.highlight", json!({"variable": name})).ok(); + } Act::Options(name) => { crate::dialogs::variables::open(app, "variable.rename", Some(&name)); } @@ -492,7 +506,7 @@ fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec) { /// The variables under their three sortable columns: a row's kind, its name and what it drives. /// A click highlights the row and selects what it drives; a double click opens Variable Options. -fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &RowStates, acts: &mut Vec) { +fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &RowStates, doc_uid: u64, acts: &mut Vec) { let columns = vec![ ColumnSpec::new(TYPE, tl!("Type"), ColumnWidth::Controls(1.0)).icon(IconId::new("arrow-up-down")).tip(tl!("Type")).sortable(), ColumnSpec::new(NAME, tl!("Variables"), ColumnWidth::fill(1.0)).sortable(), @@ -501,6 +515,7 @@ fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &Row let sorted = SORTS.iter().find(|(_, by)| *by == sort.by).map(|(key, _)| ColumnSort::new(key.clone(), sort.descending)); let by_name: HashMap<&str, &VarRow> = vars.iter().map(|v| (v.name.as_str(), v)).collect(); let out = Table::::new(tl!("Variables"), columns) + .id(ui.scope_id().with(("variables-table", doc_uid))) .select(SelectMode::Single) .sort(sorted) .empty(tl!("None")) @@ -514,20 +529,68 @@ fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &Row .cell(OBJECT, row.object.clone()) .cell_muted(OBJECT) }); + let opening_menu = out.events.iter().any(|event| matches!(event, CollectionEvent::ContextMenu(_))); + if let Some(request) = &out.menu + && let Some(row) = by_name.get(request.key.as_str()) + { + variable_menu(ui, &out.response, row, states, acts); + } for event in out.events { match event { + CollectionEvent::ContextMenu(request) => acts.push(Act::Highlight(request.key)), CollectionEvent::Column(ColumnEvent::Sort { key, descending, .. }) => { if let Some((_, by)) = SORTS.iter().find(|(column, _)| *column == key) { acts.push(Act::Run("variable.sort", json!({"by": by.id(), "descending": descending}))); } } - CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => acts.extend(keys.into_iter().next().map(Act::Click)), + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } if !opening_menu => { + acts.extend(keys.into_iter().next().map(Act::Click)); + } CollectionEvent::Activate(name) if !states.locked => acts.push(Act::Options(name)), _ => {} } } } +/// A variable's item menu, retained by the table by key and scoped to its document. +/// Row actions name their target explicitly; dynamic actions use the canvas selection. +fn variable_menu(ui: &mut Ui, opener: &egui::Response, row: &VarRow, states: &RowStates, acts: &mut Vec) { + Menu::context(row.name.clone(), opener).id(opener.id.with("variable-row-menu")).show(ui, |ui, _| { + for id in [ + SELECT_BOUND, + "variable.rename", + UNBIND, + "", + "variable.makeTextDynamic", + "variable.makeVisibilityDynamic", + "variable.makeImageDynamic", + "variable.makeGraphDynamic", + "", + DELETE_VARIABLE, + ] { + if id.is_empty() { + Divider::horizontal().show(ui); + continue; + } + let enabled = match id { + SELECT_BOUND => !row.bound.is_empty(), + "variable.rename" | DELETE_VARIABLE => !states.locked, + UNBIND => !row.bound.is_empty() && !states.locked, + _ => states.enabled(id), + }; + if MenuItem::new(title(id, states.locked)).enabled(enabled).show(ui).ran { + acts.push(match id { + SELECT_BOUND => Act::Run("select.set", json!({"ids": row.bound})), + "variable.rename" => Act::Options(row.name.clone()), + UNBIND => Act::Run("variable.unbind", json!({"ids": row.bound, "variable": row.name})), + DELETE_VARIABLE => Act::Run("variable.delete", json!({"names": [row.name]})), + _ => Act::Run(id, json!({})), + }); + } + } + }); +} + /// The data sets, the active one selected; a row the art has drifted from is in italics, so an edit /// that left the document not matching it is visible. A click on another row applies it. fn data_set_list(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec) { @@ -739,9 +802,14 @@ mod tests { /// Clicks the center of `node`. fn click(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node) { - use egui::{Event, Modifiers, PointerButton}; - let pos = center(node); - let (button, none) = (PointerButton::Primary, Modifiers::default()); + self.click_button(app, node, egui::PointerButton::Primary); + } + + fn click_button(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node, button: egui::PointerButton) { + use egui::{Event, Modifiers}; + let b = node.bounds().expect("bounds"); + let pos = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let none = Modifiers::default(); self.frame(app, vec![Event::PointerMoved(pos), Event::PointerButton { pos, button, pressed: true, modifiers: none }]); self.frame(app, vec![Event::PointerButton { pos, button, pressed: false, modifiers: none }]); self.frame(app, vec![]); @@ -754,6 +822,222 @@ mod tests { egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) } + fn open_row_menu(d: &mut Driver, app: &mut VectorcraftApp, name: &str) -> Vec { + let nodes = d.nodes(app); + let row = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label() == Some(name)).expect("variable row"); + d.click_button(app, &row.1, egui::PointerButton::Secondary); + d.nodes(app).into_iter().filter(|(id, _)| !nodes.iter().any(|(before, _)| before == id)).map(|(_, n)| n).collect() + } + + fn menu_button(nodes: &[egui::accesskit::Node], label: &str) -> egui::accesskit::Node { + nodes.iter().find(|n| n.role() == egui::accesskit::Role::MenuItem && n.label().is_some_and(|s| s.trim() == label)).expect(label).clone() + } + + #[test] + fn right_click_highlights_row_and_select_bound_object_uses_it() { + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Other", "kind": "visibility"})).unwrap(); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + let st = app.session.active().unwrap(); + assert_eq!(highlighted_row(st).as_deref(), Some("Name")); + assert!(st.selection.objects.is_empty(), "right click must preserve canvas selection"); + let bound = st.doc.variables.objects_of("Name"); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + d.click(&mut app, &menu_button(&nodes, "Select Bound Object")); + assert_eq!(app.session.active().unwrap().selection.objects, bound); + } + + #[test] + fn keyboard_opens_focused_row_menu_without_changing_canvas_selection() { + use egui::{Event, Key, Modifiers}; + let mut app = app_with_data(); + let selected = app.session.active().unwrap().selection.objects.clone(); + let mut d = Driver::new(); + let nodes = d.nodes(&mut app); + let table_id = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Table).unwrap().0; + let key = |key, modifiers| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + for _ in 0..20 { + if d.ctx.memory(|m| m.focused()).is_some_and(|id| id.value() == table_id.0) { + break; + } + d.frame(&mut app, vec![key(Key::Tab, Modifiers::NONE)]); + d.frame(&mut app, vec![]); + } + assert!(d.ctx.memory(|m| m.focused()).is_some_and(|id| id.value() == table_id.0), "Tab must focus the variable table"); + // The table owns keyboard focus; Down establishes its focused row before requesting its menu. + d.frame(&mut app, vec![key(Key::ArrowDown, Modifiers::NONE)]); + d.frame(&mut app, vec![key(Key::F10, Modifiers::SHIFT)]); + let nodes = d.nodes(&mut app).into_iter().map(|(_, n)| n).collect::>(); + assert!(!menu_button(&nodes, "Select Bound Object").is_disabled()); + assert_eq!(highlighted_row(app.session.active().unwrap()).as_deref(), Some("Name")); + assert_eq!(app.session.active().unwrap().selection.objects, selected); + d.frame(&mut app, vec![key(Key::Escape, Modifiers::NONE)]); + assert!(!d.nodes(&mut app).iter().any(|(_, n)| n.role() == egui::accesskit::Role::MenuItem)); + } + + #[test] + fn context_menu_deletes_clicked_variable_in_one_undo_step() { + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Other", "kind": "visibility"})).unwrap(); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + // A command can change the highlight while this row's menu remains open. + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + app.run("variable.sort", json!({"by": "name", "descending": true})).unwrap(); + d.frame(&mut app, vec![]); + d.click(&mut app, &menu_button(&nodes, "Delete Variable")); + let st = app.session.active().unwrap(); + assert!(st.doc.variables.variable("Name").is_none()); + assert!(st.doc.variables.variable("Other").is_some()); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.variables.variable("Name").is_some()); + assert!(!app.session.active().unwrap().doc.variables.objects_of("Name").is_empty()); + } + + #[test] + fn context_menu_unbinds_only_clicked_variable() { + let mut app = app_with_data(); + let bound = app.session.active().unwrap().doc.variables.objects_of("Name"); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + app.run("variable.bind", json!({"variable": "Visible", "ids": [bound[0].0]})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + d.click(&mut app, &menu_button(&nodes, "Unbind Variable")); + let st = app.session.active().unwrap(); + assert!(st.doc.variables.objects_of("Name").is_empty()); + assert_eq!(st.doc.variables.objects_of("Visible"), bound); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Name"), bound); + } + + #[test] + fn context_menu_unbinds_both_group_and_nested_object() { + let mut app = app_with_data(); + let text = app.session.active().unwrap().doc.variables.objects_of("Name")[0]; + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [text.0, rect]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + // Bind separately so both the group and its child have the variable. + for id in [group, text.0] { + app.run("variable.bind", json!({"variable": "Visible", "ids": [id]})).unwrap(); + } + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Visible"); + d.click(&mut app, &menu_button(&nodes, "Unbind Variable")); + assert!(app.session.active().unwrap().doc.variables.objects_of("Visible").is_empty()); + assert_eq!(undo_steps(&app), before + 1); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Name"), vec![text]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); + } + + #[test] + fn context_menu_cannot_act_on_same_named_variable_in_another_document() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + for label in ["Delete Variable", "Unbind Variable"] { + let mut app = app_with_data(); + let original = app.session.active().unwrap().doc.variables.clone(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 40, "text": "Alice"})).unwrap()["id"].clone(); + app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap(); + app.run("variable.bind", json!({"variable": "Name", "ids": [text]})).unwrap(); + let other = app.session.active().unwrap().doc.variables.clone(); + assert!(app.session.set_active(0)); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + let action = menu_button(&nodes, label); + let target_node = d + .nodes(&mut app) + .into_iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::MenuItem && n.label() == action.label()) + .expect("the open menu action") + .0; + assert!(app.session.set_active(1)); + assert!(!d.nodes(&mut app).iter().any(|(id, _)| *id == target_node), "{label}: the old menu carried over"); + // A queued accessibility click must not dispatch the old menu action in the new document. + d.frame( + &mut app, + vec![egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::Click, + target_node, + target_tree: TreeId::ROOT, + data: None, + })], + ); + assert_eq!(app.session.active().unwrap().doc.variables, other, "{label}: changed the second document"); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().doc.variables, original, "{label}: changed the first document"); + } + } + + #[test] + fn context_menu_make_text_dynamic_requires_text_without_a_text_binding() { + let mut app = app_with_data(); + let text = app.session.active().unwrap().doc.variables.objects_of("Name")[0]; + app.run("select.set", json!({"ids": [text.0]})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(menu_button(&nodes, "Make Text Dynamic").is_disabled()); + assert!(!menu_button(&nodes, "Make Visibility Dynamic").is_disabled()); + d.frame( + &mut app, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + app.run("variable.unbind", json!({"ids": [text.0], "variable": "Name"})).unwrap(); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + app.run("variable.bind", json!({"variable": "Visible", "ids": [text.0]})).unwrap(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(!menu_button(&nodes, "Make Text Dynamic").is_disabled(), "visibility bindings do not prevent a text variable"); + let before = undo_steps(&app); + d.click(&mut app, &menu_button(&nodes, "Make Text Dynamic")); + let vars = &app.session.active().unwrap().doc.variables; + let bound = vars.bindings.get(&text).unwrap(); + assert!(bound.contains("Visible")); + assert_eq!(vars.variables.iter().filter(|v| v.kind == VariableKind::Text && bound.contains(&v.name)).count(), 1); + assert_eq!(undo_steps(&app), before + 1); + } + + #[test] + fn context_menu_disables_edits_when_locked_and_selection_actions_when_empty() { + let mut app = app_with_data(); + app.run("variable.lock", json!({})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(!menu_button(&nodes, "Select Bound Object").is_disabled()); + for label in [ + "Variable Options…", + "Unbind Variable", + "Make Text Dynamic", + "Make Visibility Dynamic", + "Make Image Dynamic", + "Make Graph Dynamic", + "Delete Variable", + ] { + assert!(menu_button(&nodes, label).is_disabled(), "{label}"); + } + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Unbound", "kind": "visibility"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let nodes = open_row_menu(&mut Driver::new(), &mut app, "Unbound"); + for label in + ["Select Bound Object", "Unbind Variable", "Make Text Dynamic", "Make Visibility Dynamic", "Make Image Dynamic", "Make Graph Dynamic"] + { + assert!(menu_button(&nodes, label).is_disabled(), "{label}"); + } + assert!(!menu_button(&nodes, "Delete Variable").is_disabled()); + } + fn set_names(app: &mut VectorcraftApp) -> Vec { let sets = app.run("dataset.list", json!({})).unwrap(); sets["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap_or_default().to_string()).collect() @@ -898,7 +1182,7 @@ mod tests { check(&app, ¬hing_picked, "with nothing selected or highlighted"); app.run("select.set", json!({"ids": [t]})).unwrap(); app.run("variable.highlight", json!({"variable": "Name"})).unwrap(); - check(&app, &[("variable.makeTextDynamic", true), (UNBIND, true), (DELETE_VARIABLE, true), (SELECT_BOUND, true)], "on the bound text"); + check(&app, &[("variable.makeTextDynamic", false), (UNBIND, true), (DELETE_VARIABLE, true), (SELECT_BOUND, true)], "on the bound text"); app.run("variable.lock", json!({})).unwrap(); let locked = [("variable.makeTextDynamic", false), ("variable.define", false), ("variable.rename", false), (DELETE_VARIABLE, false), (UNBIND, true)]; diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index f537dd91c8..8830ab7526 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -23,7 +23,7 @@ use std::sync::mpsc::{Receiver, TryRecvError, channel}; use serde_json::{Value, json}; use vectorcraft_engine::EngineError; use vectorcraft_engine::cmd::fileio::progress::{self, Progress}; -use vectorcraft_engine::cmd::plugin::FilterRun; +use vectorcraft_engine::cmd::plugin::{self, FilterRun}; use vectorcraft_plugins::{permissions, registry}; use crate::VectorcraftApp; @@ -75,6 +75,11 @@ pub fn start(app: &mut VectorcraftApp, p: Value) -> Result { } // Bad parameters and a missing document fail here, before anything runs. let run = FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?; + // Typing Real-time Drawing off left out of the document is kept next, so the plug-in is given it. + let run = match plugin::keep_unapplied_typing(&mut app.session).map_err(|e| e.to_string())? { + true => FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?, + false => run, + }; let who = format!("“{}”", run.plugin().manifest().name.trim_end_matches('…')); let mut params = p; params["ids"] = json!(run.inputs().iter().map(|i| i.0).collect::>()); @@ -141,7 +146,8 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { return; } }; - if !run.current(&app.session) { + // Typing started meanwhile with Real-time Drawing off isn't in what the plug-in was given. + if !run.current(&app.session) || plugin::unapplied_typing(&app.session) { app.status(format!("{} finished, but the document or the plug-in changed meanwhile: run it again", r.who)); return; } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index a60148af5e..b1d2c72616 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -166,7 +166,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { }; w.state = state; if let Some(request) = out.pick_color { - w.nested.open(ColorPickerDialog::from_request(request)); + w.nested.open(ColorPickerDialog::from_request(request).swatch_view(crate::dialogs::color_picker::swatch_view(app))); } if out.closed.is_none() { app.prefs = Some(w); @@ -324,5 +324,69 @@ pub(crate) fn imported(app: &mut VectorcraftApp, touch_workspace: bool) { } } +/// The default of each UI-only row ([`UI_FIELDS`]), by key. Enable Contextual Task Bar takes the value the current +/// workspace was saved with, so a reset leaves the workspace as it was saved. +fn default_ui_fields(ui: &crate::UiState) -> [(&'static str, bool); 3] { + let first = crate::UiState::default(); + let task_bar = crate::workspaces::saved_task_bar(ui); + [("__smartGuides", first.view.smart_guides), ("__snapToGrid", first.view.snap_to_grid), ("__taskBar", task_bar)] +} + +/// After `prefs.reset`, alone or as a batch step, of every category or of one: the UI-only rows ([`UI_FIELDS`]) and +/// the Edit Original app of the categories it reset take their defaults too, and an open Preferences window shows +/// the reset values. Returns whether any reset was pending. +pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) -> bool { + let mut w = app.prefs.take(); + let any = apply_prefs_resets_to(app, w.as_deref_mut()); + if app.prefs.is_none() { + app.prefs = w; + } + any +} + +/// [`apply_prefs_resets`] with the open window `w`, which is out of `app` while it draws or applies. +fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindow>) -> bool { + let resets = app.session.take_prefs_resets(); + if resets.is_empty() { + return false; + } + let in_reset = |category: &str| resets.iter().any(|r| r.is_none_or(|c| c == category)); + for (key, value) in default_ui_fields(&app.ui) { + if !UI_FIELDS.iter().any(|&(k, c, _)| k == key && in_reset(c)) { + continue; + } + match key { + "__smartGuides" => app.ui.view.smart_guides = value, + "__snapToGrid" => app.ui.view.snap_to_grid = value, + _ => app.ui.task_bar = value, + } + // The window shows the reset row, so OK keeps it. + if let Some(w) = w.as_deref_mut() { + w.draft.set(key, &value); + } + } + // And the reset preferences, the groups with a reset of every category; Units ▸ General then leaves the open + // document's units alone on OK. + if let Some(w) = w { + let every = resets.contains(&None); + let prefs = app.session.prefs.to_json(); + for (k, v) in prefs.as_object().into_iter().flatten() { + let reset = spec(k).map_or(every && PREF_GROUPS.contains(&k.as_str()), |s| in_reset(s.category)); + if reset && w.draft.get::(k).is_some() { + w.draft.set(k, v); + if k == "unitsGeneral" { + w.reset_units = v.as_str().map(str::to_string); + } + } + } + w.sync_strings(); + } + // The Edit Original row shows the app's Edit Original choice. + if spec("editOriginalSystemDefaults").is_some_and(|s| in_reset(s.category)) { + crate::original_editor::reset_saved(app); + } + true +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index b4693d5830..25740a3dce 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -269,14 +269,25 @@ impl Live<'_> { page } - /// Sets every key of the draft to its default, as the answered Reset question does. + /// Sets every key of the draft to its default, the UI-only rows ([`UI_FIELDS`]) included, as the answered + /// Reset question does. fn reset_all(&mut self) { let keys: Vec = Prefs::default().to_json().as_object().into_iter().flatten().map(|(k, _)| k.clone()).filter(|k| super::is_known(k)).collect(); self.w.reset_keys(keys.iter().map(String::as_str)); + self.reset_ui_rows(|_| true); crate::original_editor::reset(self.app); } + /// Sets the UI-only rows of the categories `reset` names to their defaults. + fn reset_ui_rows(&mut self, reset: impl Fn(&str) -> bool) { + for (key, value) in super::default_ui_fields(&self.app.ui) { + if UI_FIELDS.iter().any(|&(k, c, _)| k == key && reset(c)) { + self.w.draft.set(key, &value); + } + } + } + /// The answers of the dialogs the window opened: the Reset question and the colour picker. pub(super) fn take_answers(&mut self) { if let Some(id) = self.w.reset_asked @@ -388,6 +399,11 @@ impl PreferencesModel for Live<'_> { fn reset_page(&mut self, page: &str) { let keys: Vec<&str> = PREF_SPECS.iter().filter(|s| s.category == page).map(|s| s.key).collect(); self.w.reset_keys(keys); + self.reset_ui_rows(|c| c == page); + // The Edit Original row of its page. + if spec("editOriginalSystemDefaults").is_some_and(|s| s.category == page) { + crate::original_editor::reset(self.app); + } } fn nested(&mut self, ui: &mut egui::Ui) { @@ -406,20 +422,33 @@ impl PreferencesDraft for Live<'_> { } fn apply(&mut self) -> Result<(), String> { + // A `prefs.reset` run since the last frame shows in the draft before OK reads it. + super::apply_prefs_resets_to(self.app, Some(&mut *self.w)); let values: Map = self.w.draft.to::>().unwrap_or_default().into_iter().filter(|(k, _)| !k.starts_with("__")).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u)); // A refused folder, typed or picked, comes back here as the engine's message. self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; + // When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the workspace being + // left; otherwise after it, so a return from Touch gives it to the workspace returned to. + let before_switch = touch_ws.is_some() && crate::workspaces::enters_touch(self.app, self.app.touch_screen); + if before_switch && let Some(on) = self.w.draft.get::("__taskBar") { + self.app.ui.task_bar = on; + } + let was_touch = crate::workspaces::is_current(&self.app.ui, crate::workspaces::TOUCH); if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(self.app, self.app.touch_screen); } + // When OK leaves Touch, the workspace returned to takes the row only when it changed since the window opened or + // last applied; otherwise it keeps its own. + let left_touch = was_touch && !crate::workspaces::is_current(&self.app.ui, crate::workspaces::TOUCH); + let task_bar_row = self.w.draft.get::("__taskBar").filter(|on| !left_touch || self.w.opened.get::("__taskBar") != Some(*on)); let flag = |key: &str, now: bool| self.w.draft.get::(key).unwrap_or(now); let (smart_guides, snap_to_grid, task_bar) = ( flag("__smartGuides", self.app.ui.view.smart_guides), flag("__snapToGrid", self.app.ui.view.snap_to_grid), - flag("__taskBar", self.app.ui.task_bar), + if before_switch { self.app.ui.task_bar } else { task_bar_row.unwrap_or(self.app.ui.task_bar) }, ); self.app.ui.view.smart_guides = smart_guides; self.app.ui.view.snap_to_grid = snap_to_grid; @@ -427,6 +456,9 @@ impl PreferencesDraft for Live<'_> { crate::original_editor::commit(self.app); super::snapshot(self.app); self.app.prefs_changed = true; + // The row shows the task bar in use: after OK enters Touch, that is Touch's, not the value the workspace left + // took, so a later Apply does not give the workspace left's value to Touch. + self.w.draft.set("__taskBar", &self.app.ui.task_bar); self.w.opened = self.w.draft.clone(); Ok(()) } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 393561679d..daad8a6bef 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -298,6 +298,291 @@ fn reset_preferences_keeps_an_edit_of_general_units() { assert_eq!(b.session.prefs.units_general, Prefs::default().units_general); } +/// Smart Guides, Snap to Grid and Enable Contextual Task Bar, the UI-only rows. +fn ui_rows(a: &VectorcraftApp) -> (bool, bool, bool) { + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) +} + +fn set_ui_rows(a: &mut VectorcraftApp, rows: (bool, bool, bool)) { + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = rows; +} + +/// The Contextual Task Bar workspace `name` was left with. +fn left_task_bar(a: &VectorcraftApp, name: &str) -> bool { + let id = &crate::workspaces::find(&a.ui, name).expect("a workspace").id; + a.ui.workspaces.edited.get(id).expect("left").task_bar +} + +/// Reset Preferences returns every UI-only row (Smart Guides, Snap to Grid, Enable Contextual Task Bar) to its +/// default in the draft, the value a new app shows. OK applies them; Cancel keeps the values in use. +#[test] +fn reset_preferences_resets_the_ui_only_rows() { + let default = ui_rows(&app()); + let changed = (!default.0, !default.1, !default.2); + let reset_changed = |a: &mut VectorcraftApp| { + set_ui_rows(a, changed); + open(a, Some("General")); + reset_preferences(a, PromptChoice::Proceed); + }; + let mut a = app(); + reset_changed(&mut a); + assert_eq!( + (field(&a, "__smartGuides"), field(&a, "__snapToGrid"), field(&a, "__taskBar")), + (json!(default.0), json!(default.1), json!(default.2)) + ); + assert_eq!(ui_rows(&a), changed, "nothing applied before OK"); + confirm(&mut a).unwrap(); + assert_eq!(ui_rows(&a), default, "OK applies the defaults"); + + let mut b = app(); + reset_changed(&mut b); + cancel(&mut b); + assert!(!is_open(&b)); + assert_eq!(ui_rows(&b), changed, "Cancel keeps the values in use"); +} + +/// A page's own reset also resets the UI-only row of that page, and only that one. +#[test] +fn a_page_reset_resets_the_ui_only_row_of_the_page() { + let mut a = app(); + let default = ui_rows(&a); + set_ui_rows(&mut a, (!default.0, !default.1, !default.2)); + // The saved Edit Original choice has no setter outside its module; the UI state's saved form sets it. + let chosen = json!({"path": "editor"}); + let editor = |a: &VectorcraftApp| serde_json::to_value(&a.ui.original_editor).unwrap_or_default(); + a.ui.original_editor = serde_json::from_value(chosen.clone()).unwrap(); + let reset_page = |a: &mut VectorcraftApp, page: &str| { + open(a, Some(page)); + let mut w = a.prefs.take().expect("Preferences is open"); + model::Live { app: &mut *a, w: &mut w }.reset_page(page); + a.prefs = Some(w); + }; + reset_page(&mut a, "General"); + assert_eq!(field(&a, "__taskBar"), json!(default.2), "General: Enable Contextual Task Bar"); + assert_eq!((field(&a, "__smartGuides"), field(&a, "__snapToGrid")), (json!(!default.0), json!(!default.1)), "the other pages' rows"); + confirm(&mut a).unwrap(); + assert_eq!(editor(&a), chosen, "General keeps the Edit Original choice"); + reset_page(&mut a, "File Handling"); + confirm(&mut a).unwrap(); + assert_eq!(editor(&a)["path"], Value::Null, "File Handling resets the Edit Original choice"); +} + +/// `prefs.reset` (the Command Palette's Reset Preferences) also returns the UI-only rows to their defaults, as a +/// batch step too; with a category, only that category's rows; with an unknown or malformed category, none. +#[test] +fn prefs_reset_resets_the_ui_only_rows_of_its_category() { + let default = ui_rows(&app()); + let changed = (!default.0, !default.1, !default.2); + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + set_ui_rows(&mut a, changed); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + for bad in [json!("Nowhere"), json!(["General"]), json!(5)] { + assert!(a.run("prefs.reset", json!({"category": bad})).is_err(), "{bad}"); + assert_eq!(ui_rows(&a), changed, "{bad}: an unknown or malformed category resets nothing"); + assert_eq!(a.session.prefs.keyboard_increment, 7.0, "{bad}: the preferences are kept"); + } + a.run("prefs.reset", json!({"category": "general"})).unwrap(); + assert_eq!(ui_rows(&a), (changed.0, changed.1, default.2), "General: Enable Contextual Task Bar only"); + a.run("command.batch", json!({"commands": [{"command": "prefs.reset", "params": {"category": "Guides & Grid"}}]})).unwrap(); + assert_eq!(ui_rows(&a), (changed.0, default.1, default.2), "Guides & Grid, as a batch step: Snap to Grid only"); + a.run("prefs.reset", json!({"category": "Smart Guides"})).unwrap(); + assert_eq!(ui_rows(&a), default, "Smart Guides: Smart Guides"); + set_ui_rows(&mut a, changed); + a.run("prefs.reset", json!({})).unwrap(); + assert_eq!(ui_rows(&a), default, "every category"); +} + +/// A `prefs.reset` run while Preferences is open shows the reset values in the draft, for the categories it reset, +/// so OK keeps the reset; rows of other categories keep the draft's values. +#[test] +fn prefs_reset_while_preferences_is_open_shows_the_reset_values() { + let fresh = app(); + let default = ui_rows(&fresh); + let mut a = app(); + set_ui_rows(&mut a, (!default.0, !default.1, !default.2)); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + open(&mut a, Some("General")); + a.run("prefs.reset", json!({"category": "General"})).unwrap(); + assert_eq!(field(&a, "__taskBar"), json!(default.2), "the window shows the reset row"); + assert_eq!(field(&a, "__smartGuides"), json!(!default.0), "a row of another category keeps its value"); + confirm(&mut a).unwrap(); + assert_eq!(ui_rows(&a), (!default.0, !default.1, default.2), "OK keeps the reset"); + assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment, "OK keeps the reset preference"); + + // Every category, the preference groups included. + let group = fresh.session.prefs.to_json()["pixelSnap"].clone(); + let mut changed = group.clone(); + let flag = changed.as_object_mut().and_then(|o| o.values_mut().find(|v| v.is_boolean())).expect("a pixelSnap option is a boolean"); + *flag = json!(!flag.as_bool().unwrap_or_default()); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + a.run("prefs.set", json!({"key": "pixelSnap", "value": changed})).unwrap(); + open(&mut a, Some("General")); + assert_eq!(field(&a, "pixelSnap"), changed); + a.run("prefs.reset", json!({})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(ui_rows(&a), default, "every category"); + assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment); + assert_eq!(a.session.prefs.to_json()["pixelSnap"], group, "OK keeps the reset group"); + + // Run straight on the session, with OK before the next frame. + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + open(&mut a, Some("General")); + a.session.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment, "OK keeps a reset outside run"); +} + +/// Reset Preferences and `prefs.reset` give Enable Contextual Task Bar the value the current workspace was saved +/// with, which for a workspace saved with the bar off differs from the default. +#[test] +fn reset_preferences_gives_the_task_bar_the_workspaces_value() { + let off = crate::workspaces::builtins().into_iter().find(|w| !w.record.task_bar).expect("a workspace saved with the bar off"); + let in_workspace = |a: &mut VectorcraftApp| { + crate::workspaces::switch(a, off.name).unwrap(); + assert!(!a.ui.task_bar, "{} starts with the bar off", off.name); + a.ui.task_bar = true; + }; + let mut a = app(); + in_workspace(&mut a); + open(&mut a, Some("General")); + reset_preferences(&mut a, PromptChoice::Proceed); + assert_eq!(field(&a, "__taskBar"), json!(false), "the draft shows the workspace's value"); + confirm(&mut a).unwrap(); + assert!(!a.ui.task_bar, "OK applies the workspace's value"); + + let mut b = app(); + in_workspace(&mut b); + b.run("prefs.reset", json!({"category": "General"})).unwrap(); + assert!(!b.ui.task_bar, "prefs.reset gives the workspace's value"); + let mut c = app(); + assert!(c.ui.task_bar, "the default workspace starts with the bar on"); + c.ui.task_bar = false; + c.run("prefs.reset", json!({})).unwrap(); + assert!(c.ui.task_bar, "the default workspace's value"); +} + +/// On a touch screen, OK after Reset Preferences turns Enable Touch Workspace back on: the reset task bar goes to +/// the workspace left, and Touch keeps its own. With Touch entered automatically while Preferences was open, +/// clearing Enable Touch Workspace gives the row to the workspace returned to. +#[test] +fn ok_sets_the_task_bar_in_the_workspace_outside_touch() { + use crate::workspaces::{TOUCH, is_current, switch, sync_touch_workspace}; + let mut a = app(); + a.touch_screen = true; + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + switch(&mut a, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + open(&mut a, Some("General")); + reset_preferences(&mut a, PromptChoice::Proceed); + assert_eq!(field(&a, "touchWorkspace"), json!(true), "the reset turns it on"); + confirm(&mut a).unwrap(); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + assert!(!left_task_bar(&a, "Essentials Classic"), "the workspace left takes the reset value"); + + let mut b = app(); + b.run("prefs.set", json!({"key": "touchWorkspace", "value": true})).unwrap(); + switch(&mut b, "Essentials Classic").unwrap(); + open(&mut b, Some("General")); + b.touch_screen = true; + sync_touch_workspace(&mut b, true); + assert!(is_current(&b.ui, TOUCH)); + set_field(&mut b, "touchWorkspace", json!(false)).unwrap(); + confirm(&mut b).unwrap(); + assert!(is_current(&b.ui, "Essentials Classic")); + assert!(!b.ui.task_bar, "the workspace returned to takes the row"); + assert!(left_task_bar(&b, TOUCH), "Touch keeps its own task bar"); +} + +/// After an Apply that enters Touch, the task bar row shows Touch's task bar: a later Apply that leaves the row +/// unedited keeps it, and an edit or a reset of the row reaches it. Leaving Touch with the row unedited gives the +/// workspace returned to the value it left with. +#[test] +fn apply_after_entering_touch_keeps_touchs_task_bar() { + use crate::workspaces::{TOUCH, is_current, switch}; + use craft::ui::patterns::preferences::PreferencesDraft as _; + let apply = |a: &mut VectorcraftApp| { + let mut w = a.prefs.take().expect("Preferences is open"); + let r = model::Live { app: &mut *a, w: &mut w }.apply(); + a.prefs = Some(w); + r.unwrap(); + }; + let mut a = app(); + a.touch_screen = true; + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + switch(&mut a, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + open(&mut a, Some("General")); + reset_preferences(&mut a, PromptChoice::Proceed); + assert_eq!(field(&a, "__taskBar"), json!(false), "the reset row differs from Touch's task bar"); + apply(&mut a); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + apply(&mut a); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "an Apply without a task bar edit keeps Touch's task bar"); + assert_eq!(field(&a, "__taskBar"), json!(true), "the row shows Touch's task bar"); + set_field(&mut a, "__taskBar", json!(false)).unwrap(); + apply(&mut a); + assert!(!a.ui.task_bar, "an edit to the row reaches Touch"); + + // Reset Preferences in Touch gives Touch its saved value, the value the row showed before the edit. + reset_preferences(&mut a, PromptChoice::Proceed); + apply(&mut a); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "the reset reaches Touch"); + + // Leaving Touch with the row unedited: the workspace returned to keeps the value it left with. + set_field(&mut a, "touchWorkspace", json!(false)).unwrap(); + apply(&mut a); + assert!(is_current(&a.ui, "Essentials Classic")); + assert!(!a.ui.task_bar, "the workspace returned to keeps its reset value"); +} + +/// A Touch return marker left over from an earlier automatic switch (Window › Workspace does not clear it) does not +/// change where OK puts the task bar: OK enters Touch from the workspace it leaves, so that workspace takes the row +/// and Touch keeps its own. +#[test] +fn ok_sets_the_task_bar_in_the_workspace_left_with_a_stale_touch_marker() { + use crate::workspaces::{TOUCH, is_current, switch}; + let mut a = app(); + a.touch_screen = true; + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + a.ui.touch_workspace_restore = Some("Typography".into()); + switch(&mut a, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + open(&mut a, Some("General")); + reset_preferences(&mut a, PromptChoice::Proceed); + confirm(&mut a).unwrap(); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + assert!(!left_task_bar(&a, "Essentials Classic"), "the workspace left takes the reset value"); +} + +/// A `prefs.reset` run straight on the session, outside `VectorcraftApp::run`, resets the UI-only rows in the next +/// frame, and before the next command switches workspaces. +#[test] +fn prefs_reset_outside_run_resets_the_ui_only_rows_in_the_next_frame() { + let mut a = app(); + let default = ui_rows(&a); + set_ui_rows(&mut a, (!default.0, !default.1, !default.2)); + a.session.execute("prefs.reset", &json!({})).unwrap(); + let ctx = a.ui_ctx.clone().expect("a window context"); + crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default()); + assert_eq!(ui_rows(&a), default); + + // Before the next command switches workspaces: the workspace left keeps the reset value. + let mut b = app(); + crate::workspaces::switch(&mut b, "Essentials Classic").unwrap(); + b.ui.task_bar = true; + b.session.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + b.run("window.workspace", json!({"name": crate::workspaces::ESSENTIALS})).unwrap(); + assert!(b.ui.task_bar, "Essentials keeps its own task bar"); + assert!(!left_task_bar(&b, "Essentials Classic"), "the workspace left keeps the reset value"); +} + #[test] fn old_pref_files_keep_their_brightness() { let mut a = app(); @@ -527,6 +812,23 @@ fn prefs_import_of_touch_workspace_switches_the_workspace() { assert!(crate::workspaces::is_current(&a.ui, "Typography")); } +/// A `prefs.reset` run straight on the session, then a touch screen that switches to Touch: the workspace left keeps +/// the reset value. +#[test] +fn a_pending_prefs_reset_applies_before_a_touch_switch() { + use crate::workspaces::{TOUCH, is_current, switch, sync_touch_workspace}; + let mut a = app(); + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + switch(&mut a, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + a.session.execute("prefs.reset", &json!({})).unwrap(); + assert!(a.session.prefs.touch_workspace, "the reset turns Enable Touch Workspace on"); + sync_touch_workspace(&mut a, true); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + assert!(!left_task_bar(&a, "Essentials Classic"), "the workspace left keeps the reset value"); +} + /// A folder that no folder can be created in, or that is not there, is refused on OK with the /// engine's message, and the draft keeps its value. #[test] diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 9f1fcecb71..d7545f2df7 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -51,6 +51,9 @@ pub struct Done { /// The frame holds pixels copied from the worker's last frame ([`crate::canvas::render_job`]), /// and `ms` is the time of the copy and of the parts rendered. pub reused: bool, + /// The frame drew art in a way that depends on its size + /// ([`vectorcraft_render::FrameStats::view_sized`]): a part of it drawn on its own may differ. + pub view_sized: bool, } /// Render `job` as the worker thread does: inside the job's automation roots and deferred @@ -59,7 +62,7 @@ pub(crate) fn render(r: &mut Renderer, kept: &mut Option, + /// Told whether the active tool reads an airbrush pen's finger wheel (Windows: the host opens + /// the tablet driver's Wintab context only while it does). Without it nothing is told. + pub stylus_wheel: Option>, pub read: Option, /// Read at most a number of bytes from a file (desktop). A file with a size limit is read one /// byte past the limit, so a larger file is refused without reading all of it. Without it, the diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index c02f72f02e..42f01d739b 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -226,7 +226,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(c.id); } - let group = if c.menu.is_empty() { id_group(c.id) } else { c.menu.join(" › ") }; + let group = command_group(c.id, c.menu); v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false }); } v.extend(crate::state::all_panels().map(|(id, label)| Entry { @@ -246,28 +246,30 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(id); } - tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false }); + tail.push(Entry { key: id.to_string(), label: label.to_string(), group: command_group(id, &[]), is_tool: false, shows_key: false }); } // A command listed only because an item of the menu bar runs it can have the group and // label of another entry. When that entry is an engine command that no item of the menu bar - // runs, the command the item runs keeps the name and the other entry is shown in the group - // of its id: File › Export Selection… runs `file.exportSelection`, as the menu item does, - // and `document.exportSelection` shows as Document › Export Selection…. Otherwise the - // command is left out: Window › Learn stays the Learn panel's entry. Entries that still - // have the same name, plug-ins included, are given names of their own by - // [`distinct_names`]. + // runs, the command the item runs keeps the name and the other entry is shown in its own + // group ([`own_group`]): File › Export Selection… runs `file.exportSelection`, as the menu + // item does, and `document.exportSelection` shows as Document › Export Selection…. When + // that is the group the other entry has already, both are listed: Object › Expand… runs + // the Expand dialog, and `object.expand` shows its key. Otherwise the command is left out: + // Window › Learn stays the Learn panel's entry. Entries that still have the same name, + // plug-ins included, are given names of their own by [`distinct_names`]. let name = |e: &Entry| (e.group.clone(), e.label.clone()); - let new_names: HashSet<_> = v.iter().chain(&tail).filter(|e| by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); - for e in v.iter_mut().chain(tail.iter_mut()) { - if new_names.contains(&name(e)) - && !by_the_menu_bar.contains(e.key.as_str()) + let movable = |e: &Entry| { + !by_the_menu_bar.contains(e.key.as_str()) && vectorcraft_engine::find_command(&e.key).is_some() && !menu_bar_items().contains_key(e.key.as_str()) - { - e.group = id_group(&e.key); + }; + let new_names: HashSet<_> = v.iter().chain(&tail).filter(|e| by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); + for e in v.iter_mut().chain(tail.iter_mut()) { + if new_names.contains(&name(e)) && movable(e) { + e.group = own_group(&e.key); } } - let names: HashSet<_> = v.iter().chain(&tail).filter(|e| !by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); + let names: HashSet<_> = v.iter().chain(&tail).filter(|e| !by_the_menu_bar.contains(e.key.as_str()) && !movable(e)).map(name).collect(); let keep = |e: &Entry| !by_the_menu_bar.contains(e.key.as_str()) || !names.contains(&name(e)); v.retain(keep); tail.retain(keep); @@ -402,6 +404,115 @@ fn name_of(e: &Entry, group: &str, label: &str) -> String { if e.shows_key { format!("{name} ({})", e.key) } else { name } } +/// The group of command `id`, whose menu path is `menu`: that path, or for a command no menu holds +/// the menu path of the item of the menu bar that runs it ([`menu_bar_path`]: Recolor Artwork… +/// goes under Edit › Edit Colors), or else [`own_group`]. +fn command_group(id: &str, menu: &[&str]) -> String { + if !menu.is_empty() { + return menu.join(" › "); + } + menu_bar_path(id).map_or_else(|| own_group(id), str::to_string) +} + +/// The group of a command that neither a menu nor an item of the menu bar holds: the menu path the +/// items of the menu bar that run the commands of its id's first two parts share (Remove Corners +/// goes under Object › Plug-ins › Path Precision Tools with Set Corners), else its [`GROUPS`] +/// entry, else [`id_group`]. +fn own_group(id: &str) -> String { + if let Some(path) = family_path(id) { + return path.to_string(); + } + GROUPS + .iter() + .find(|(key, _)| if key.ends_with('.') { id.starts_with(key) } else { id == *key }) + .map_or_else(|| id_group(id), |(_, g)| g.to_string()) +} + +/// The one menu path of the items of the menu bar that run the other commands whose id starts with +/// the first two parts of an id of three or more parts (`addon.pathtools.`). +fn family_path(id: &str) -> Option<&'static str> { + let mut parts = id.splitn(3, '.'); + let (Some(a), Some(b), Some(_)) = (parts.next(), parts.next(), parts.next()) else { return None }; + let prefix = format!("{a}.{b}."); + let mut paths = menu_bar_paths().keys().filter(|k| k.starts_with(&prefix) && k.as_str() != id).filter_map(|k| menu_bar_path(k)); + let first = paths.next()?; + paths.all(|p| p == first).then_some(first) +} + +/// The groups of the commands of Keyboard Shortcuts that no menu holds and whose id's first part +/// is no name: (id, or the start of ids when it ends with `.`; group). A panel's commands go under +/// the panel's Window menu item (Window › Layers), and a dialog's under the menu or panel that +/// opens it. +const GROUPS: &[(&str, &str)] = &[ + ("addon.", "Object › Plug-ins"), + ("app.", "Application"), + ("css.", "Window › CSS Properties"), + ("docInfo.", "Window › Document Info"), + ("imageTrace.", "Window › Image Trace"), + ("livePaint.", "Object › Live Paint"), + ("plugin.", "Object › Plug-ins"), + ("svgFilter.", "SVG Filters"), + ("svgInteractivity.", "Window › SVG Interactivity"), + ("threeD.", "Window › 3D and Materials"), + ("ui.action.", "Window › Actions"), + ("ui.actionSet.", "Window › Actions"), + ("ui.blendOptions", "Window › Properties"), + ("ui.brushObjectOptions", "Window › Brushes"), + ("ui.brushOptions", "Window › Brushes"), + ("ui.bulletsAndNumbering", "Window › Paragraph"), + ("ui.colorGroupOptions", "Window › Swatches"), + ("ui.colorGuideOptions", "Window › Color Guide"), + ("ui.colorPicker", "Color"), + ("ui.colorRgbPercent", "Window › Color"), + ("ui.corners", "Window › Transform"), + ("ui.dialogReset", "Dialogs"), + ("ui.dxfOptionsDialog", "File"), + ("ui.epsOptionsDialog", "File"), + ("ui.fileInfoDialog", "File"), + ("ui.findAndReplace", "Window › Properties"), + ("ui.findFontsInFolder", "Type"), + ("ui.hpglOptionsDialog", "File"), + ("ui.hyphenation", "Window › Paragraph"), + ("ui.javascriptFilesDialog", "Window › SVG Interactivity"), + ("ui.justification", "Window › Paragraph"), + ("ui.layerOptions", "Window › Layers"), + ("ui.layersPanelOptions", "Window › Layers"), + ("ui.loadAllStyles", "Window › Character Styles"), + ("ui.loadCharStyles", "Window › Character Styles"), + ("ui.loadParaStyles", "Window › Paragraph Styles"), + ("ui.missingFontsDialog", "Type"), + ("ui.newArtboard", "Window › Artboards"), + ("ui.newBrush", "Window › Brushes"), + ("ui.newCharStyle", "Window › Character Styles"), + ("ui.newColorGroup", "Window › Swatches"), + ("ui.newLayer", "Window › Layers"), + ("ui.newParaStyle", "Window › Paragraph Styles"), + ("ui.newSwatch", "Window › Swatches"), + ("ui.pdfSummary.", "File"), + ("ui.perspectivePlane", "View › Perspective Grid"), + ("ui.perspectiveUserPreset1.", "View › Perspective Grid › One Point Perspective"), + ("ui.perspectiveUserPreset2.", "View › Perspective Grid › Two Point Perspective"), + ("ui.perspectiveUserPreset3.", "View › Perspective Grid › Three Point Perspective"), + ("ui.placementOptionsDialog", "Window › Links"), + ("ui.rasterEffectsSettingsDialog", "Effect"), + ("ui.recolorRedo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.recolorUndo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.relinkDialog", "Window › Links"), + ("ui.rename", "Window › Layers"), + ("ui.retype", "Window › Properties"), + ("ui.runInstalledScript", "File › Scripts"), + ("ui.sampleScreenColor", "Color"), + ("ui.savePdfDialog", "File"), + ("ui.shortcutImportDialog", "Shortcuts"), + ("ui.simplifyAuto", "Object › Path › Simplify"), + ("ui.simplifyMoreOptions", "Object › Path › Simplify"), + ("ui.smoothAuto", "Object › Path › Smooth"), + ("ui.spotColors", "Window › Swatches"), + ("ui.symbolOptions", "Window › Symbols"), + ("ui.tateChuYokoSettings", "Window › Character"), + ("ui.warichuSettings", "Window › Character"), +]; + /// The group of a command no menu holds: the first part of its id, capitalised (`edit.x` → "Edit"). fn id_group(id: &str) -> String { let mut c = id.split('.').next().unwrap_or_default().chars(); @@ -410,7 +521,7 @@ fn id_group(id: &str) -> String { /// Gives entries that have the same group and label names of their own, and leaves the others as /// they are. It runs on the whole snapshot, plug-ins included, after [`fixed_entries`] has shown an -/// engine command in the group of its id or left out a command listed only because an item of the +/// engine command in its own group ([`own_group`]) or left out a command listed only because an item of the /// menu bar runs it: /// 1. A command that an item of the menu bar runs, as a key press would run it, is shown under /// that item's menu path ([`menu_bar_path`]): the four Other Library… commands go under Window › @@ -614,6 +725,29 @@ const NEEDS_A_PARAM: [&str; 77] = [ "type.ruby", ]; +/// UI commands with no default key, no menu bar item and a params doc whose fields are all optional +/// that a key press can run with no params: each opens its dialog for the selection, the current +/// item or the panel's selection, or reports in the status bar why it cannot. Rename names the +/// selection, Color Picker… opens for the proxy in front, Brush Options… for the selected path's +/// brush, and Layer Options for the highlighted rows. +pub(crate) const KEY_ONLY_UI: [&str; 15] = [ + "ui.rename", + "ui.colorPicker", + "ui.newSwatch", + "ui.newColorGroup", + "ui.colorGroupOptions", + "ui.newBrush", + "ui.brushOptions", + "ui.layerOptions", + "ui.corners", + "ui.placementOptionsDialog", + "ui.relinkDialog", + "ui.perspectivePlane", + "ui.bulletsAndNumbering", + "ui.missingFontsDialog", + "ui.findFontsInFolder", +]; + /// The (label, params) of each menu bar item, by command id. fn menu_bar_items() -> &'static HashMap> { static ITEMS: OnceLock>> = OnceLock::new(); @@ -704,11 +838,9 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool { /// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts /// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc -/// of `{}` or `{path…}`. Rename has no default key, and a key press names the selection: it needs -/// no `id`. Color Picker… has no default key either, and a key press opens it for the proxy in -/// front. +/// of `{}` or `{path…}`, or is one of [`KEY_ONLY_UI`]. fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool { - !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" || id == "ui.colorPicker" + !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || KEY_ONLY_UI.contains(&id) } /// Does a menu bar item run the command with no params, so that it does what its label says and opens @@ -2219,8 +2351,8 @@ mod tests { /// params, or with the one set of params all its items give) is listed in Edit › Keyboard /// Shortcuts, also when the command has no menu path of its own: Set Corners…, whose params doc /// names a field a call must give, the Perspective Grid toggles, Edit Custom Dictionary…, a - /// query, and Recolor Artwork…, a UI command. Such a command is listed in the group of its id, - /// next to the commands of its family that were listed before. A shortcut given to one survives + /// query, and Recolor Artwork…, a UI command. Such a command is listed under the menu path of + /// the item that runs it. A shortcut given to one survives /// a saved set's round trip. Find Next is left out: its menu item gives `find` empty, which the /// command rejects. When another entry has the same group and label, the command the menu item /// runs keeps the name if no menu item runs the other: File › Export Selection… is @@ -2244,7 +2376,9 @@ mod tests { assert_eq!(shown("file.exportSelection"), Some(("File".into(), "Export Selection…".into()))); assert_eq!(shown("document.exportSelection"), Some(("Document".into(), "Export Selection…".into()))); // No command listed only because an item of the menu bar runs it shares its group and label - // with another entry. + // with another entry, except an engine command that no item of the menu bar runs, whose own + // group is the same: that one shows its key. + let off_the_bar = |k: &str| vectorcraft_engine::find_command(k).is_some() && !menu_bar_items().contains_key(k); let own = |k: &str| { vectorcraft_engine::command_specs() .iter() @@ -2258,13 +2392,19 @@ mod tests { for e in v.iter().chain(tail) { names.entry((e.group.as_str(), e.label.as_str())).or_default().push(e.key.as_str()); } - let shared: Vec<_> = names.iter().filter(|(_, keys)| keys.len() > 1 && keys.iter().any(|k| !own(k))).collect(); + let shared: Vec<_> = names + .iter() + .filter(|(_, keys)| keys.len() > 1 && keys.iter().any(|k| !own(k)) && !keys.iter().filter(|k| own(k)).all(|k| off_the_bar(k))) + .collect(); assert!(shared.is_empty(), "{shared:?}"); + let keyed = |id: &str| entry(id).map(|e| (e.group, e.label, e.shows_key)); + assert_eq!(keyed("ui.expandDialog"), Some(("Object".into(), "Expand…".into(), false))); + assert_eq!(keyed("object.expand"), Some(("Object".into(), "Expand…".into(), true))); for (id, group) in [ - (crate::addons::pathtools::set_corners::COMMAND, "Addon"), - ("perspective.grid.snap", "Perspective"), - (crate::dialogs::custom_dictionary::COMMAND, "Text"), - ("ui.recolorDialog", "Ui"), + (crate::addons::pathtools::set_corners::COMMAND, "Object › Plug-ins › Path Precision Tools"), + ("perspective.grid.snap", "View › Perspective Grid"), + (crate::dialogs::custom_dictionary::COMMAND, "Edit"), + ("ui.recolorDialog", "Edit › Edit Colors"), ] { let e = entry(id).unwrap_or_else(|| panic!("{id} is listed")); assert_eq!(e.group, group, "{id}"); @@ -2575,4 +2715,46 @@ mod tests { assert!(needs_a_value("document.setUnits")); assert!(crate::palette::items().iter().all(|(_, id)| id != "document.setUnits")); } + + /// A command no menu holds is grouped under the menu path of the item of the menu bar that runs + /// it, or under the menu or panel it belongs to: no entry's group is a run-together id part + /// such as "Ui", "ImageTrace" or "ThreeD". + #[test] + fn commands_no_menu_holds_are_grouped_by_their_menu_or_panel() { + let menu_less = + |key: &str| vectorcraft_engine::find_command(key).map_or_else(|| menus::UI_COMMANDS.iter().any(|c| c.0 == key), |c| c.menu.is_empty()); + let mut names: HashSet = ["Tools", "Window"].into_iter().map(String::from).collect(); + names.extend(crate::state::all_panels().map(|(_, label)| label.to_string())); + names.extend(menus::menu_tree().into_iter().map(|(top, _)| top.to_string())); + names.extend(menu_bar_paths().values().flatten().flat_map(|(path, _)| path.split(" › ")).map(String::from)); + // A dialog's commands go under its command's label: Recolor Artwork, Character Style Options. + let labels = menus::UI_COMMANDS.iter().map(|c| c.1).chain(vectorcraft_engine::command_specs().iter().map(|c| c.label)); + names.extend(labels.map(|label| label.trim_end_matches('…').to_string())); + let mut wrong = vec![]; + for e in entries().iter().filter(|e| !e.is_tool && !e.key.contains(':') && menu_less(&e.key)) { + if let Some(path) = menu_bar_path(&e.key) + && e.group != path + { + wrong.push(format!("{}: {} is not under {path}", e.key, e.group)); + } + for part in e.group.split(" › ") { + let one_word = !part.contains(' ') && part.chars().skip(1).all(|c| !c.is_uppercase()); + if !names.contains(part) && (!one_word || ["Ui", "App", "Addon", "Css", "Plugin"].contains(&part)) { + wrong.push(format!("{}: {}", e.key, e.group)); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + // Every row of GROUPS groups a listed command. + let unused: Vec<_> = GROUPS + .iter() + .filter(|(key, _)| !entries().iter().any(|e| if key.ends_with('.') { e.key.starts_with(key) } else { e.key == *key })) + .collect(); + assert!(unused.is_empty(), "{unused:?}"); + let group = |id: &str| entry(id).map(|e| e.group); + assert_eq!(group("ui.recolorDialog").as_deref(), Some("Edit › Edit Colors")); + assert_eq!(group("ui.rename").as_deref(), Some("Window › Layers")); + assert_eq!(group("ui.justification").as_deref(), Some("Window › Paragraph")); + assert_eq!(group("addon.pathtools.cornerRemove").as_deref(), Some("Object › Plug-ins › Path Precision Tools")); + } } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index eaa0065ba4..decf0abcfa 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -30,13 +30,14 @@ pub(crate) fn run_fired(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &F return; } // A menu's Cut, Copy or Paste that no framework part took, while an egui text field has the keys, goes to that - // field as its clipboard event, as its keys would; Paste pastes the text of a Copy's formats, written first. + // field as its clipboard event, as its keys would; Paste pastes the text of a Copy's formats, written first, or + // nothing when they could not be written and have no text ([`VectorcraftApp::field_paste_text`]). if fired.source == FireSource::Menu && let Some(field) = ctx.memory(|m| m.focused()).filter(|&id| egui::TextEdit::load_state(ctx, id).is_some()) && let Some(event) = match fired.command.id.as_str() { "edit.copy" => Some(egui::Event::Copy), "edit.cut" => Some(egui::Event::Cut), - "edit.paste" | "edit.pasteWithoutFormatting" => app.written_clipboard_text().map(egui::Event::Paste), + "edit.paste" | "edit.pasteWithoutFormatting" => app.field_paste_text().map(egui::Event::Paste), _ => None, } { diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index cabde4b445..491b075729 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1839,3 +1839,26 @@ fn a_filter_plugin_row_translates_its_path_and_not_its_name() { assert_eq!(filter, format!("{path} › Group")); assert_eq!(command, format!("{path} › {}", crate::i18n::tr(zh, "Group"))); } + +/// A UI command whose params are all optional and that no item of the menu bar runs can be given a +/// key: Keyboard Shortcuts lists it, and the key opens its dialog or says in the status bar why it +/// cannot. +#[test] +fn a_key_runs_a_ui_command_whose_params_are_all_optional() { + for id in crate::shortcut_editor::KEY_ONLY_UI { + let mut app = app_with_a_selected_rectangle(); + let listed = app.run("shortcuts.list", json!({"query": id})).unwrap(); + assert!(listed.as_array().is_some_and(|rows| rows.iter().any(|r| r["id"] == id)), "{id} is listed: {listed}"); + // Rename edits the name in place and Color Picker… opens the framework's picker; other tests + // check what they open. + if ["ui.rename", "ui.colorPicker"].contains(&id) { + continue; + } + let ctx = ready(&mut app); + bind(&mut app, id, "Cmd+Alt+Shift+F12"); + app.ui.status.clear(); + key_frame(&mut app, &ctx, tap(Key::F12, cmd() | Modifiers::ALT | Modifiers::SHIFT)); + key_frame(&mut app, &ctx, vec![]); + assert!(dialog_kind(&app).is_some() || !app.ui.status.is_empty(), "{id}: the key opens a dialog or reports why not"); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b37805eb57..1ed56d8faa 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -156,10 +156,16 @@ impl View { /// Takes the view the canvas reports back, the inverse of [`Self::canvas`]. pub fn set_canvas(&mut self, view: &CanvasView, ui_scaling: f32) { self.center = view.center; - self.zoom = view.zoom * f64::from(ui_scaling); + self.zoom = Self::zoom_of_canvas(view, ui_scaling); self.rotation = view.rotation; self.rect = view.rect; } + + /// The zoom [`Self::zoom`] holds for the canvas view `view` at `ui_scaling`, the inverse of the + /// zoom in [`Self::canvas`]: the zoom `view.setZoom` and the View menu set and the status bar shows. + pub fn zoom_of_canvas(view: &CanvasView, ui_scaling: f32) -> f64 { + view.zoom * f64::from(ui_scaling) + } } /// The status bar's angle menu and View › Rotate View list these preset view angles, each as diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index f92fc2f347..dc3a9f5195 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -22,6 +22,10 @@ use crate::VectorcraftApp; /// The tool the pen's eraser end selects. const ERASER: &str = "eraser"; +/// What decides whether the active tool reads an airbrush pen's finger wheel ([`sync_wheel_use`]): +/// the active document's uid and revision, its current brush, and the tool with its options. +type WheelKey = (Option<(u64, u64)>, Option, &'static str, serde_json::Value); + /// The end of the pen the canvas saw last, and the tool the eraser end stands in for /// ([`sync_eraser_tool`]). #[derive(Clone, Debug, Default)] @@ -30,6 +34,8 @@ pub(crate) struct PenEnd { end: Option, /// The tool that was active when the eraser end selected the Eraser. before: Option<&'static str>, + /// What the host was last told about the finger wheel, and for which state ([`sync_wheel_use`]). + wheel: Option<(WheelKey, bool)>, } impl PenEnd { @@ -79,6 +85,33 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool { } } +/// Tells the host whether the active tool reads an airbrush pen's finger wheel +/// ([`crate::Services::stylus_wheel`]): the Paintbrush with a brush on Stylus Wheel, or +/// the Blob Brush or the Eraser with a value on it. The host is told at the first call and then each time the answer +/// changes; the tool is asked again only when the document, its current brush, the tool or its +/// options change. +/// +/// [`VectorcraftApp::tick`] calls this once a frame, with no document open too, and the canvas +/// calls it again when the pen's end changes the tool ([`sync_eraser_tool`]). +pub(crate) fn sync_wheel_use(app: &mut VectorcraftApp) { + if app.services.stylus_wheel.is_none() { + return; + } + let st = app.session.active(); + let key = + (st.map(|s| (s.uid, s.revision)), st.and_then(|s| vectorcraft_brush::current(&s.doc)), app.session.tool_id(), app.session.tool_options()); + if app.pen_end.wheel.as_ref().is_some_and(|(k, _)| *k == key) { + return; + } + let used = app.session.tool_reads_wheel(app.view_info()); + let told = app.pen_end.wheel.replace((key, used)).map(|(_, u)| u); + if told != Some(used) + && let Some(tell) = app.services.stylus_wheel.as_mut() + { + tell(used); + } +} + #[cfg(test)] mod tests { use super::*; @@ -126,4 +159,33 @@ mod tests { assert!(!sync_eraser_tool(&mut app)); assert_eq!(app.session.tool_id(), "rectangle"); } + + #[test] + fn the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel() { + use serde_json::json; + let told = std::rc::Rc::new(std::cell::RefCell::new(vec![])); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let tell = told.clone(); + app.services.stylus_wheel = Some(Box::new(move |used| tell.borrow_mut().push(used))); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.select_tool("paintbrush"); + let frame = |app: &mut VectorcraftApp| { + sync_wheel_use(app); + told.borrow().clone() + }; + assert_eq!(frame(&mut app), [false], "told at the first frame"); + assert_eq!(frame(&mut app), [false], "and not again while nothing changes"); + app.session.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + assert_eq!(frame(&mut app), [false], "a brush without Stylus Wheel"); + let params = json!({"variation": [0, 0, 2], "modes": ["fixed", "fixed", "stylusWheel"]}); + app.session.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + assert_eq!(frame(&mut app), [false, true], "its size on Stylus Wheel"); + app.select_tool("rectangle"); + assert_eq!(frame(&mut app), [false, true, false], "another tool"); + app.select_tool(ERASER); + assert_eq!(frame(&mut app), [false, true, false], "the Eraser at its defaults"); + app.session.set_tool_option("sizeMode", &json!("stylusWheel")); + app.session.set_tool_option("sizeVariation", &json!(4)); + assert_eq!(frame(&mut app), [false, true, false, true], "its size on Stylus Wheel"); + } } diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index cc214b08dd..9371e118fd 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -85,8 +85,8 @@ pub(crate) struct Publishing { /// The latest one's formats wait to be written. pending: bool, /// The latest one's formats could not be written: what the system clipboard's text was when the - /// write failed, and the text of those formats. - unwritten: Option<(Held, String)>, + /// write failed, and the text of those formats, if they have text. + unwritten: Option<(Held, Option)>, /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] /// then. Its formats' notes replace the message only while the status bar still shows it and /// nothing has set the status since. @@ -120,6 +120,22 @@ impl Publishing { fn shows_status(&self, ui: &crate::state::UiState) -> bool { ui.status == self.status.0 && ui.status_sets == self.status.1 } + + /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing + /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? Different text read from `cb` shows + /// a later copy: the record of the failed write is then dropped, so the clipboard holding the + /// older text again later does not bring it back. Text that could not be read keeps the record. + fn holds_unwritten(&mut self, cb: &mut Clipboard) -> bool { + let Some((held, _)) = &self.unwritten else { return false }; + let now = held_text(cb); + if now == *held { + return true; + } + if now.is_some() { + self.unwritten = None; + } + false + } } /// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the @@ -185,14 +201,31 @@ impl VectorcraftApp { || self.clipboard.holds_ours() } + /// Is the latest Copy or Cut one whose formats could not be written to the system clipboard, + /// with nothing copied since? Paste then takes the internal clipboard, and a paste into type or + /// a text field takes that copy's text (nothing when its formats have no text), until another + /// app copies something. A copy is noticed only when it changes the clipboard's text, so the + /// copy is kept only when the clipboard held text when the write failed. When it held only a + /// picture, or nothing that could be read, Paste takes what the clipboard holds. + fn holds_unwritten_copy(&mut self) -> bool { + self.clipboard_publishing.holds_unwritten(&mut self.clipboard) + } + /// The text of the latest Copy or Cut whose formats could not be written to the system - /// clipboard, while nothing has been copied since that Copy or Cut. A paste into type or a text - /// field takes this text until another app copies something. A copy is noticed only when it - /// changes the clipboard's text, so the copy is kept only when the clipboard held text when the - /// write failed. + /// clipboard, while nothing has been copied since that Copy or Cut + /// ([`Self::holds_unwritten_copy`]). pub(crate) fn unwritten_clipboard_text(&mut self) -> Option { - let (held, text) = self.clipboard_publishing.unwritten.as_ref()?; - (held_text(&mut self.clipboard) == *held).then(|| text.clone()) + self.clipboard_publishing.unwritten.as_ref()?.1.as_ref()?; + self.unwritten_copy().flatten() + } + + /// While [`Self::holds_unwritten_copy`]: the text of that copy's formats, `None` inside when + /// they have no text. + fn unwritten_copy(&mut self) -> Option> { + if !self.holds_unwritten_copy() { + return None; + } + self.clipboard_publishing.unwritten.as_ref().map(|(_, text)| text.clone()) } /// After Copy or Cut: offer the copied objects to other apps. The background worker makes the @@ -279,8 +312,8 @@ impl VectorcraftApp { /// Writes `formats` to the system clipboard; `before` is the clipboard's text at the Copy or Cut. /// When that fails, another app may hold the clipboard open: it keeps what it held (or what the - /// failed write left), and a paste into text takes this copy's text until something else is - /// copied ([`Self::unwritten_clipboard_text`]). + /// failed write left). Until something else is copied, Paste takes this copy, and a paste into + /// text takes its text ([`Self::holds_unwritten_copy`]). fn write_formats(&mut self, formats: &[Flavor], before: &Held) -> Result { let cb = &mut self.clipboard; let before_write = held_text(cb); @@ -306,7 +339,7 @@ impl VectorcraftApp { // A clipboard with no text can't show a later copy of a picture, or tell an empty clipboard // from one that couldn't be read: unless it held text the write emptied, and it reads. let trackable = held.is_some() || (before_write.is_some() && cb.read(&[TEXT]).is_ok()); - self.clipboard_publishing.unwritten = text.filter(|_| current && left_by_write && trackable).map(|text| (held, text)); + self.clipboard_publishing.unwritten = (current && left_by_write && trackable).then_some((held, text)); Err(e.to_string()) } @@ -389,17 +422,20 @@ impl VectorcraftApp { let waited = ctx.data(|d| d.get_temp::(egui::Id::unique("clipboard.pending-at-tick"))).unwrap_or(false); ctx.data_mut(|d| d.remove::(egui::Id::unique("clipboard.pending-at-tick"))); if !(self.clipboard_publishing.pending || waited) { - // A copy whose formats could not be written: a paste takes its text, not the text the - // clipboard kept ([`Self::unwritten_clipboard_text`]). + // A copy whose formats could not be written: a paste takes its text, or nothing when + // they have none, not the text the clipboard kept ([`Self::unwritten_copy`]). let pasting = textless || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))); - if pasting && let Some(text) = self.unwritten_clipboard_text() { + if pasting && let Some(text) = self.unwritten_copy() { ctx.input_mut(|i| { - for e in &mut i.events { - if let egui::Event::Paste(t) = e { - t.clone_from(&text); + i.events.retain_mut(|e| match (e, &text) { + (egui::Event::Paste(t), Some(text)) => { + t.clone_from(text); + true } - } - if textless { + (egui::Event::Paste(_), None) => false, + _ => true, + }); + if textless && let Some(text) = text { i.events.insert(0, egui::Event::Paste(text)); } }); @@ -474,7 +510,10 @@ impl VectorcraftApp { // A picture or file the host read from the paste. Some(f) if f.mime != TEXT => import_command(&f, center), _ if self.clipboard.readable_any_time() => { - if self.clipboard_publishing.pending || self.clipboard.holds_ours() { + // After a Copy or Cut whose formats could not be written, with nothing copied + // since, what the clipboard still holds is older than the internal clipboard. + let publishing = &mut self.clipboard_publishing; + if publishing.pending || publishing.holds_unwritten(&mut self.clipboard) || self.clipboard.holds_ours() { return Ok(None); } // Art and text load at once, so a paste that waits behind another takes them as it was given; only a @@ -554,12 +593,24 @@ impl VectorcraftApp { } /// The text on the system clipboard once the formats a Copy or Cut is making are written, for a - /// paste into a text field or type. When they could not be written, their text - /// ([`Self::unwritten_clipboard_text`]). + /// paste into a text field or type. When they could not be written, their text, or `None` when + /// they have none ([`Self::unwritten_copy`]). pub(crate) fn written_clipboard_text(&mut self) -> Option { // Only other copies' formats are ahead of them on the worker ([`Self::publish_clipboard`]). background::wait_until(self, |app| !app.clipboard_publishing.pending); - self.unwritten_clipboard_text().or_else(|| self.system_clipboard_text()) + self.unwritten_copy().unwrap_or_else(|| self.system_clipboard_text()) + } + + /// The text a paste from the Edit menu gives a focused text field ([`Self::written_clipboard_text`]): + /// empty when the formats of a Copy or Cut could not be written and have no text, so the field + /// takes nothing and the art is not pasted onto the canvas. `None` when the system clipboard + /// holds no text. + pub(crate) fn field_paste_text(&mut self) -> Option { + background::wait_until(self, |app| !app.clipboard_publishing.pending); + match self.unwritten_copy() { + Some(text) => Some(text.unwrap_or_default()), + None => self.system_clipboard_text(), + } } /// The text on the system clipboard, if any. diff --git a/crates/ui-egui/src/tests/clipboard.rs b/crates/ui-egui/src/tests/clipboard.rs index f54e222b98..240a578ac5 100644 --- a/crates/ui-egui/src/tests/clipboard.rs +++ b/crates/ui-egui/src/tests/clipboard.rs @@ -474,6 +474,49 @@ fn type_paste_drops_a_refused_copy_it_cannot_track() { assert_eq!(paste_at(&mut app, 5), "Own: "); } +/// After a Copy whose formats have no text (On Copy: Include SVG Code off) and could not be +/// written, a paste into type takes nothing, from the menu or a paste event, not the text another +/// app left on the clipboard. A later copy in another app still pastes. +#[test] +fn a_paste_into_type_after_a_refused_textless_copy_takes_nothing() { + use vectorcraft_engine::cmd::clipboard::TEXT; + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board) = super::sysclip::app(); + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": false})); + let rect = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [rect]})); + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + super::sysclip::refuse_writes(&board, true); + run(&mut app, "edit.copy", json!({})); + crate::background::wait_all(&mut app); + super::sysclip::refuse_writes(&board, false); + + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + let text = |app: &VectorcraftApp| { + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() + }; + let place = |app: &mut VectorcraftApp| { + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + }; + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: ", "the menu's Paste"); + place(&mut app); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Old".into())]); + assert_eq!(text(&app), "Own: ", "a paste event"); + + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]); + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: New", "the later copy"); +} + #[test] fn a_paste_event_waiting_on_a_refused_copy_pastes_that_copy() { let _guard = TEST_CLIP_LOCK.lock().unwrap(); diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 2ec147e593..441817c8b8 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -134,6 +134,128 @@ fn right_click_on_empty_canvas_offers_the_view_and_selects_nothing() { assert_eq!(app.session.active().unwrap().doc.art_bounds(), None); } +/// The document point at the centre of the canvas view, where a key request reports itself. +fn view_centre(app: &VectorcraftApp) -> Point { + let view = app.canvas_view().unwrap(); + view.to_doc(view.rect.center()) +} + +/// `key` with `modifiers`, pressed on the focused canvas, then a frame to show the result. +fn menu_key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + frame(app, ctx, vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + frame(app, ctx, vec![]); +} + +/// Rectangle A, selected with a click (which also gives the canvas the keyboard focus), and an unselected +/// rectangle B under the view's centre with a locked rectangle over it. +fn selection_away_from_the_centre(app: &mut VectorcraftApp, ctx: &egui::Context) -> (NodeId, NodeId) { + let a = rect(app, 0.0, 0.0); + frame(app, ctx, vec![]); + let c = view_centre(app); + let b = rect(app, c.x - 50.0, c.y - 50.0); + let locked = rect(app, c.x - 25.0, c.y - 25.0); + app.run("layer.setProps", json!({"ids": [locked.0], "locked": true})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let p = screen(app, 50.0, 50.0); + click(app, ctx, p, PointerButton::Primary); + assert_eq!(app.session.active().unwrap().selection.objects, [a]); + (a, b) +} + +/// Asserts the menu opened for `a` as selected, at a point over it, without what lies under the view's centre. +fn opened_for_the_selection(app: &VectorcraftApp, a: NodeId) { + assert_eq!(app.session.active().unwrap().selection.objects, [a], "a key request keeps the selection"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let over_a = Rect::from_two_pos(screen(app, 0.0, 0.0), screen(app, 100.0, 100.0)); + assert!(over_a.contains(at), "the menu opens at the selection: {at:?} in {over_a:?}"); + assert!(has(app, "Arrange") && has_command(app, "object.arrange.bringToFront"), "{:?}", labels(app)); + assert!(app.ui.context_locked.is_none() && !has(app, "Unlock"), "nothing under the view's centre is measured"); +} + +#[test] +fn shift_f10_opens_the_menu_for_the_selection_without_changing_it() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (a, _) = selection_away_from_the_centre(&mut app, &ctx); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + opened_for_the_selection(&app, a); +} + +#[cfg(not(target_os = "macos"))] +#[test] +fn menu_key_opens_the_menu_for_the_selection_without_changing_it() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (a, _) = selection_away_from_the_centre(&mut app, &ctx); + menu_key(&mut app, &ctx, egui::Key::Menu, egui::Modifiers::NONE); + opened_for_the_selection(&app, a); +} + +/// With nothing selected, Shift+F10 opens the menu at the view's centre and selects nothing, even over an object. +#[test] +fn shift_f10_with_nothing_selected_opens_the_menu_at_the_view_centre() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let c = view_centre(&app); + rect(&mut app, c.x - 50.0, c.y - 50.0); + app.run("select.none", json!({})).unwrap(); + // A click on the empty artboard gives the canvas the focus and keeps the selection empty. + let p = screen(&app, 380.0, 280.0); + click(&mut app, &ctx, p, PointerButton::Primary); + assert!(app.session.active().unwrap().selection.objects.is_empty()); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "the object under the view's centre stays unselected"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let centre = app.canvas_view().unwrap().rect.center(); + assert!(at.distance(centre) < 0.5, "{at:?} at {centre:?}"); + assert!(has(&app, "Select All") && !has(&app, "Arrange"), "{:?}", labels(&app)); +} + +/// With the Artboard tool, Shift+F10 opens the menu for the selected artboard, at it, and selects no other artboard; +/// the menu's Paste would put artboards on it. +#[test] +fn shift_f10_with_the_artboard_tool_keeps_the_selected_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + crate::menus::invoke(&mut app, "view.fitAll", json!({})); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + let boards: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let centre = view_centre(&app); + let away = boards.iter().position(|r| !r.contains(centre)).unwrap(); + app.select_tool("artboard"); + // A click on the artboard selects it and gives the canvas the focus. + let c = boards[away].center(); + let p = screen(&app, c.x, c.y); + click(&mut app, &ctx, p, PointerButton::Primary); + assert_eq!(crate::panels::artboards::picked(&app, boards.len()), [away]); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + assert_eq!(crate::panels::artboards::picked(&app, boards.len()), [away], "a key request keeps the selected artboard"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let on_board = Rect::from_two_pos(screen(&app, boards[away].x0, boards[away].y0), screen(&app, boards[away].x1, boards[away].y1)); + assert!(on_board.contains(at), "the menu opens at the selected artboard: {at:?} in {on_board:?}"); + let pasted_at = app.ui.context_artboards.as_ref().map(|f| f.at).expect("the menu's artboard facts"); + assert!(boards[away].contains(pasted_at), "{pasted_at:?} on {:?}", boards[away]); +} + +/// A right-click on an object that is not selected still selects it, with another object selected before. +#[test] +fn right_click_still_selects_the_object_under_the_pointer() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (_, b) = selection_away_from_the_centre(&mut app, &ctx); + // Inside B, outside the locked rectangle over its middle. + let c = view_centre(&app); + let p = screen(&app, c.x - 40.0, c.y - 40.0); + click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [b]); + assert!(app.ui.context_menu_at.is_some_and(|at| at.distance(p) < 0.5), "the menu opens at the pointer"); +} + /// A right-click over a locked object adds an Unlock submenu that lists the object by its name; once /// the menu is closed, the menu lists no Unlock items. #[test] diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 8a13fbda07..f1f6bcd09c 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -63,6 +63,57 @@ fn settings_lists_every_preferences_page() { assert_eq!(crate::prefs_dialog::page(&m.app), Some("Units")); } +/// The default shortcut of command `id`, as the shortcut editor lists it. +fn default_chord(id: &str) -> Option { + crate::shortcut_editor::default_command_shortcut(id).and_then(crate::keymap::stored::parse_vc) +} + +/// The Settings › General… item of `bar`. +fn general(bar: &MenuBar) -> &Item { + let page = PREF_CATEGORIES[0]; + bar.items().into_iter().find(|it| it.command.id == "edit.preferences" && it.command.params["category"] == page).expect("Settings › General…") +} + +/// The menu bar hands every item its command's shortcut, so Save, Open, Undo and Group show their keys and AppKit +/// takes them as key equivalents. +#[test] +fn native_items_carry_their_commands_shortcuts() { + let m = Mac::new(true); + let bar = m.fake.last(); + for id in ["file.save", "file.open", "edit.undo", "object.group"] { + let chord = default_chord(id); + assert!(chord.is_some(), "{id} has a default shortcut"); + assert_eq!(find(&bar, id).shortcut, chord, "{id}"); + } +} + +/// A command bound to another key shows that key in the menu bar, and its old key is no longer the item's. +#[test] +fn a_rebound_command_shows_its_new_key_in_the_menu_bar() { + let mut m = Mac::new(true); + let old = default_chord("object.group"); + m.app.run("shortcuts.set", json!({"id": "object.group", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = find(&m.fake.last(), "object.group").shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + +/// Settings › General… carries Preferences' shortcut as the user set it, not the default one. +#[test] +fn settings_general_follows_a_rebound_preferences() { + let mut m = Mac::new(true); + let old = default_chord("edit.preferences"); + assert_eq!(general(&m.fake.last()).shortcut, old); + m.app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = general(&m.fake.last()).shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + /// A native menu can't turn a plain item into a check item in place: the app's read of the menus /// is guarded by a state key, and these tests count the reads through a fake backend. /// diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0b36cec615..71977801c5 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -6,6 +6,7 @@ use std::{ cell::{RefCell, RefMut}, + collections::HashMap, rc::Rc, }; @@ -13,7 +14,8 @@ use craft::behavior::PartRef; use craft::ui::runtime::frame::take_output; use craft::ui::testing::pointer::part_rect_of_node; use craft::ui::testing::{Fixture, Target}; -use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, vec2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, pos2, vec2}; +use serde_json::json; use crate::VectorcraftApp; @@ -259,6 +261,21 @@ impl Panel { /// A right click on the control named `name`. pub(crate) fn secondary_click(&mut self, name: &str) { let at = self.find(name).center(); + self.secondary_click_at(at); + } + + /// Right-clicks the zero-based control of `role`, including rows with identical names. + pub(crate) fn secondary_click_nth(&mut self, role: craft::ui::contract::Role, index: usize) { + self.frame(); + let at = self.look_nth(role, index).center(); + self.secondary_click_at(at); + } + + fn look_nth(&self, role: craft::ui::contract::Role, index: usize) -> Target { + self.fixture.by_role(role).into_iter().nth(index).unwrap_or_else(|| panic!("no {role:?} at {index} in {:?}", self.names())) + } + + fn secondary_click_at(&mut self, at: Pos2) { let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; self.frame_with(vec![Event::PointerMoved(at)]); self.frame_with(vec![button(true)]); @@ -360,4 +377,109 @@ impl Panel { pub(crate) fn focused(&self, name: &str) -> bool { self.fixture.tree().focused_key() == self.look(name).node } + + /// Whether the zero-based control of `role` has focus, including rows with identical names. + pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool { + self.fixture.tree().focused_key() == self.look_nth(role, index).node + } +} + +/// Where [`floated`] shows a panel in the app window. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Place { + /// Docked in its column. + Docked, + /// Floating at x 520, this many points wide. + Floating(f32), +} + +/// A panel as one frame of the whole app window drew it. +pub(crate) struct Shown { + /// The panel's body. + pub(crate) body: Rect, + /// The name and rect of every named node in the body. + pub(crate) nodes: Vec<(String, Rect)>, + /// Each catalog string asked for, with the text the panel's language shows for it. + names: Vec<(String, String)>, +} + +impl Shown { + /// The rects of the nodes named `name` (a catalog string asked for). + pub(crate) fn rects(&self, name: &str) -> Vec { + let shown = self.names.iter().find(|(asked, _)| asked == name).map_or(name, |(_, shown)| shown.as_str()); + let found: Vec = self.nodes.iter().filter(|(label, _)| label == shown).map(|(_, r)| *r).collect(); + assert!(!found.is_empty(), "the panel shows no {shown:?}"); + found + } + + /// The nodes of `nodes` that reach past either side of the body, each with its rect. + pub(crate) fn past(&self, nodes: impl IntoIterator) -> Vec { + let outside = |r: &Rect| r.left() < self.body.left() - 0.5 || r.right() > self.body.right() + 0.5; + nodes.into_iter().filter(|(_, r)| outside(r)).map(|(name, r)| format!("{name} at {r:?}")).collect() + } + + /// The nodes named each of `names` (catalog strings asked for) that reach past either side of the body, each with + /// its rect. + pub(crate) fn past_named(&self, names: &[&str]) -> Vec { + self.past(names.iter().flat_map(|name| self.rects(name).into_iter().map(|r| ((*name).to_owned(), r)))) + } + + /// The vertical middles of the nodes named `names`, in order. + pub(crate) fn middles(&self, names: &[&str]) -> Vec { + names.iter().flat_map(|name| self.rects(name)).map(|r| r.center().y).collect() + } +} + +/// Panel `panel` of `app` shown at `place` in the whole app window (1440 by 900 pt), drawn in `lang`, with the catalog +/// strings `names` as `lang` shows them. The test sets `app` up before the call. A floating panel's body is the tab +/// panel at the left edge the float asked for; a docked panel's body is the tab panel that shows every one of `names`. +pub(crate) fn floated(mut app: VectorcraftApp, panel: &str, lang: &str, place: Place, names: &[&str]) -> Shown { + use egui::accesskit::{Node, NodeId, Role}; + const AT: f32 = 520.0; + app.session.prefs.interface_language = lang.into(); + app.run("window.panel", json!({ "panel": panel })).unwrap(); + match place { + Place::Docked => app.run("window.panel.dock", json!({ "panel": panel })).unwrap(), + Place::Floating(width) => app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(), + }; + app.run("window.panel.activate", json!({ "panel": panel })).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)); + let mut nodes: Vec<(NodeId, Node)> = Vec::new(); + for at in 1..=8 { + let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; + let out = crate::testing::app_frame(&mut app, &ctx, input); + nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); + } + // The frames set the language from the preference; the names are looked up in it before English is put back. + let names: Vec<(String, String)> = names.iter().map(|name| ((*name).to_owned(), crate::i18n::t(name).to_owned())).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let rect = |node: &Node| node.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))); + let by_id: HashMap = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let under = |root: NodeId| { + let mut found = Vec::new(); + let mut todo = vec![root]; + while let Some(id) = todo.pop() { + let Some(node) = by_id.get(&id) else { continue }; + if let (Some(label), Some(r)) = (node.label(), rect(node)) { + found.push((label.to_owned(), r)); + } + todo.extend(node.children().iter().copied()); + } + found + }; + let mut bodies = nodes.iter().filter(|(_, n)| n.role() == Role::TabPanel).filter_map(|(id, n)| Some((rect(n)?, under(*id)))); + let found = match place { + Place::Docked => { + assert!(!names.is_empty(), "a docked panel is found by the names it shows"); + bodies.find(|(_, named)| names.iter().all(|(_, shown)| named.iter().any(|(label, _)| label == shown))) + } + Place::Floating(_) => bodies.find(|(r, _)| (r.left() - AT).abs() < 1.0), + }; + let (body, nodes) = found.unwrap_or_else(|| panic!("no {panel} panel at {place:?} in {lang}")); + if let Place::Floating(width) = place { + assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for"); + } + Shown { body, nodes, names } } diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index ed161e797f..ef910a800e 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -201,6 +201,69 @@ fn a_heavy_filter_s_result_needs_the_document_as_it_was() { assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); } +/// A heavy filter that writes type, run while typing is in progress with Real-time Drawing off: +/// the typing is kept before the run starts, so the plug-in is given the typed text and its result +/// applies once it is done. A run that can't start keeps no typing. Typing started with Real-time +/// Drawing off while it runs isn't in what it was given: nothing changes, and the status bar says +/// to run it again. +#[test] +fn a_heavy_filter_is_given_the_typing_in_progress() { + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_engine::ViewInfo; + use vectorcraft_engine::tools::{PointerEvent, PointerKind}; + let id = "test.ui.heavy.typing"; + let plain = |app: &VectorcraftApp, t: NodeId| match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + // Clicks into the end of `t` with the Type tool and types `text`. + let type_into = |app: &mut VectorcraftApp, t: NodeId, text: &str| { + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(text, v).unwrap(); + }; + let mut app = app(); + app.session.prefs.real_time_drawing = false; + let t = NodeId(app.run("text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20})).unwrap()["id"].as_u64().unwrap()); + let style = match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","budget":"heavy","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ); + // It adds "!" to the text it is given: "AB" or, given only "A", "A". + let src = tpl::when_given_else(&manifest, tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!")); + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + app.run("plugin.install", json!({"dataBase64": data, "allowHeavy": true, "grant": ["doc.read", "doc.write"]})).unwrap(); + type_into(&mut app, t, "B"); + assert_eq!(plain(&app, t), "A", "Real-time Drawing off leaves the typing out of the document"); + // A run that can't start leaves the typing in progress, out of the document. + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(plugin_runs::start(&mut app, json!({"id": "test.ui.heavy.missing", "ids": [t.0]})).is_err()); + assert_eq!(plain(&app, t), "A", "a run that can't start keeps no typing"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(app.session.in_interaction(), "the typing is still in progress"); + let p = json!({"id": id, "ids": [t.0]}); + assert_eq!(plugin_runs::start(&mut app, p.clone()).unwrap()["background"], true); + assert_eq!(plain(&app, t), "AB", "the typing is kept before the run starts"); + finish_runs(&mut app); + assert_eq!(plain(&app, t), "AB!", "{}", app.ui.status); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + // Typing started while it runs, Real-time Drawing off. + plugin_runs::start(&mut app, p).unwrap(); + type_into(&mut app, t, "C"); + let doc = app.session.doc().unwrap().doc.clone(); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().doc, doc, "nothing changed"); + assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); +} + /// The progress window is the run's: headed by it, with Cancel and Continue in Background; Cancel /// stops the run, which changes nothing, and the window goes. #[test] diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index f904500cdf..b56303f960 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -276,6 +276,25 @@ fn the_dialog_reduces_previews_and_applies_as_one_undo_step() { assert_eq!(colors(&mut r.app()), 5); } +/// Enter in the field that has the focus is OK: the color group is made with the name typed, and the dialog closes. +#[test] +fn enter_in_a_field_is_ok() { + let mut r = open(app(), json!({"colors": ["#ff8000", "#0080ff"]})); + r.settled(); + r.set("groupName", json!("Enter Group")).unwrap(); + r.settled(); + r.click_label("Color Group:"); + r.settled(); + assert!(r.focused().is_some(), "a field of the dialog has the focus"); + let groups = r.app().session.doc().unwrap().doc.swatch_groups.len(); + key(&mut r, Key::Enter); + assert!(!r.is_open(), "Enter closes Recolor Artwork"); + let app = r.app(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), groups + 1, "Enter makes the color group, as OK does"); + assert_eq!(doc.swatch_groups.last().map(|g| g.name.as_str()), Some("Enter Group")); +} + #[test] fn presets_open_colour_jobs_and_libraries_and_both_tabs_draw() { let mut app = app(); @@ -1318,6 +1337,37 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { } } +/// A Color Picker opened over the dialog, on its color models, has the Color Swatches button that +/// switches it to the swatches. +#[test] +fn a_picker_over_the_dialog_offers_the_color_swatches_view() { + let mut r = edit(&["#ff0000", "#0000ff"]); + let at = marker(&r, 0); + right_click(&mut r, at); + tap(&mut r, "Color Picker"); + assert!(picker(&r).is_some(), "the marker's Color Picker opens the picker"); + assert!(has(&r, "Color Swatches"), "the picker has the Color Swatches button"); + tap(&mut r, "Color Swatches"); + assert!(has(&r, "Color Models"), "the button switches the picker to its swatches"); +} + +/// Pick from Swatches opens the picker on its swatches, showing the library that Limit to Library +/// limits the rows to. +#[test] +fn pick_from_swatches_shows_the_limit_to_library_library() { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let lib = library_of(&mut app, &[json!({"name": "Lib Teal", "color": "#008080"}), json!({"name": "Lib Plum", "color": "#8e4585"})]); + let mut r = assign(app, json!({"library": lib})); + assert_eq!(field(&r, "limitTo"), json!(lib)); + let at = rect(&r, "New 1").center(); + right_click(&mut r, at); + tap(&mut r, "Pick from Swatches"); + assert!(picker(&r).is_some(), "Pick from Swatches opens the Color Picker"); + assert!(has(&r, "Color Models"), "the picker shows its swatches, with the button back to the color models"); + assert!(has(&r, "Lib Teal") && has(&r, "Lib Plum"), "the swatches are the Limit to Library library's"); +} + /// Undo Changes and Redo Changes step back and forward through the dialog's own color edits, and /// the art previews each step; the document's undo history is unchanged until OK, which records /// one step. Both buttons start disabled, and a new edit after Undo Changes leaves nothing to redo. diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..7e90dba636 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -77,8 +77,8 @@ pub(super) fn open_blocker(app: &VectorcraftApp) { } /// One pass of the dialog host with `events`; a key pressed in it is let go in a second pass, as a -/// person lets go of it. -pub(super) fn frame(app: &VectorcraftApp, events: Vec) { +/// person lets go of it. Returns the last pass's output. +pub(super) fn frame(app: &VectorcraftApp, events: Vec) -> egui::FullOutput { let ctx = app.ui_ctx.clone().unwrap(); let dialogs = app.dialogs().unwrap(); let released: Vec = events @@ -92,10 +92,12 @@ pub(super) fn frame(app: &VectorcraftApp, events: Vec) { .collect(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let pressed = !released.is_empty(); + let mut last = egui::FullOutput::default(); for events in std::iter::once(events).chain(pressed.then_some(released)) { - let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); - out.textures_delta.clear(); + last = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); + last.textures_delta.clear(); } + last } pub(super) fn key(k: egui::Key) -> egui::Event { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4022cb7c65..b1cdf7cf95 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -103,6 +103,46 @@ fn a_run_goes_frame_by_frame_and_is_one_undo_step() { let _ = std::fs::remove_dir_all(&dir); } +/// The warning automation asked while confined to a folder: Run runs the script as automation's, +/// with that folder still the only place it may read. +#[test] +fn the_warning_runs_the_script_under_the_access_it_was_asked_with() { + let mut app = app(); + let (inside, outside) = (folder("scope-in"), folder("scope-out")); + let path = outside.join("draw.js"); + std::fs::write(&path, DRAW).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| { + menus::run_ui_command(app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + }) + }); + assert!(confirm(&mut app, KIND)); + assert!(app.ui.status.contains("outside the read root"), "the script outside the folder is refused: {}", app.ui.status); + assert!(!app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&inside); + let _ = std::fs::remove_dir_all(&outside); +} + +/// The warning a person asked, answered by automation confined to a folder: the script runs with +/// that folder still the only place it may read. +#[test] +fn the_warning_answered_under_narrower_access_keeps_it() { + let mut app = app(); + let (inside, outside) = (folder("narrow-in"), folder("narrow-out")); + let path = outside.join("draw.js"); + std::fs::write(&path, DRAW).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + assert!(vectorcraft_engine::file_access::confine(roots.as_ref(), || confirm(&mut app, KIND))); + assert!(app.ui.status.contains("outside the read root"), "the script outside the folder is refused: {}", app.ui.status); + assert!(!app.session.script_running()); + let _ = std::fs::remove_dir_all(&inside); + let _ = std::fs::remove_dir_all(&outside); +} + #[test] fn do_not_show_again_is_remembered_and_the_script_still_runs() { let mut app = app(); @@ -465,3 +505,39 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { cancel(&mut app, PICKER_KIND); finish(&mut app); } + +/// With two files picked, the file dialog lists them in a scrolled group named Picked files. +#[test] +fn a_scripts_file_dialog_lists_several_picked_files_in_a_named_group() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let given = vec!["/picked/a.txt".to_string(), "/picked/b.txt".to_string()]; + script_run::with_host(&app, |host, _| host.get_mut::().map(|d| d.add(given, true, false))).unwrap(); + frame(&app, vec![]); + let out = frame(&app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let groups: Vec<_> = + update.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Group).filter_map(|(_, node)| node.label()).collect(); + assert!(groups.contains(&"Picked files"), "a group named Picked files: {groups:?}"); + let nodes: std::collections::HashMap<_, _> = update.nodes.iter().map(|(id, node)| (*id, node)).collect(); + let (_, group) = update + .nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::Group && node.label() == Some("Picked files")) + .expect("the Picked files group"); + let mut texts = Vec::new(); + let mut pending = group.children().to_vec(); + while let Some(id) = pending.pop() { + if let Some(node) = nodes.get(&id) { + texts.extend(node.label().into_iter().chain(node.value()).map(str::to_owned)); + pending.extend_from_slice(node.children()); + } + } + for path in ["/picked/a.txt", "/picked/b.txt"] { + assert!(texts.iter().any(|text| text == path), "{path} is inside the Picked files group: {texts:?}"); + } + cancel(&mut app, PICKER_KIND); + finish(&mut app); +} diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index 9c20603db8..ed97ffcdb7 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -380,6 +380,79 @@ fn copy_and_cut_copy_the_text_selected_in_a_panel_label() { assert!(copied(&after).iter().any(|t| t.starts_with(">| frames.into_iter().flat_map(|events| copied(&a.frame(events))).collect::>(); + let (status, sets) = (a.app.ui.status.clone(), a.app.ui.status_sets); + let clicked = copies(&mut a, vec![vec![Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false)], vec![]]); + assert_eq!(clicked, [length], "a click copies the value, once"); + assert!(a.app.ui.status_sets != sets && a.app.ui.status != status, "the status bar says it was copied"); + assert_eq!(a.selected(), 1, "the art stays selected"); + assert!(a.app.session.clipboard.is_empty(), "no art copied"); + a.time += 1.0; + let twice = copies(&mut a, vec![vec![click(at, true)], vec![click(at, false)], vec![click(at, true)], vec![click(at, false)], vec![]]); + assert_eq!(twice, [length], "a double click copies the value once"); + a.time += 1.0; + let (from, to) = (text_rect(&out, length).left_center() + vec2(1.0, 0.0), text_rect(&out, length).right_center() - vec2(1.0, 0.0)); + let mut drag = vec![vec![Event::PointerMoved(from)], vec![click(from, true)]]; + drag.extend((1..=4).map(|k| vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)])); + drag.extend([vec![click(to, false)], vec![]]); + assert!(copies(&mut a, drag).is_empty(), "a drag selects and copies nothing"); + a.time += 1.0; + let shift = Event::ModifiersChanged(Modifiers::SHIFT); + let shift_click = + |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }; + let extended = copies( + &mut a, + vec![ + vec![shift.clone(), Event::PointerMoved(at)], + vec![shift_click(at, true)], + vec![shift_click(at, false)], + vec![Event::ModifiersChanged(Modifiers::NONE)], + ], + ); + assert!(extended.is_empty(), "a Shift-click copies nothing"); + a.time += 1.0; + // Shift let go in the frame of the release: the click was still a Shift-click. + let let_go = copies( + &mut a, + vec![ + vec![shift, Event::PointerMoved(at)], + vec![shift_click(at, true)], + vec![shift_click(at, false), Event::ModifiersChanged(Modifiers::NONE)], + vec![], + ], + ); + assert!(let_go.is_empty(), "a Shift-click copies nothing when Shift is let go in the same frame"); + a.time += 1.0; + // Released on the length, then moved onto the Paths count in the same frame. + let there = text_rect(&out, "2").center(); + let moved = + copies(&mut a, vec![vec![Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false), Event::PointerMoved(there)], vec![]]); + assert_eq!(moved, [length], "a click copies the value it was released on, not the one the pointer moved to"); + a.time += 1.0; + // A click on the Paths count, then a drag across the length, in one frame. + let (from, to) = (text_rect(&out, length).left_center() + vec2(1.0, 0.0), text_rect(&out, length).right_center() - vec2(1.0, 0.0)); + let both = copies( + &mut a, + vec![ + vec![Event::PointerMoved(there)], + vec![click(there, true), click(there, false), Event::PointerMoved(from), click(from, true), Event::PointerMoved(to), click(to, false)], + vec![], + ], + ); + assert!(!both.iter().any(|t| t == length), "a drag after a click in the same frame does not copy the dragged value"); +} + /// Drag across a label in a window of its own (a floating panel's), selecting its text there. The /// main window's labels then copy nothing on Copy or Cut, which run on the art a pass later. fn select_label_text_in_another_window(a: &mut App) { diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index baa21396ed..38efb55e1f 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -398,6 +398,90 @@ fn our_own_copy_pastes_the_lossless_internal_clipboard() { assert!(matches!(pasted(&app)[0].kind, NodeKind::Path { .. })); } +/// SVG markup of three closed paths, a group of two more and a compound path with a hole: five +/// objects. +fn closed_paths_svg() -> String { + let mut svg = String::from(r#""#); + for x in [10, 20, 30] { + svg.push_str(&format!(r##""##)); + } + svg.push_str(r#""#); + svg.push_str(r#""#); + svg +} + +/// Paste the objects of [`closed_paths_svg`] from another app and select them all → their count. +fn paste_closed_paths(app: &mut VectorcraftApp, board: &Arc>) -> usize { + copy_elsewhere(board, vec![(SVG, closed_paths_svg().into_bytes())]); + run(app, "edit.paste", json!({})); + run(app, "select.all", json!({})); + let objects = count(app); + assert_eq!(app.session.active().unwrap().selection.objects.len(), objects); + objects +} + +/// A Copy or Cut whose formats can't be written to the system clipboard (another app holds it +/// open, or refuses the write) stays what every Paste command takes while nothing else is copied, +/// also when its formats have no text; the clipboard's older text does not replace it, and a paste +/// into text takes the copy's text, or nothing. A later copy in another app still wins. A later copy is +/// noticed only when it changes the clipboard's text, so when the clipboard held only a picture, +/// or could not be read (another app holds it open), Paste takes what the clipboard holds. +#[test] +fn a_copy_the_system_clipboard_refused_still_pastes_the_copied_art() { + type Fail = fn(&Arc>, bool); + // Case, Copy or Cut, how the write fails, On Copy: Include SVG Code, the other app's copy + // before it is a picture, Paste takes the copied art. + let cases: [(&str, &str, Fail, bool, bool, bool); 5] = [ + ("refused", "edit.cut", refuse_writes, true, false, true), + ("refused, no text", "edit.cut", refuse_writes, false, false, true), + ("refused copy", "edit.copy", refuse_writes, true, false, true), + ("locked", "edit.cut", lock, true, false, false), + ("refused, over a picture", "edit.cut", refuse_writes, true, true, false), + ]; + let pastes = + ["edit.paste", "edit.pasteInFront", "edit.pasteInBack", "edit.pasteInPlace", "edit.pasteOnAllArtboards", "edit.pasteWithoutFormatting"]; + for (case, op, fail, svg_text, over_picture, kept) in cases { + let (mut app, board) = app(); + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": svg_text})); + let objects = paste_closed_paths(&mut app, &board); + if over_picture { + copy_elsewhere(&board, vec![(PNG, blue_png())]); + } else { + copy_elsewhere(&board, vec![(TEXT, b"Words another app copied".to_vec())]); + } + fail(&board, true); + run(&mut app, op, json!({})); + background::wait_all(&mut app); + fail(&board, false); + assert!(app.ui.status.starts_with("Couldn't copy to the system clipboard"), "{case}: {}", app.ui.status); + let left = if op == "edit.cut" { 0 } else { objects }; + assert_eq!(count(&app), left, "{case}"); + if !kept { + run(&mut app, "edit.paste", json!({})); + match &pasted(&app)[0].kind { + NodeKind::Image { .. } => assert!(over_picture, "{case}: the picture"), + NodeKind::Text(t) => assert_eq!((over_picture, t.plain_text().as_str()), (false, "Words another app copied"), "{case}"), + kind => panic!("{case}: not what the clipboard holds: {kind:?}"), + } + continue; + } + let text = app.written_clipboard_text(); + assert_eq!(text.is_some(), svg_text, "{case}: a paste into text takes the copy's text, or nothing: {text:?}"); + assert!(text.is_none_or(|t| t.contains(" Self { + self.tools_steps = 2; + self + } +} + /// The id of a built-in workspace: its lower-case name with dashes. fn builtin_id(name: &str) -> String { name.to_lowercase().replace(' ', "-") @@ -226,7 +236,7 @@ pub fn builtins() -> Vec { let w = |name: &'static str, fronts: &'static [&'static str], f: &dyn Fn(&mut WorkspaceRecord)| { let mut record = WorkspaceRecord::default(); f(&mut record); - Builtin { name, fronts, record } + Builtin { name, fronts, tools_steps: 1, record } }; vec![ w(ESSENTIALS, &[], &|_| {}), @@ -248,7 +258,8 @@ pub fn builtins() -> Vec { w("Painting", &["brushes"], &|x| { x.control_bar = true; x.toolbar_advanced = true; - }), + }) + .double_tools(), w("Printing and Proofing", &["info"], &|x| { x.control_bar = true; x.rulers = true; @@ -279,7 +290,10 @@ pub fn builtins() -> Vec { /// The built-ins as the framework's named workspaces. fn builtin_set() -> Vec> { - builtins().into_iter().map(|b| NamedWorkspace::new(builtin_id(b.name), b.name, crate::panel_docking::default_workspace(b.fronts))).collect() + builtins() + .into_iter() + .map(|b| NamedWorkspace::new(builtin_id(b.name), b.name, crate::panel_docking::builtin_workspace(b.fronts, b.tools_steps))) + .collect() } /// The chrome the set stores beside a layout, from `record`. Never read back: the record is the truth. @@ -290,11 +304,23 @@ fn chrome_of(record: &WorkspaceRecord) -> WorkspaceChrome { chrome } +/// Whether [`sync_touch_workspace`] with `touch_screen` switches to the Touch workspace. +pub fn enters_touch(app: &VectorcraftApp, touch_screen: bool) -> bool { + app.session.prefs.touch_workspace && touch_screen && !is_current(&app.ui, TOUCH) +} + +/// Whether the current workspace was saved with the Contextual Task Bar on. +pub(crate) fn saved_task_bar(ui: &UiState) -> bool { + saved_record(&ui.workspaces, &ui.workspaces.set.current).task_bar +} + /// Preferences › Devices › Enable Touch Workspace (#394): on, a touch screen switches to the Touch /// workspace; off, or when no touch screen is reported, the workspace before that switch is /// restored if Touch was entered automatically. Each switch keeps the layout it leaves and brings /// back the one it returns to as it was left, as Window › Workspace does. pub fn sync_touch_workspace(app: &mut VectorcraftApp, touch_screen: bool) { + // A pending `prefs.reset` applies to the workspace it was run in. + crate::prefs_dialog::apply_prefs_resets(app); let auto = app.session.prefs.touch_workspace && touch_screen; if auto { if !is_current(&app.ui, TOUCH) { @@ -745,6 +771,36 @@ mod tests { } } + /// Painting lays the Tools panel out in two columns and Window › Toolbars › Double Column reads + /// checked; every other built-in workspace has one column. Switching back to Essentials brings + /// back its own column count, as it was left, and Reset Painting gives two columns again. + #[test] + fn painting_shows_tools_in_two_columns_and_essentials_keeps_its_own() { + let steps = |app: &VectorcraftApp| { + crate::panel_docking::column_of(crate::panel_docking::layout_of(&app.ui), crate::toolbar::TOOLS).and_then(|(_, column)| column.steps) + }; + let double = |app: &VectorcraftApp| crate::menus::checked(app, "window.toolbarColumns", &json!({})); + let mut app = app(); + assert_eq!((steps(&app), double(&app)), (Some(1), Some(false)), "Essentials starts with one column"); + for b in builtins() { + switch(&mut app, b.name).unwrap(); + let painting = b.name == "Painting"; + assert_eq!(steps(&app), Some(if painting { 2 } else { 1 }), "{}", b.name); + assert_eq!(double(&app), Some(painting), "Double Column in {}", b.name); + } + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!((steps(&app), double(&app)), (Some(1), Some(false)), "Essentials has one column again"); + app.run("window.toolbarColumns", json!({"double": true})).unwrap(); + switch(&mut app, "Painting").unwrap(); + app.run("window.toolbarColumns", json!({"double": false})).unwrap(); + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!(double(&app), Some(true), "Essentials keeps the two columns it was left with"); + switch(&mut app, "Painting").unwrap(); + assert_eq!(double(&app), Some(false), "Painting keeps the one column it was left with"); + reset(&mut app); + assert_eq!((steps(&app), double(&app)), (Some(2), Some(true)), "Reset Painting gives two columns again"); + } + /// A file saved before `WorkspaceSet` names workspaces in any case: the layout remembered under /// another spelling belongs to the saved workspace, once; a name no workspace has is dropped, /// and a saved name equal to a built-in's is refused and reported. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 220bdf2e45..f3b8a18d85 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -494,9 +494,8 @@ button (Add Tool…) opens a menu of every tool under the drawer's headings: a c there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). -`window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and -`window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its -lane does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: +`window.toolbar.dock {name, side?, order?}` docks a toolbar as a column of the dock along the window's left or right +edge, and `window.toolbar.float {name, x?, y?}` floats it again; dragging its title bar does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them. @@ -817,7 +816,9 @@ lists to the system clipboard (once they are written, the status bar shows the f another message has replaced the Copy or Cut's meanwhile), and every Paste command first loads what another app copied (`clipboard.importSvg`, `importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error -and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no +and pastes nothing. After a Copy or Cut whose formats could not be written to the system clipboard, every Paste +command takes the internal clipboard instead until another app copies something (only while the clipboard held text +that could be read when the write failed). Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no Paste event for it). Screenshots paste on every platform: Windows reads `PNG`, else `CF_DIBV5`/`CF_DIB`, macOS the pasteboard's PNG or TIFF, Linux `image/png`, and the web the picture the browser's paste event carries (#457). In the desktop app a Paste from the menus or the keys (`ui.key`) decodes a bitmap off the UI thread: `ui.inspect` lists diff --git a/docs/gaps.md b/docs/gaps.md index 41d263851f..8b19b60ddc 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -12,6 +12,12 @@ ## Feature submission evidence +History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. + +OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. + +- **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -24,7 +30,7 @@ Draft enhancement #5804: Preferences › File Handling can select a raster edito > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. -**Feature evidence last updated:** 2026-11-20. +**Feature evidence last updated:** 2026-11-21. Properties panel Quick Actions include contextual text actions when live type is selected: Create Outlines (`type.createOutlines`), Retype (`ui.retype`), and Find and Replace… (`ui.findAndReplace`), while retaining standard object actions (Arrange: Bring to Front, Lock) and suppressing path-only actions (Offset Path, Simplify) for type-only selections. Evidence: `panels::properties::tests::type_quick_actions_show_text_commands_and_create_outlines` in `crates/ui-egui/src/panels/properties/tests.rs`. Scores and estimates unchanged. @@ -60,6 +66,11 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | +| 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. | +| 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. | +| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); headless tests in crates/ui-egui/src/panels/properties/tests.rs; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | @@ -526,6 +537,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Implemented (2026-11-20):** History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. + +- **Implemented and tested (2026-11-21):** OpenType panel feature rows have an item context menu. A secondary click keeps the text selection and offers Turn Off when the feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step; a checkbox click stays a toggle. The Stylistic Sets button and the East Asian menu items are unchanged. Headless regression coverage: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. + - **Implemented (2026-11-20):** Asset Export tiles have item context menus: Export and Remove act on the asset selection (plural labels for multiple assets), Rename opens the clicked tile's inline field, Select Artwork on Canvas selects that tile's source nodes, and Add Selected Artwork as One Asset / Multiple Assets are enabled with canvas selection. A right-click selects an unselected tile, clearing the previous asset selection, and preserves a multi-selection when the tile is already selected. Export reuses the raster/3D export path; Remove is one undo step and keeps the artwork. Headless regression coverage: `crates/ui-egui/src/panels/tests_asset_export.rs`. Other G12 panel gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-20):** Appearance panel row context menus: right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Headless regression coverage: `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. @@ -992,6 +1007,9 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. | | 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index f7c47826fd..e2d8dabca6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1222,6 +1222,8 @@ the art below it inside the object, groups and layer around it, the object's row the background when `against` or `opacity` is given; inside an object, group or layer that isolates its blending, the modes blend only with the art it holds); `opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque. +While the active tool paints with the proxy's color (the Live Paint Bucket, the Shape Builder's fill), that color is +drawn the same way, and the selected objects' opacities and blend modes do not apply. `against` takes a color, or `"below"` (the default, also for `null`): the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it (locked art, opacity, blend modes and images included; template layers and guides left out, as exports leave them out; the artboard's white where nothing @@ -1485,6 +1487,13 @@ a larger file. A lossy file keeps the alpha exactly when some pixels are not opa that is not a whole number, is refused; a lossless file ignores `quality`. Export for Screens takes both in a WebP row or in `settings.webp`. +GIF and PNG-8 exports take Save for Web's `transparencyDither` (`none`, the default, `diffusion`, `pattern` or `noise`) +and `transparencyDitherAmount` (0 to 100, default 100) next to `dither` and `ditherAmount`, and they change the file as +in `document.exportForWeb`: with `transparency` on, some partly transparent pixels become transparent and the rest keep +their color, and without `transparency` the keys do not change the file. For GIF and PNG-8 an unknown method, or an +amount that is not a whole number from 0 to 100, is refused; other formats do not read the keys, and the warnings name +them. GIF and PNG-8 Options show both as Transparency Dither and its amount, disabled while Transparency is off. + `shape.ellipse` (and `draw_shape` with `shape: "ellipse"`) takes `anchors`, the number of smooth anchors (default 4). Without it, or at 4, it draws a live ellipse. Any other count from 2 to 1000 draws a closed plain path with that many anchors spaced evenly by angle, clockwise from the left one and fitted to `width` × `height`. The Ellipse dialog (a @@ -2152,6 +2161,20 @@ one opens as before and draws it as `rgb`: → invalid parameters for `effect.setParams`: `channel` must be one of rgb, red, green, blue ``` +The `mode` of Drop Shadow, Inner Glow and Outer Glow must name one of the 16 blend modes: `normal`, `darken`, +`multiply`, `colorBurn`, `lighten`, `screen`, `colorDodge`, `overlay`, `softLight`, `hardLight`, `difference`, +`exclusion`, `hue`, `saturation`, `color` or `luminosity`. The name is read in any letter case and with any spaces, +hyphens or underscores (`Color Burn` and `color-burn` are `colorBurn`). An omitted `mode` keeps the effect's default +(`multiply` for Drop Shadow, `screen` for the glows). New `effect.apply` and `effect.setParams` calls refuse any other +value. An older document, action or journal with an unknown name still draws it as `normal`. A non-string value uses +the effect's default. The effect dialogs and the Appearance panel show `mode` as a blend-mode menu. +`ui.dialog.set` accepts the same blend-mode spellings. + +```json +{"id": "effect.setParams", "params": {"index": 0, "params": {"mode": "multipy"}}} +→ invalid parameters for `effect.setParams`: `mode` must be one of normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color, luminosity +``` + Radial Blur's Blur Center, `centerX` and `centerY`, must each be a number from 0 to 1: the share of the object's bounds across from its left edge and down from its top edge (0.5 each, the object's center, by default). The effect turns or zooms about that point, which moves and scales with the object. `effect.apply` and `effect.setParams` refuse any other @@ -2710,8 +2733,11 @@ string, `?.` and `??` are syntax errors. Which files read these forms is VectorC https://ecma-international.org/publications-and-standards/standards/ecma-357/): XML and XMLList literals, the `..`, `.@`, `.*`, `.()` and `::` selectors, `for each`, `default xml namespace`, and the global `XML`, `XMLList`, `Namespace`, `QName`, `isXMLName` and `setDefaultXMLNamespace`, as the XML object pages describe them -(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file also has +`Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a named engine +(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps +its globals. The script reaches the app through the global object `vc`, and writes to the Script Console and runs +other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -2723,8 +2749,20 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and - `app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as + `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`, + `app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `executeMenuCommand` runs the command of a menu item + on the active document, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts + describe the method, and takes these names from the list at + https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510: + `selectall` (`select.all`), `deselectall` (`select.none`), `group` (`object.group`), `ungroup` + (`object.ungroup`), `makeMask` (`object.clippingMask.make`), `releaseMask` (`object.clippingMask.release`), + `compoundPath` (`object.compoundPath.make`) and `noCompoundPath` (`object.compoundPath.release`), and + `Fit Artboard to artwork bounds` (https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee), which runs + `artboard.fitToArt` on the active artboard. Names are matched exactly. Any other name throws an error that names + it, and a name that is not a string throws a `TypeError`. VectorCraft's own rule: a menu item that is not + available, with no document open, nothing selected that it acts on, or a locked active artboard or one with no art + for `Fit Artboard to artwork bounds`, does nothing and adds no undo step. An available menu item runs its command, + and an error that command returns throws. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level @@ -2853,6 +2891,30 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +In a `.js` script, `Promise` follows 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`. `Promise.any` is not provided. These are VectorCraft's +own rules: + +- The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after + the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. + A promise still pending when no job is left stays pending, and the run ends. +- The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends + stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error + `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or + `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. +- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one + item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the + statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. +- A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the + report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was + rejected (the `throw`, or the call of its reject function or of `Promise.reject`), `unhandledRejectionCount` counts + all of them, and the Script Console shows an error line for each, as in + `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. + `all` and `race` preserve an input rejection's known location. Calling a saved reject function from script uses + that call's location. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits + `file` and sets `line` and `column` to 0. + The first run in an engine decides whether the engine has `Symbol` and the iterators of arrays, strings and `arguments` objects, and each run's script decides which syntax that run reads. The built-in functions' names follow the rule above. A `.jsx` script or a `source` string that starts a new engine has no `Symbol` and no iterators of arrays, @@ -3065,7 +3127,8 @@ VectorCraft sets these limits itself: In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, -runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with +`unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the @@ -3912,36 +3975,23 @@ the window's edge. ## Docking toolbars made with New Toolbar -A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (Dock to Left and -Dock to Right in the context menu of the toolbar's title bar, remote mode, `invoke_menu`) docks it in a lane along the -window's left or right edge. On the left, the lane is right of the Tools panel when the Tools panel is docked at the -window's edge. With Keep Tools Beside the Canvas on and the Tools panel docked on the left, the lane is right of the -Tools panel beside the canvas, and dropping a title bar on the Tools panel or on the lane docks the toolbar there. `side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it -docked at last, or at the left the first time. Toolbars docked at one edge stack from the top. `order` is the -toolbar's place in that stack, 0 at the top, from 0 to the number of other toolbars docked there; without it, the -toolbar goes at the end, or stays where it is when it is already docked at that edge. Each toolbar takes an equal -share of the lane's height and its tools scroll in it, and the lane is as wide as its widest toolbar. When the lane -is too short to give each toolbar 88 points of height, the stack wraps into more columns, left to right, and the lane -widens, so no toolbar covers another. A lane takes at most half the width the canvas and panels would have (beside -the canvas, it also leaves the canvas at least 200 points, and the canvas keeps room for one column); when that -many columns still give a toolbar less than 88 points, the toolbars in those columns show only their title bars, which -still float, dock and show the context menu. A column too short for all of its title bars shows as many as fit, and -the mouse wheel over the column scrolls through the others, one toolbar per notch. -`window.toolbar.float {name, x?, y?}` (Float Toolbar in the same menu) floats it with its top-left corner at `x`, `y` -in screen points, or where it floated last when both are omitted. Both commands answer -`{toolbar, floating, side, order, pos}`: `side` is the edge the toolbar docks at (while it floats, the edge it docked -at last), `order` its place in that edge's stack (null while it floats) and `pos` where it floats (while it is docked, -where it floated last). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole -number in range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, -`side` and `order` for each toolbar. +A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (remote mode, +`invoke_menu`) docks it as a column of the dock along the window's left or right edge, and a hidden toolbar shows. +`side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it docks at +now, else at the edge of the docked panel it left when it floated or was hidden, else at the left. `order` is the +place of the toolbar's column in that edge's dock, 0 at the window's edge, from 0 to the number of the dock's other +columns; without it, the toolbar docks as the innermost column, or stays where it is when it already docks at that +edge. `window.toolbar.float {name, x?, y?}` floats it with its top-left corner at `x`, `y` in window points, each +from -1000000 to 1000000. When both are omitted, the dock floats it as it floats a panel, and a toolbar that floats +already stays where it is. Both commands answer `{toolbar, floating, side, order, pos}`: `side` is the edge the +toolbar docks at (while it floats or is hidden, the edge `window.toolbar.dock` uses without `side`), `order` its +column's place in that edge's dock (null while it floats) and `pos` its top-left corner while it floats (null while it +is docked). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole number in +range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, `side` +and `order` for each toolbar. -With the pointer, dropping a floating toolbar's title bar on the window's left or right edge, or on that edge's lane, -docks it at the end of that edge's stack; the target lights up while the title bar is dragged over it. Dragging a -docked toolbar's title bar out of its lane floats it under the pointer. Escape, or the window losing focus, during -the drag puts the toolbar back where it was. Hiding a docked toolbar keeps its place, renaming it keeps its place, a -copy made with Manage Toolbars' + floats, and deleting one closes up the stack. Placement is kept with the workspace. -Toolbars saved before docking existed load floating. The lanes, the edge targets and the stacking are VectorCraft's -own layout rules. +Dragging the toolbar's title bar also docks and floats it. Placement is kept with the +workspace. These are VectorCraft's own layout rules. ```json {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} @@ -4134,7 +4184,8 @@ Copy) and `object.transformAgain`, also when no object is selected, in one undo guide transforms as the line `view.guides.release` makes of it, and the default origin is the center of the selected objects' box and those lines together. A guide that ends up vertical or horizontal stays a ruler guide at its new place: a turn of 180° keeps it, and a turn of 90° makes a horizontal guide vertical. A guide at any other angle -becomes a guide path along its line, on the guide's layer, and is selected as one. Locked or hidden guides do not +becomes a guide path along its line, on the guide's layer, and is selected as one; the reply's `ids` list it after +the transformed objects. Locked or hidden guides do not transform, nor do guides when `ids` is given or `objects` is false. `object.rotate` with `absolute` and only ruler guides selected is an error, as guides have no bounding box angle. @@ -4474,9 +4525,12 @@ already walks Image Trace. Short agent entry points: value goes from the value less the variation (a Scatter brush's first value, an Art brush's `width`) at 0 to the value plus the variation (the second value, `width_max`) at 1, and a stroke without a wheel draws the value half way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The - desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; - it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation - code 3. + desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and + on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` + is installed; without it a Windows pen reads no wheel. Windows opens the Wintab context only while the active tool + uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Blob Brush or + the Eraser with a value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps + no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it @@ -5006,9 +5060,13 @@ already walks Image Trace. Short agent entry points: `replace` is true. Every preset in the file is checked first, and a file with a built-in preset's or `Custom`'s name, two presets of one name, a preset without a name or `params`, settings `imageTrace.presets.save` refuses, or a newer `version` changes nothing. In the app, opening a `.vctracepresets` file (File › Open, a drop, or the file picked - for Import… on the web) imports it as Import… does. Also in the app, - `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog, - and `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) + for Import… on the web) imports it as Import… does. Also in the app, the Image Trace panel's Preset row has a Manage + presets menu. Its Save as New Preset… and Rename… (a saved preset; also F2 on the picker) open a name field in the + row, which starts with the first free "Tracing Preset N" for a new preset and with the preset's name for a rename. + Enter or OK runs `imageTrace.presets.save` (with the panel's settings for a new preset, with `newName` for a rename), + and Escape or Cancel saves nothing. A built-in preset's name, `Custom` or another saved preset's name shows a message + under the field and keeps it open. Its Delete (a saved preset) runs `imageTrace.presets.delete`. + `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) and the saved ones, with the selected preset's settings. Its New… (from the selected preset) and Edit… (a saved preset) open an editor with the Image Trace panel's settings; OK saves with `imageTrace.presets.save` and Cancel saves nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects @@ -8228,7 +8286,8 @@ the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: `items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind. Double-clicking one with Direct Selection opens Corners (`ui.corners {id?, corners?}`, -dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). Double-clicking a selected live shape's corner +dialog `corners`: `kind`, `radii`, `radius`, a percentage of each corner's own maximum while `radii` is `relative`; OK runs +`object.setLiveShape`, as one undo step for corners whose maximums differ). Double-clicking a selected live shape's corner widget with the Selection tool shows and selects the Transform panel, as the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools do. With the headless backend, the `pointer_gesture` reply carries `{"panel": "transform"}` in its `requests`; the desktop app runs `window.panel.activate {"panel": "transform"}` instead, and its reply has no `requests`. The tool, the selection and the document stay as they are, and @@ -8394,6 +8453,13 @@ Commands listed this way include `type.fractionalWidths`, `type.systemLayout`, ` `links.embed`, `links.update`, `object.slice.delete`, `artboard.switchOrientation`, `artboard.distributeSpacing`, `appearance.targetContents` and `paint.invert`. +They also list these UI commands, which have no menu bar item and no default shortcut and whose params are all +optional: `ui.newSwatch`, `ui.newColorGroup`, `ui.colorGroupOptions`, `ui.newBrush`, `ui.brushOptions`, +`ui.layerOptions`, `ui.corners`, `ui.placementOptionsDialog`, `ui.relinkDialog`, `ui.perspectivePlane`, +`ui.bulletsAndNumbering`, `ui.missingFontsDialog` and `ui.findFontsInFolder`. A key assigned to one runs it with no +params, as `{}` does: it opens the dialog for the selection or the current item, or the status bar shows why it cannot, +for example "no brush selected". + Edit › Keyboard Shortcuts and `shortcuts.list` leave out a command with no default shortcut when a key press cannot run it: no item of the menu bar runs it, it opens no dialog when run without params, and it is one of these: @@ -9299,6 +9365,14 @@ Preferences. `prefs.reset` resets the preferences at once, without the question. {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"unitsGeneral","value":"millimeters"}}} ``` +Reset Preferences also sets the dialog's `__smartGuides`, `__snapToGrid` and `__taskBar` fields to their defaults +(`__taskBar` takes the value the current workspace was saved with). A category's own reset sets the field of that +category (Smart Guides, Guides & Grid or General), and File Handling's also resets the app chosen for Edit Original. +`prefs.reset` run while Preferences is open shows the values it reset in the dialog. In the app, `prefs.reset` also resets Smart Guides, +Snap to Grid and Enable Contextual Task Bar when it resets every category or their category (Smart Guides, Guides & +Grid and General), and the app chosen for Edit Original when it resets every category or File Handling. A `category` +left out or `null` resets every category, and one that is not a string is an error. + `prefs.export {path?}` writes the preferences as a JSON file, `{"format": "vectorcraft-preferences", "version": 1, "prefs": {…}}`, and replies `{path, count}`; without `path` it replies `{data, count}` with the file's text. The file holds every preference `prefs.list` lists and the `eyedropper`, `perspectiveWidget`, `pathfinder`, `glyphSnap` and @@ -10364,8 +10438,13 @@ copied (SVG, then PDF, then text, then a bitmap; SVG markup in text counts as SV formats and they are published when they are ready. While that thread has a save, an export, a print or a recovery copy to finish, Copy and Cut make and publish them at once. When another Copy or Cut, or a copy of text in VectorCraft, comes first, they are dropped. Pasting what VectorCraft copied keeps the lossless internal clipboard, -also before its formats are published. While a text field or the Type tool has the keyboard, the app waits for -them. Windows carries every format both ways and pastes a bitmap from PNG, else +also before its formats are published. When the formats could not be written (another app held the clipboard open +or refused the write), every Paste takes the internal clipboard until another app copies something, and a paste +into a text field or type takes the copy's text, or nothing when the formats have no text. The app notices that +copy only when it changes the clipboard's text, so Paste reads the system clipboard when it held only a picture, or +nothing that could be read, at the failed write. Once a paste has read the changed text, the older text coming back +does not restore the copy. While a +text field or the Type tool has the keyboard, the app waits for them. Windows carries every format both ways and pastes a bitmap from PNG, else from the device-independent bitmap screenshots copy (`CF_DIBV5`, then `CF_DIB`; alpha kept, opaque when it is zero throughout, at most 32768 px a side); macOS and Linux carry one format (the text, else the PNG) and paste text and bitmaps (macOS the pasteboard's PNG, else TIFF, as screenshots copy them). A Paste from the menus or the keys decodes @@ -13688,8 +13767,10 @@ its features turned off, distinct from unset. not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value. They also reject a size outside 0.1 to 1296, explicit leading outside 0.1 to 5000, horizontal or vertical scale -outside 1 to 10000, and baseline shift or Tate-chu-yoko offsets outside -1296 to 1296. `leading: null` keeps -Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. +outside 1 to 10000, baseline shift or Tate-chu-yoko offsets outside -1296 to 1296, tracking or kerning +outside -1000 to 10000, rotation outside -360 to 360, a stroke miter limit outside 1 to 500, a +stroke dash length outside 0 to 4000000 or offset outside -4000000 to 4000000, Small Caps outside 1 to 200 and a +variable font axis setting that is not a number. `leading: null` keeps Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. @@ -13821,9 +13902,16 @@ transforms and names included: pixels and runs that don't fit come the same way, fit makes `plugin.run` return a memory-budget error naming the object and its size, with nothing changed. A path or compound path that doesn't fit makes it return the memory-budget error `the selection is too large to hand over`, and more than 100,000 of these objects make it return an object-budget error. Its output returns -each of them as `{"id": …}` or exactly as given, otherwise `plugin.run` returns an error naming the object and the -field, and the document and undo history are unchanged. A filter, or a live effect with commands, at plug-in API level 3 -whose manifest lists `context` (`settings`, `artboards`, `layers`, `swatches`; `context` in its `plugin.list` entry) +each of them as `{"id": …}` or exactly as given (an image may leave out `opacity`), otherwise `plugin.run` returns an +error naming the object and the field, and the document and undo history are unchanged. A filter at plug-in API level 3 whose manifest also lists some of +those kinds in `writes` (with `doc.write`; `writes` in its `plugin.list` entry) may return an object of such a kind with +only the fields it changes: its name and `transform`, type's `text.runs` (at most 4,096 runs and 4,096 paragraphs, and +fills and strokes with only the keys their `type` reads) and `text.paragraphs` (one style per paragraph of the new text, +also when returned as given next to changed runs), an image's `opacity` and +an instance's `symbolId`, which must name a symbol in the document. Any other changed field, or a value out of range, +makes `plugin.run` return an error naming the object and the field, with nothing changed (docs/plugins.md, "Writing +type, images and symbols"). An output that changes nothing records no undo step. A filter, or a live effect with +commands, at plug-in API level 3 whose manifest lists `context` (`settings`, `artboards`, `layers`, `swatches`; `context` in its `plugin.list` entry) also lists `doc.read` in its `permissions`, and each filter or command run is given those parts of the active document in `_context.document`, with or without a selection: the document's name without its folder, color mode, units, active artboard size, bleed and raster effects resolution; every artboard's id, name and rectangle; every layer and sublayer @@ -13911,13 +13999,21 @@ naming the permissions needed. With `VECTORCRAFT_NO_PREFS` set there is no store flag lasts for that session only. In other sessions the approval, or a `grant` accepted under the flag, is kept with the module's hash, counts as approved in later sessions and in the desktop app, and covers only that module: the same bytes install again without one, also from a headless session that reads the same `grants.json`, and a module -with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. `plugin.remove` +with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. A +`grants.json` that does not carry VectorCraft's MAC for its folder, or is at another generation than the one the key +store keeps for the folder, such as an earlier copy put back (see [plug-ins](plugins.md#grants-file-integrity)), grants +nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an +approval lasts for that session only and the file is left as it is. `plugin.remove` forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When -`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed. -When the plug-in's settings and cache can't be moved back from their `.removed` folder then either, the error names -that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A +`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed; +so does a `plugin.remove` while the system key store can't be reached, also when `grants.json` is missing or doesn't +name the plug-in. When `plugin.remove` can't delete an installed plug-in's stored module, it returns an error naming +the file, and the plug-in stays installed with its grant kept in the store. For an id that isn't installed, +`plugin.remove` also deletes the module stored for it that didn't +load and returns `{removed}`. When the plug-in's settings and cache can't be moved back from their `.removed` folder +then either, the error names that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A filter without `doc.write` or `state` that returns output needing them gets an error and the document is unchanged. A plug-in of API level 2 (`api: 2` in its entry) that lists `progress` may report its progress, see Cancel and write log lines: `notifications/cancelled` makes its `vc_cancelled` return 1, and its log lines go to the server's log @@ -14358,9 +14454,10 @@ The new path takes the current fill, stroke and stroke weight (`fill` and `strok above the front-most object along the area (one whose outline touches the area's outline, or that covers it) and is selected. When a group, Live Paint group, Shaper group or clipping group holds that object, the new path goes above the outermost group in its layer, not inside it, and the group keeps its members. In isolation mode only the paths in -the isolated layer or group bound areas, for the tool's hover and click and for the command (with `ids`, only the -paths of the listed objects that are in it), and the new path goes inside the isolated layer or group, 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 +the isolated layer or group bound areas, for the tool's hover and click and for the command. With `ids`, the paths +of the listed objects that are in it bound areas, and all of its paths do when `ids` lists the isolated layer or group +or a layer or group that holds it; the other listed objects are ignored. The new path goes inside the isolated layer +or group, 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. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo @@ -15284,8 +15381,16 @@ Tools: change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a canceled preview does not leave a circle worked out on the previewed paths. + With `addPoints` on, the circle also adds an anchor point to the first segment and to the second segment (or the + one beside it) where it touches them, with `path.insertAnchor` at that point, so the segments are split without + changing their shape; the anchors and the circle are one `command.batch` undo step, and one Undo removes all of them. + When a touched path was not selected, a `select.set` step puts the selection back before the circle is drawn, so + Draw Behind places the circle behind the objects that were selected. + A touch within 0.05 screen pixels of an existing anchor adds no anchor there; when neither touch adds one, only the + circle is drawn. Alt (Option on macOS) held at the release turns `addPoints` the other way for that circle, and a + dot right of and below the pointer shows while it is in effect, following Alt as it is pressed and let go. Options (`tool.setOption`, or a double-click on the tool; kept with the preferences): `radius` (pt, 0.01 to - 1000000, 36); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`, + 1000000, 36); `addPoints` (Add Points to Existing Paths, true or false, false); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`, `blue`, `magenta`, `green`, `black` or `gray`; `red`) is the color of the circle, the cross, the radii and the note; `snapTolerance` (screen pixels, 0 to 25, 3; VectorCraft's own range and default) is how near the pointer picks a segment while Smart Guides are on (their Snapping Tolerance counts instead when it is larger) or while they are off @@ -15475,7 +15580,7 @@ Commands: - `addon.pathtools.shape.set {id, …}` changes a parametric shape's numbers (the same keys; a new `kind` takes its own defaults for the values not given) and redraws it in place. With `reference` (0 to 8 on the 9-point grid of the bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box - keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. Snapping to the pixel + keeps its place, as with the Transform panel's W and H; with `center`, the shape's center moves to it; otherwise the shape's center stays. Snapping to the pixel grid and an attachment to a path apply after that, as they do for the Transform panel's W and H, and can move the point. A `reference` outside 0 to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; `null` when snapping to the pixel grid left a plain path). diff --git a/docs/plugins.md b/docs/plugins.md index 64dc663710..1e98bf058d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -356,8 +356,10 @@ capability model proposed for PhotoCraft plug-ins `grants.json`, and installs a module that lists permissions only under a grant recorded for this very module, also when it loads the Additional Plug-ins Folder. The approval does not protect against native code linked into VectorCraft or against another program running as the same user, which can change the files in the `Plug-ins` - folder. `grants.json` is not signed, so such a program can add a grant to it. `--allow-plugin-grants` is a choice - the person starting a headless session makes. + folder. `grants.json` carries a MAC made with a key kept in the system key store ([grants file + integrity](#grants-file-integrity)), so a program that only edits the file can't add a grant to it; one running as + the same user can still read the key or change VectorCraft. `--allow-plugin-grants` is a choice the person starting + a headless session makes. - **Replacing asks first.** When the file is another module than the plug-in installed with its id, or, with none installed, its id has settings and a cache in the `Plug-ins` folder, Install Plug-in… and File › Open show its id and SHA-256 and ask whether to install it in place of that plug-in, which gives it the settings and cache kept for @@ -378,7 +380,8 @@ capability model proposed for PhotoCraft plug-ins hexadecimal digits covers nothing. `plugin.remove` forgets the grant, and so does a successful `plugin.install` of a module that lists no permissions under that id, so the earlier bytes need a new approval. When `plugin.remove` can't remove the grant from `grants.json`, it returns an error, the plug-in stays installed, and a second `plugin.remove` - tries again. A refused install leaves the grant, the plug-in installed with the id, the `Plug-ins` folder and the + tries again. The same happens when it can't delete the plug-in's stored module, and the grant stays in `grants.json`. + A refused install leaves the grant, the plug-in installed with the id, the `Plug-ins` folder and the list of disabled plug-ins as they are. When another session installs a plug-in with the id or changes its grant while `plugin.install` checks a module, the install is refused, before anything is written to the `Plug-ins` folder, if the other plug-in would need `replace: true` or the changed grant no longer approves the module. A @@ -395,8 +398,8 @@ capability model proposed for PhotoCraft plug-ins it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be removed and the module already stored can't be read back or written back, the new module stays in the folder, and the grant stops counting. The grant also stops counting when the folder held no module for that id. A - `grants.json` larger than 1 MiB, or one that is not a JSON list, grants nothing: the new module stays in the folder, - and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be + `grants.json` larger than 1 MiB, or one that is neither a grants object nor a JSON list, grants nothing: the new + module stays in the folder, and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant stops counting, including for the next load, which tries the removal again. When a later file in the folder holds a module with the @@ -413,8 +416,8 @@ capability model proposed for PhotoCraft plug-ins covers. An entry of `grants.json` that this version can't use (a permission it doesn't know, an invalid id) is skipped and stays in the file until its plug-in is granted again, replaced by a module that lists no permissions, or removed. When such an entry can't be removed from the file, `plugin.install` and `plugin.remove` treat it as a grant - that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written - larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for + that can't be removed. A `grants.json` that is neither a grants object nor a JSON list is never overwritten, and + the file is never written larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, a stored plug-in is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins Folder and `plugin.reload` install only plug-ins that such a grant covers, and report the others. A module without a @@ -425,7 +428,8 @@ capability model proposed for PhotoCraft plug-ins - `api` is the plug-in API level the manifest is written for: `1` (the default); `2`, which adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects); or `3`, which - adds `context` ([document information](#document-information)). A higher one is refused. `plugin.list` and + adds a filter's `writes` ([writing type, images and symbols](#writing-type-images-and-symbols)) and `context` + ([document information](#document-information)). A higher one is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. `context` is not a permission either: it is read under `doc.read` in the same way, and the install prompt says that the plug-in @@ -454,6 +458,67 @@ geometry, fill rule, reference box and the paints the effect is given: a plug-in changes. Failures are cached too. The swatches and patterns a painted result names are checked against the document each time it is drawn, and a paint linked to a global swatch is drawn in that swatch's current color at its own tint. +#### Grants file integrity + +`grants.json` holds the grants in a JSON object, `{"version": 1, "generation": 3, "grants": [...], "mac": "..."}`. +`mac` is an HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the +folder the file is in, the `generation` and the `grants` list written as compact JSON. The key is 32 random bytes that +VectorCraft makes when it records the first grant. VectorCraft keeps the key in the system key store, as the secret of +the account `hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, written as 64 lower-case +hexadecimal digits, and never in a file: + +- On macOS the key is in the user's Keychain. +- On Windows the key is a generic credential in Credential Manager. +- On Linux and the BSDs the key is in the Secret Service, for example GNOME Keyring. When its collection is locked, + the desktop may ask to unlock it. + +When VectorCraft can't connect to the key store, it tries again the next time it needs the key, so a key store that +starts after VectorCraft is used without a restart. VectorCraft reads the key from the key store each time it checks or +signs `grants.json`, so a key removed or replaced there is not used. + +VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in `%LOCALAPPDATA%` on Windows, in the +temporary folder on macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `%LOCALAPPDATA%` or +`$XDG_RUNTIME_DIR` is not set, no key is made, and approvals last for the session only, as when the key store can't be +reached. + +The key store also keeps a generation for each `Plug-ins` folder, as a secret of 16 lower-case hexadecimal digits (the +generation as an 8-byte big-endian number) of the account `generation-v1-` followed by the SHA-256 of the folder's +resolved path in hexadecimal, in the same service. A key store that holds no generation for a folder counts as +generation 0. VectorCraft reads the generation from the key store only, never from `grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first +raises the kept generation by two, then writes the file at the generation after the raised one, and then keeps that +generation. When it removes a signed `grants.json`, it raises the generation by two first. The kept generation never +goes down: when the file can't be written or removed after the raise, the generation stays raised, the file left in +place grants nothing, and each plug-in it names that lists permissions asks for approval again. VectorCraft checks +before the raise whether the signed file would be larger than 1 MiB; when it would, VectorCraft logs a warning and +leaves the file and the generation as they are, and the file keeps its grants. When the key store can't keep the generation of a write, the file +just written grants nothing, and the write reports a failure. That file is one generation past the kept one, so the +next raise by two moves past it. When the kept generation is within two of the largest 64-bit value, VectorCraft +logs a warning and leaves the file and the generation as they are. + +VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its +folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it +names that lists permissions asks for approval again. This covers a file that an earlier version wrote (a plain JSON +list), a grant that another program edited or added, a file whose `mac` was removed or changed, a file copied from +another `Plug-ins` folder or another computer, an earlier copy of the file put back after a grant was revoked or the +file was removed, a write whose generation the key store didn't keep, a file left in place by a write or removal that +failed after the generation was raised, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when +the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists +no permissions under that id, or a folder load that forgets the grant), VectorCraft raises the generation by two, then +takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It +also raises the generation by two when a grant is forgotten while there is no `grants.json`, or while the file in its +place grants nothing (no valid MAC, too large, or neither a grants object nor a JSON list) and has no entry to take out, +whenever the key store holds a key. A `generation` written into such a file has no effect on the raise. When the key +store can't raise the generation, VectorCraft logs a warning. + +When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no +`grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored +for the id is not replaced, and `plugin.remove` of a plug-in returns an error and leaves the plug-in installed, as for a +grant that can't be removed. This also happens when there is no `grants.json` or the file doesn't name the plug-in. +`plugin.remove` of an id that isn't installed deletes the module stored for it that didn't load, such as one an +earlier version's `grants.json` approved, and returns `{removed}`. With `VECTORCRAFT_NO_PREFS` set there is no plug-in store, and the web build keeps no grants file. The +MAC does not protect against another program running as the same user, which can read the key from the key store or +change VectorCraft itself. + ## ABI v1 A plug-in is a core WebAssembly module (MVP + these post-MVP features: mutable globals, sign extension, saturating @@ -671,11 +736,17 @@ the module's start function, in a run that isn't a filter's run on a document, o filters](#heavy-filters)). Hosts from before it ignore the key, so there the filter gets a light run's budget. - `api`: the plug-in API level, `1` when left out. `permissions`: what the plug-in may do, a list of names ([permissions](#permissions)); without it, what its kind implies. -- `inputs` (filters at `api` 2 only): the kinds of object besides paths and compound paths the filter reads, any of +- `inputs` (filters at `api` 2 or later): the kinds of object besides paths and compound paths the filter reads, any of `"type"`, `"image"` and `"symbolInstance"`, each at most once (`"inputs": ["type", "image"]`). Left out or `[]`, the filter gets paths and compound paths alone, as before. An unknown, repeated or wrongly typed entry, `inputs` on another kind, below `api` 2, or without a `permissions` list that holds `doc.read`, is refused when the plug-in is installed, and so is `api` 2 on hosts from before it. +- `writes` (filters at `api` 3 only): the kinds among `inputs` the filter may change ([writing type, images and + symbols](#writing-type-images-and-symbols)), each at most once (`"writes": ["type"]`). Left out or `[]`, everything + the filter reads stays read-only. An unknown, repeated or wrongly typed entry, a kind `inputs` doesn't list, `writes` + on another kind, below `api` 3, or without `doc.write` in `permissions`, is refused when the plug-in is installed. + Hosts from before `api` 3 refuse the manifest. A host at `api` 3 that doesn't read `writes` installs the filter, + ignores the key and keeps everything the filter reads read-only, so an output that changes those objects is refused. - `context` (filters, and live effects with `commands`, at `api` 3 only): the parts of the active document a run reads in `_context.document`, any of `"settings"`, `"artboards"`, `"layers"` and `"swatches"`, each at most once (`"context": ["artboards", "layers"]`). Left out or `[]`, a run gets none, as before. An unknown, repeated or wrongly @@ -733,10 +804,12 @@ declares them still installs there: | `help` | Shows what the parameter does when the pointer rests on its label (1–1,000 characters; line breaks allowed). | | `helpUrl` | Opens this `https://` page (at most 512 bytes) from a button after the field. | | `visibleWhen` | `{"pattern": ["lines", "crosshatch"], "outline": [true]}` shows the parameter only while each parameter it names (a checkbox or a choice declared before it) has one of the values listed and is shown itself. | +| `widget` | `"slider"` shows an `int` parameter as a slider over `min..max` with its number field, moving by 1. A `number` parameter with `min` below `max` always shows a slider with its field, with or without the key. The key needs `min` below `max`, and an `int`'s range within ±9,007,199,254,740,992; on any other parameter, or with another value, the manifest is refused at install. | A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's -parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons. +parameters uses `label`, `unit`, `help`, `visibleWhen` and `widget`, and lists the parameters without sections or +help buttons. ### Input @@ -810,7 +883,7 @@ every attribute: "runs": [{"text": "Hello\nthere", "style": {"font_family": "Source Sans 3", "size": 12}}], "paragraphs": [{"justify": "Left"}, {"justify": "Center"}]}, "truncated": false}, - {"id": 18, "type": "image", "bounds": [0, 0, 4, 2], "transform": [2, 0, 0, 2, 0, 0], "pixelSize": [2, 1], + {"id": 18, "type": "image", "bounds": [0, 0, 4, 2], "transform": [2, 0, 0, 2, 0, 0], "opacity": 1, "pixelSize": [2, 1], "colorMode": "rgb", "linked": false, "pixelsOmitted": false, "pixelsBase64": "AAAegGQAHoA="}, {"id": 19, "type": "symbolInstance", "bounds": [100, 0, 110, 10], "transform": [1, 0, 0, 1, 100, 0], "symbolId": "Star", "overrides": {}} @@ -824,7 +897,7 @@ every attribute: true` and empty `runs` and `paragraphs`. The runs and paragraphs of all the type in one input take at most 16 MiB of JSON: type whose runs and paragraphs don't fit what the type before it in paint order left comes with `truncated: true` too. -- An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or +- An image (`"image"`): `opacity` is its opacity, 0 to 1; `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape that is not a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right, bottom right, bottom left), and its `transform` is then the affine placement nearest them, the one that matches the @@ -844,10 +917,13 @@ every attribute: - A symbol instance (`"symbolInstance"`): `symbolId` is the name of the symbol it shows, with `missing: true` when the document has no symbol of that name. `overrides` is `{}`. -These objects are read only. The output must list each of them exactly once, as `{"id": 17}` alone or exactly as it -was given (numbers compare by value, so `1` and `1.0` are the same). A changed or added field, one left out, an object -listed twice or left out, and a new object with one of these types are refused, and the document and undo history -stay as they were: `objects[1] (id 17): read-only field 'text.runs[0].text' changed`, `objects (id 17): a read-only +Objects of a kind that the manifest's `writes` doesn't list are read only. The output must list each of them exactly +once, as `{"id": 17}` alone or exactly as it was given (numbers compare by value, so `1` and `1.0` are the same). An +image may leave out `opacity`, which hosts before `api` 3 don't give. An object of a kind that `writes` lists is also +listed exactly once, and its entry may give only the fields it changes ([writing type, images and +symbols](#writing-type-images-and-symbols)). An output deletes the paths and compound paths it leaves out +([output](#output)), but none of these objects. A changed or added field, one left out, an object listed twice or left +out, and a new object with one of these types are refused, and the document and undo history stay as they were: `objects[1] (id 17): read-only field 'text.runs[0].text' changed`, `objects (id 17): a read-only object was left out`. The field is named with control and bidirectional characters escaped (`\u{202E}`), cut to 64 characters. New objects listed after one of them go just above it. @@ -861,6 +937,61 @@ the objects after it are written. An output lists at most 100,000 objects, so a objects fails with `plug-in exceeded its object budget (more than 100000 read-only objects)`. An echo of them counts toward the 64 MiB output cap. +### Writing type, images and symbols + +A filter at `api` 3 whose manifest lists some of its `inputs` kinds in `writes`, with `doc.write` in its +`permissions`, may change the objects of those kinds it is given. It returns such an object as `{"id": 17}` alone, +exactly as given, or with the fields it changes; a field it leaves out keeps its value. Each kind takes these fields: + +| Kind | Fields a filter may change | +|------|----------------------------| +| `type` | `name`, `transform`, `text.runs`, `text.paragraphs` | +| `image` | `name`, `transform`, `opacity` | +| `symbolInstance` | `name`, `transform`, `symbolId` | + +```json +{"objects": [ + {"id": 17, "text": {"runs": [{"text": "Goodbye", "style": {"font_family": "Source Sans 3", "size": 14}}]}}, + {"id": 18, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.5}, + {"id": 19, "symbolId": "Moon"} +]} +``` + +- `name` is a string, or `null` for no name. +- `transform` is six finite numbers, each within ±4,000,000, that don't flatten the object to a line. The object moves + by the change from its given transform, so an image's distorted corners move with it. +- `text.runs` replaces the type's runs: each is `{text, style, inline?}` with the character attributes as the native + file stores them, and an attribute the host doesn't know is refused, as is a key of a fill or stroke that its `type` + doesn't read. There is at least one run, at most 4,096, at most 4,096 paragraphs, and at most 256 KiB of UTF-8 text; + the runs written in one output take at most 16 MiB. Every number in every run's style is + checked against the range `charStyle.new` keeps it to, including a style one of the type's runs already has: size + 0.1 to 1296 pt, leading 0.1 to 5000 pt, tracking and kerning -1000 to 10000, horizontal and vertical scale 1 to + 10000 %, baseline shift -1296 to 1296 pt, rotation -360 to 360°, and the ranges `docs/mcp.md` gives for + `charStyle.new` for the East Asian, Warichu and stroke attributes. A style that none of the type's runs has also needs a font family of 1 to 256 + printable characters, and fills and strokes that a path's appearance would take. Inline graphics stay where they + were: the runs keep each `inline` run as it was given, in the same order. The characters of threaded type, and of + type with ruby, can't change, though their attributes can. The runs and paragraphs of type given with + `truncated: true` can't change. +- `text.paragraphs` holds one paragraph style per paragraph of the new text, each checked as `paraStyle.new` checks + its attributes: indents and space before and after within ±1296 pt, the Hyphenation and Justification options in + their ranges, at most 256 tab stops at 0 to 100,000 pt, and a custom Kinsoku set only by the name of one of the + document's sets, whose characters the paragraph takes. A `text.paragraphs` list returned as it was given next to + changed `text.runs` must also hold one style per paragraph of the new text. With `text.runs` alone, each paragraph keeps its style when + the number of paragraphs stays the same. When runs add or join paragraphs, the host matches the old and new + paragraphs by their text: a paragraph whose text is unchanged keeps its style, changed paragraphs take the styles of + the paragraphs they replace in order, and a paragraph added between others takes the style of the one before it (of + the next one at the start), without a list number. Apart from the paragraphs both texts start and end with, when + the old paragraphs times the new ones pass 262,144, the host pairs them in order instead. +- `opacity` is a number from 0 to 1. +- `symbolId` names a symbol in the document. An instance that shows another symbol loses its overrides, as Replace + Symbol does. + +Every other field, including `type`, `bounds`, `text.kind` and an image's pixels, stays read-only, and objects of these +kinds can't be added or left out. A changed read-only field or a value out of range refuses the whole output, naming +the object and the field (`objects[2] (id 18).opacity: must be a number from 0 to 1`), and the document and undo history +stay as they were. The changes of one run are one undo step, with the type laid out again; an output that changes +nothing records no undo step. The host never reads or gives a linked image's file when a filter writes. + ### Document information A filter, or a live effect with [commands](#commands), whose manifest lists `context` (plug-in API level 3) gets those @@ -948,7 +1079,9 @@ For an **object filter**, the output is the new state of the input objects: - An object without an `id` is new and needs a `path`. It goes just above the object listed before it, or, listed before any input object, just below the first one listed after it. New objects take a path's defaults: no fills or strokes, full opacity. -- Input objects missing from the output are deleted. The order of the input objects themselves doesn't change. +- Input paths and compound paths missing from the output are deleted; type, images and symbol instances can't be left + out ([reading type, images and symbols](#reading-type-images-and-symbols)). The order of the input objects themselves + doesn't change. - `type` turns a path into a compound path (one member per subpath) or back; `name: ""` clears the name. - `guide: true` makes the object a guide, as View › Guides › Make Guides does (a compound path's members become guide paths), and `guide: false` a plain path again; `locked: true` locks it and `locked: false` unlocks it. Objects @@ -1102,7 +1235,7 @@ per change of their input, parameters or paints (results are cached), not per fr - Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, importers that make type, images, layers or artboards, and placed importer files that stay linked to their file. - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces - it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see - [`inputs`](#reading-type-images-and-symbols)). + it returns), filters that add or delete type, images or symbol instances or change their pixels and other fields + (a filter at `api` 3 changes [some of their fields](#writing-type-images-and-symbols)). - Scripts can't run object filters (`plugin.*` commands are refused there), so a script doesn't change what Apply Last Filter runs. diff --git a/docs/roadmap.md b/docs/roadmap.md index 985c3f16e0..9b41b638cf 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -53,7 +53,7 @@ Creating a gradient from solid or empty paint uses the document's color model fo Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-03. +**Feature evidence last updated:** 2026-11-21. M1 selection: Enclosing Lasso selects whole objects enclosed by a freehand loop. It is an add-on under Object › Plug-ins, and its tool is also in the Lasso tool's group in both shipped toolbars, @@ -76,6 +76,8 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | M14/G12: Appearance panel item context menus for stroke, fill, effect, and root object rows (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance); secondary-click selects unselected rows including via name label links; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | M14/G12: Graphic Styles panel item context menus in thumbnail and list views (Options…, Duplicate, Delete, Redefine, Break Link); regression tests in crates/ui-egui/src/panels/graphic_styles.rs; scores and estimates unchanged. | @@ -199,7 +201,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | -| M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | +| M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -241,6 +243,8 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | @@ -485,3 +489,5 @@ Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transpare > **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. > **Text styles status (2026-11-19):** Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides) are implemented and covered by headless tests; parity scores and estimates are unchanged. + +> **History status (2026-11-20, G12/M14):** History row context menus are implemented with headless snapshot, pending-edit, typing, stepping, clear-history, keyboard menu and document-switch regressions in `panels::history::tests` (#8845). Other G12 work, scores and estimates are unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 90367efd7c..022ff2bb6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -32,6 +32,10 @@ ## Feature submission evidence +History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. + +Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -58,7 +62,7 @@ Spiral decay now applies after each full wind of four segments. A newly drawn sp Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-19. +**Feature evidence last updated:** 2026-11-21. Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. @@ -79,7 +83,11 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | +| 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. | | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | +| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | @@ -110,6 +118,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | Pencil and Paintbrush: a closed stroke (Alt at the release, or ending within Close Paths When Ends Are Within of its start) is fitted as the open stroke would be and closed by a straight segment back to its start, instead of curving on past both ends (`pencil_alt_closes_a_stroke_straight_back_to_its_start` in `crates/engine/src/tests/draw2.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged. | +| 2026-11-13 | minor | Scale tool: a Shift-drag within 22.5° of horizontal or vertical scales along that axis alone, a diagonal one uniformly (#6324); scores unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release (`a_continued_stroke_shows_where_it_connects_or_closes` in `crates/tools/src/draw2/gesture/tests.rs`, `pencil_extend_closes_as_closed_says` in `crates/engine/src/tests/draw2.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Pencil: ignores Smart Guides and Snap to Point and shows no Smart Guides, hovering or drawing; a stroke's ends and both ends of its straight lines follow the hand, while Snap to Grid and Snap to Pixel still move them (#7252; `pencil_follows_the_hand_and_shows_no_smart_guides`, `pencil_ends_still_snap_to_the_grid_and_pixels` in `crates/tools/src/draw2/gesture/tests.rs`). Public basis: community experts on the reference app's forum say Smart Guides and the other snapping options don't make the Pencil snap ([Drawing and snapping to path in Illustrator](https://community.adobe.com/questions-652/drawing-and-snapping-to-path-in-illustrator-766887)). Scores and estimates unchanged. | | 2026-11-13 | minor | Snap to Point: with Smart Guides off it still pulls drawn and dragged points onto anchors and ruler guides, but draws none of the Smart Guides labels ("anchor") or lines (#7250; `guides::tests::snap_to_point_without_smart_guides_shows_no_guides`). Scores and estimates unchanged. | @@ -323,7 +332,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -669,6 +678,8 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline and the hover highlight; `the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn` in the same file covers the limit; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group or layer draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover outline and other panes. A selected blend, repeat or intertwine draws no outline for its hidden members. The points of hidden members do not count toward the 100,000-point limit. The rectangle drawn above that limit still uses the selection's bounds, which include a group's hidden members. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` (with the hover outline) and `the_overlay_limit_leaves_out_hidden_members` in `crates/ui-egui/src/canvas/selection/tests.rs`; `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. @@ -815,6 +826,7 @@ since 2026-10-01. - **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. - **EPS export and Discard White Overprint:** the help page describes Discard White Overprint as taking the overprint attribute off white objects in output, without changing the artwork ([white overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html)). EPS export and PostScript printing, composite and separated, now follow Discard White Overprint in Output (Document Setup), as PDF export does: a white fill or stroke marked to overprint knocks out while the setting is on and overprints while it is off. The same page says the setting covers process white and not spot white, so a white fill linked to a spot swatch that has a color keeps overprinting. The tiles of an overprinting pattern fill overprint with it. Evidence: `cmd::fileio::tests_eps::overprints_are_kept_or_discarded`, `tests::tiles_overprint_with_their_overprinting_pattern`, `tests::white_type_fills_knock_out_with_discard_white_overprint`, `tests::spot_white_fills_overprint_with_discard_white_overprint`, `print::tests::white_overprints_knock_out_on_postscript_plates_with_discard_white_overprint`. - **Save PDF custom flattener settings:** the help page describes the Advanced section's flattener preset for PDF 1.3 saves of transparent art, with a Custom button for adjusting the flattener settings, and says neither is available at PDF 1.4 and later ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). Save PDF › Advanced now has Custom… beside Flattener preset, enabled for PDF 1.3, PDF/X-1a and PDF/X-3. It opens Custom Transparency Flattener Options on the settings the save would use: the raster/vector balance, both resolutions, the text and stroke outline switches and Anti-alias Rasters; Clip Complex Regions shows on, as the PDF 1.3 writer always clips, overprints are kept only with Overprint set to Preserve, and Preserve Alpha Transparency shows off, as PDF 1.3 rasters keep no alpha. OK goes back to Save PDF with the preset shown as [Custom] and the save flattens with those settings; settings equal to the preset's leave its name, choosing a preset drops them, and Cancel goes back unchanged. PDF presets keep the flattener preset but not these settings, and Save Preset… says so while they are set. `ui.savePdfDialog` keeps a `flattener` it is given. The [Custom] label, the Cancel behavior, Anti-alias Rasters, the editor's absence from the PDF preset editor and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::save_pdf::tests::custom_is_enabled_where_the_save_flattens`, `custom_starts_from_the_preset_and_cancel_goes_back_unchanged`, `custom_options_are_written_until_a_preset_is_chosen`, `custom_options_equal_to_the_preset_leave_its_name`, `custom_shows_alpha_as_the_pdf_1_3_writer_drops_it`, `save_preset_says_it_leaves_the_custom_flattener_options_out`, `save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones`. +- **Save PDF and Print field names for screen readers:** the number, length and range fields of Print (copies, range, width, height, overlap, tile range, gutter, scale, bleed sides, flatness, unprintable margin) and of Save PDF (range, bleed sides, font subset threshold) have a name in the accessibility tree. Evidence: `dialogs::save_pdf::tests::the_range_bleed_and_subset_fields_are_named`, `dialogs::tests_print::every_number_and_length_field_is_named`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. @@ -840,7 +852,7 @@ since 2026-10-01. - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). - **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). -- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. +- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt, tracking and kerning from -1000 to 10,000, rotation from -360° to 360°, a stroke miter limit from 1 to 500, Small Caps from 1% to 200%, finite stroke dashes and variable font axis settings. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), the Tate-chu-yoko Settings Up/Down and Left/Right (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0 pt, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these seven. Language sets the language the characters are shaped in, not hyphenation or spelling. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html). - **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). @@ -897,6 +909,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Reset Preferences resets every setting the dialog shows:** Smart Guides and Snap to Grid also return to their defaults (on and off) when Reset Preferences is confirmed, and General's Enable Contextual Task Bar takes the value the current workspace was saved with. OK in Preferences applies them with the other defaults, and Cancel keeps the values in use. A category's own reset resets the row of that category, and File Handling's also resets the app chosen for Edit Original. `prefs.reset` (the Command Palette's Reset Preferences) resets them too, each only when it resets every category or the setting's own, and with every category or File Handling it also clears the app chosen for Edit Original. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`, `crates/ui-egui/src/original_editor.rs`. - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. @@ -962,6 +975,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Text command parameter errors:** `text.editRange`'s `insert`, `text.setText`'s `text` and `text.createInPath`'s `mode` and `text` must be strings, `text.createInPath`'s `at` must be two numbers, and `start` in `text.touchType`, `text.glyphAlternates` and `text.setGlyphAlternate` must be a whole number of at least 0. A wrong value is an error naming the parameter, and the document and undo history do not change; null is read as the parameter left out. Pathfinder `precision` takes a number, a string that is all one number or a length with a unit, and refuses a string such as `"1abc"`. This is VectorCraft's own rule; no score changes. Tests: `tests::textedit::text_edits_refuse_a_param_of_the_wrong_type` and `tests::pathops::pathfinder_options_round_trip_and_refuse_bad_values` in `vectorcraft-engine`. - **Automation:** + - Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. - Variables: a visibility variable binds a locked layer, a locked object and objects inside a locked layer or group, and `dataset.select`, `dataset.next` and `dataset.prev` show and hide them without unlocking them; `dataset.list`, `dataset.capture` and `dataset.update` read whether they show. A text, image or graph variable refuses locked art. @@ -1018,7 +1032,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - - Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet; its previews and Save… use the remembered ones, and a preset picked in the dialog does not change them. + - Save for Web: with Transparency on, GIF and PNG-8 offer Transparency Dither (No Transparency Dither, Diffusion, Pattern and Noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an Amount for Diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is No Transparency Dither with Amount 100; with Pattern, Noise, or Diffusion at Amount 100, about as many pixels stay opaque as their opacity says, and a lower Diffusion Amount comes closer to No Transparency Dither; Pattern uses an 8×8 ordered pattern and Noise a fixed noise, so the same art always gives the same file; Amount 0 gives the same file as No Transparency Dither; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; both rows are disabled while Transparency is off and keep their values; presets and the remembered settings keep them (`transparencyDither`, `transparencyDitherAmount`). + - Export As: GIF and PNG-8 Options offer the same Transparency Dither and Amount as Save for Web, disabled while Transparency is off, and `document.export` takes `transparencyDither` and `transparencyDitherAmount` for GIF and PNG-8 with the same values, refusing an unknown method or an amount that is not a whole number from 0 to 100; other formats do not read the keys, and the warnings name them. Using Save for Web's keys in the other export is VectorCraft's own rule. `crates/engine/src/cmd/fileio/tests_palette.rs` (`palette_exports_take_the_transparency_dither`), `crates/ui-egui/src/dialogs/tests_raster_formats.rs` (`palette_options_send_the_transparency_dither`, `palette_options_name_the_transparency_dither_controls`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). @@ -1040,7 +1055,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. @@ -1098,9 +1113,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. + - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. + - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. @@ -1211,6 +1227,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Korean catalog (`crates/ui-egui/src/i18n/ko.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 39 Korean messages; they are the composite font, select-a-path, justification order and `path.freehand` connect errors that open #7211, #7214, #7116 and #7330 translate. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The Vietnamese catalog (`crates/ui-egui/src/i18n/vi.tsv`) has an `@msg` row for 115 of the status and error messages that the untranslated report listed for every complete-message catalog, among them the image export, color profile, color book, swatch exchange file, swatch library, DXF and DWG import, 3D and Revolve errors and the `index` whole-number error, 1,750 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 1,875 Vietnamese messages without a row; open #7211, #7378, #7405 and #7434 translate 53 of them. - The Swedish catalog (`crates/ui-egui/src/i18n/sv.tsv`) translates status and error messages, among them the image export, color profile, color book, swatch exchange file, DXF import, 3D and Revolve errors and the `index` check of `document.activate`, 3,106 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 518 Swedish messages, 54 of them messages that no catalog translates yet. + - History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. - The History panel menu's Clear History (`edit.clearHistory`) removes every step to undo and to redo and leaves the document as it is; it is not an undo step itself, and it is disabled when there is no step to clear. - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. @@ -1354,6 +1371,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - Screen readers read the isolation bar's back arrow as a button named for what it does (Back One Level, Exit Isolation Mode, Exit Symbol Editing Mode, or Done while a pattern is edited), in the UI's language (`the_isolation_bars_controls_have_screen_reader_names`). - In isolation mode the Layers panel lists only the art of the isolated layer, sublayer or group, and lists the other layers and groups again when isolation mode ends ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=212)). As VectorCraft's own rules, the isolated layer, sublayer, group or object is the top row and opens on entering, the panel scrolls back to its row on leaving, search and filter look only inside it, nothing is dropped beside its row or into the empty space under the rows, Rename and Locate Object open no rows outside it, and rows highlighted outside it are no longer highlighted. With no row highlighted, Delete Selection and the trash do not delete a current layer outside it. New Layer, New Sublayer and Duplicate (in the panel menu and a row's context menu) are off, and OK in New Layer Options is an error, while the layer or copy they make would be outside it (`isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again`, `isolation_opens_the_isolated_row_and_keeps_drops_inside_it`, `isolation_drops_highlights_outside_the_isolated_art`, `isolation_keeps_rename_and_locate_to_the_rows_listed`, `isolation_keeps_delete_to_the_rows_listed`, `isolation_keeps_new_layers_to_the_rows_listed`, `new_layer_options_ok_checks_isolation_again`). - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). @@ -1501,7 +1519,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Eraser Tool Options show the Blob Brush's tip preview under the Roundness rows. A drag on the arrowhead turns the Angle, and a drag that starts on a black dot moves it toward the center for a flatter tip or away from it for a rounder one, as the Eraser tool options section of the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133) describes; the fields show the new values, and OK keeps them. The drag's mapping and the Angle and Roundness sliders are the Blob Brush preview's, which are VectorCraft's own, with the Eraser's Roundness range of 1% to 100% for the drag and the keys. The preview shows the set Angle and Roundness, not a Random or pen-driven variation of them. Regression tests: `dialogs::tests::the_eraser_tip_preview_sets_the_angle_and_roundness_by_dragging`, `dialogs::freehand::tests::a_roundness_dot_keeps_the_eraser_at_one_percent_or_more`. The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). + - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Scale tool drag with Shift held scales along one axis when it runs horizontally or vertically and uniformly when it runs diagonally ([Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); #6324). The page gives no angle: in VectorCraft a drag within 22.5° of an axis runs along it, judged from the pointer's own movement, and a drag that starts level with the reference point on that axis scales uniformly, having nothing to scale along it (`scale_shift_follows_the_drag_direction` and `scale_shift_axis_follows_the_pointer_not_the_snapped_press` in `crates/tools/src/xform/transform.rs`). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Shear takes an angle from -359° to 359° and shears by its tangent, so 120° slants as -60°; an angle outside that range, and ±90° and ±270° (VectorCraft's own rule), return an error ([shear objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `shear_angles_slant_by_their_tangent`, `shear_rejects_angles_with_no_shear_or_out_of_range`). The Transform panel's Shear field takes the same range, and the status bar shows the error for an angle Shear refuses, as VectorCraft's own rule ([shear objects with the Transform panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `panels::transform::tests::the_shear_field_takes_angles_from_minus_359_to_359`, `the_shear_field_shows_the_error_for_an_angle_with_no_shear`). Align and Distribute act on the anchor points selected with Direct Selection (#1641, fixes #1636). Align moves the points to the edge or center of their own bounds, of the artboard with Align to Artboard, or to a key guide; with a key anchor, the other points move to it and the key anchor stays in place. On a pixel-aligned path, the snap to the pixel grid that follows Align can move the key anchor when it ends up on a horizontal or vertical straight segment, which the snap puts on a whole or half point. Distribute spaces the points among themselves (`align_moves_selected_anchor_points`, `selected_anchor_points_align_to_a_key_guide`, `align_moves_the_other_points_to_the_key_anchor`). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. @@ -1813,6 +1831,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + Right-clicking an OpenType feature row preserves the text selection. The row offers **Turn Off** when every affected character has the feature on, and **Turn On** when the feature is off or mixed. On a mixed Type-tool selection, **Turn On** enables the feature across the selected range and leaves characters outside it untouched. **Reset OpenType Features** restores the same defaults as the panel menu. Each action takes one undo step. Focused tests in `panels::opentype::tests` include `right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `clicking_turn_on_sets_that_feature_in_one_undo_step`, `turn_on_preserves_the_mixed_character_range_and_undo_restores_its_runs`, and `clicking_reset_opentype_features_clears_the_rows`. The OpenType panel menu has a Stylistic Sets submenu after Reset OpenType Features, with the same sets, labels and checks as the panel's Stylistic Sets button; a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features, and the submenu is disabled with no text selected or when the font offers no sets. The 2019 user guide ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) has stylistic sets chosen from the OpenType panel menu. The submenu's place in the menu is VectorCraft's own. Tests: `panels::opentype::tests::the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off`. With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. With Show East Asian Options on, the OpenType panel menu also has Proportional Metrics, before H or V Style; [the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) lists it among the OpenType panel options that this setting shows. It sets the `proportionalMetrics` character attribute that the Character panel menu's item sets (`palt` in horizontal type, `vpal` in vertical type), through `text.setFormat` for selected type and `text.setRangeStyle` while the Type tool edits text. It is checked when every character it changes has the attribute (at a Type tool caret, every character of the text), and choosing it turns the attribute on for all of them, or off when it is checked, in one undo step, keeping their other attributes; with no type selected it is disabled. Its place in the menu and the check rule are VectorCraft's own. Tests: `panels::opentype::tests::proportional_metrics_turns_on_and_off_for_a_mixed_range`, `panels::opentype::tests::proportional_metrics_reaches_a_selected_object_and_the_text_at_a_caret`. @@ -2112,7 +2131,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2120,7 +2139,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. @@ -2699,6 +2718,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. +- **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. - **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged. - **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. @@ -2715,11 +2735,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Bulk memory fuzz cases use the host's fuel constants:** `crates/engine/tests/plugin_fuzz.rs` samples runs around one slice of the instruction budget and lengths around the bytes one unit of fuel pays for with `vectorcraft_plugins`' own `FUEL_SLICE` and `BYTES_COPIED_PER_FUEL`, so the sampled cases move when either value changes. Regressions: `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), every number in every run's and paragraph's style is checked against the range `charStyle.new` and `paraStyle.new` keep it to (one shared check, also for a style the type already has), a custom Kinsoku set must be one of the document's, a style of the filter's own needs a font family and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-ins read document information without a selection (G17):** a filter, or a live effect with commands, at plug-in API level 3 lists `context` (`settings`, `artboards`, `layers`, `swatches`) with `doc.read` in its `permissions`, so installing it asks for approval and the prompt names the document information, and each filter or command run is given those sections in `_context.document` whether or not anything is selected: the document's name without its folder, color mode, units, active artboard size, bleed and raster effects resolution; every artboard's id, index, name, rectangle and whether it is active; every layer and sublayer with its id, parent, depth, name, own visibility, lock and template settings, color and whether it is current; and every swatch as `swatch.list` lists it, with the document's revision. No path, object or other document is given, and drawing a live effect gets none. More than 10,000 rows or 4 MiB of them fail the run before the plug-in starts, and each row takes 1,000 instructions from its budget (VectorCraft's own values). Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. -- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -2727,6 +2748,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal and never lowered. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept, a file left in place by a write or removal that failed after the generation was raised) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file, and `plugin.remove` of a stored plug-in that didn't load deletes its module and reports it removed. When the key store can't be reached, an approval lasts for the session only, the file is left as it is, and `plugin.remove` fails and leaves the plug-in installed. A key store that can't be reached is tried again the next time it is needed. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/store/grant_keys.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) unless its manifest places it in another menu, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands at one spot keep plug-in id order and then manifest order; a filter whose commands are all placed elsewhere is a single item in Object › Plug-ins, and such a live effect is a single item in Effect › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. @@ -3076,6 +3098,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its options, off to start) also adds an anchor point where the circle touches each of the two segments, splitting them without changing their shape, in the circle's undo step; a touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. Tests: `addons::tangent_circle::tests::add_points_*` in `vectorcraft-tools`, `the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step` in `vectorcraft-engine`, and the options dialog test in `vectorcraft-ui-egui`. + The tool's options dialog also sets the preview and how a segment is picked, the options the help page lists (https://docs.astutegraphics.com/subscribe/tangent-circle-tool): Circle Center and Circle Radii Lines (`center`, `radii`) show or hide the center cross and the radii, Color (`color`: red, blue, magenta, green, black or gray) colors the circle, the cross, the radii and the note, Snap Tolerance (`snapTolerance`, screen pixels) is how near the pointer picks a segment with Smart Guides on, the Smart Guides Snapping Tolerance counting when it is larger, and Snap When Smart Guides Are Off (`snapWithoutGuides`) keeps that reach with Smart Guides off; without it the Selection Tolerance applies. Of the segments within reach the nearest is picked. The defaults (both shown, red, 3 px, snapping on) and the 0 to 25 px range are VectorCraft's own; they are kept with the preferences, and `tool.setOption` gives an error for a value an option does not take. Tests: `addons::tangent_circle::tests` in `vectorcraft-tools` (the preview options, the snapping reach, the options' values) and `the_tangent_circle_options_set_the_preview_and_snapping` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) @@ -3245,6 +3269,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 29cc1b5a18..142666cec2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -44,7 +44,7 @@ Creating a gradient from solid or empty paint uses the document's color model fo Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-19. +**Feature evidence last updated:** 2026-11-21. Enclosing Lasso is an add-on under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select. A toolbar @@ -70,6 +70,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. | @@ -416,7 +418,9 @@ the type shortcuts (tracking/kerning/leading/baseline steps with Alt/Shift), and Layers panel. The shortcut editor also lists the commands that are in no menu but run without parameters (Edit › Duplicate, panel-menu commands such as Break Link to Symbol), so they can be given shortcuts (#1539). It lists each button of the Align panel's Align Objects, Distribute Objects and Distribute Spacing rows under Align, with no default shortcut, and a -shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). +shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. +It also lists the panel and dialog commands whose parameters are all optional, such as New Swatch…, Brush Options… +and Corners…, and a shortcut set there opens the dialog for the selection or says in the status bar why it cannot. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Cmd/Ctrl+Alt+. (`stroke.weightUp`, Stroke Weight Up) and Cmd/Ctrl+Alt+, (`stroke.weightDown`, Stroke Weight Down), the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) gives them, step the weight of each selected stroke from its own weight: by a quarter unit of Units › Stroke up to one unit, then by whole units, down to a quarter unit; with nothing selected they step the weight of the next object drawn (#5797). @@ -515,6 +519,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | +| History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | | Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | @@ -556,7 +561,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | @@ -636,6 +641,8 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index 7ee456a6c2..3caf8f4a81 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -5,8 +5,8 @@ //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` //! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` -//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and -//! `Function`), and print each one's counts. +//! tests, run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`) and the `test/built-ins/Promise` tests, and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256