diff --git a/ASSETS.md b/ASSETS.md index 9220086fa7..03f33d9a6e 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -33,7 +33,7 @@ Generated-in-code art is original and has no file to list. This covers the defau **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. -**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. +**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles. | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| diff --git a/Cargo.lock b/Cargo.lock index 6e9dee6f4b..53ddb08a11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8719,6 +8719,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", + "vectorcraft-eps", "vectorcraft-geom 0.24.1", "vectorcraft-metafile", "vectorcraft-pathops 0.24.1", diff --git a/NOTICE b/NOTICE index 99d05d6235..4d7c813796 100644 --- a/NOTICE +++ b/NOTICE @@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; web builds BIZ UDPGothic Regular only) under the SIL Open Font License 1.1. Their license texts ship with the release packages as OFL-.txt. +Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed +SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face. PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources), compiled into the app through the hayro-cmap crate under the BSD 3-Clause License: diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 5b5cec5a69..13ed5c8c9e 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -53,6 +53,20 @@ pub struct Pointers { /// The pen's pressure and end for the canvas, the source the install reads. // PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above. source: PenSource, + /// The pen whose finger wheel is read ([`Pointers::wheel`]). + wheel: Option, + /// Every reading written into the source, in order. + #[cfg(test)] + readings: Vec, +} + +/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential +/// pressure other than 0 since it came near. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Wheel { + id: i32, + eraser: bool, + reads: bool, } #[cfg(target_arch = "wasm32")] @@ -64,6 +78,11 @@ struct Input<'a> { id: i32, button: i16, pressure: f32, + /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. + tangential: f32, + /// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving + /// one element for another is still in its hover range. + entered: bool, modifiers: egui::Modifiers, } @@ -90,11 +109,29 @@ impl Pointers { self.source.clone() } - /// A pen moved or pressed with `pressure`, with the end it last pressed with. - fn pen_sample(&self, pressure: f32) { + /// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed + /// with. The source queues each reading, and the runtime pairs the readings with the frame's + /// pointer moves, so each move written after its own reading keeps that reading's wheel. + fn pen_sample(&mut self, pressure: f32, wheel: Option) { let mut sample = PointerSample::new(pressure); sample.eraser = self.eraser; + sample.wheel = wheel; self.source.set(Some(sample)); + #[cfg(test)] + self.readings.push(sample); + } + + /// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with + /// Pointer Events' `tangentialPressure` (−1..1, + /// ): a wheel of + /// 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 for a pen + /// without a wheel, so 0 reads as none until that pen, with that end, has reported a value + /// other than 0 since it came near. A value that is not a number is none. + fn wheel(&mut self, id: i32, tangential: f32) -> Option { + let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads); + let reads = known || (tangential.is_finite() && tangential != 0.0); + self.wheel = Some(Wheel { id, eraser: self.eraser, reads }); + (reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0) } fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { @@ -134,7 +171,10 @@ impl Pointers { } /// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe). - fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool { + /// + /// `coalesced` holds the positions the pen reported since the last event, each with its + /// pressure and tangential pressure, the last one at `pos`. + fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool { let id = e.id; if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { // Another pointer moved while no pen presses (a palm under a pen pressing is @@ -163,19 +203,24 @@ impl Pointers { if let Some(end) = end { self.eraser = end; } - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel); self.pen = Some(id); self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force); self.press(id, pos, button, e.modifiers); } "pointermove" if self.pen == Some(id) => { - self.pen_sample(e.pressure); // The positions the pen reported between two events (up to 240 a second - // on an iPad), each with its pressure, so fast strokes keep their curve. - for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) { - self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1)); - self.events.push(Event::PointerMoved(c.0)); + // on an iPad), each with its pressure and wheel, so fast strokes keep + // their curve. + for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) { + let wheel = self.wheel(id, tangential); + self.pen_sample(pressure, wheel); + self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure)); + self.events.push(Event::PointerMoved(at)); } + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel); self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force); self.events.push(Event::PointerMoved(pos)); } @@ -189,12 +234,19 @@ impl Pointers { } // Pointer Events report no end while a pen hovers: it keeps the end it // last pressed with. - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel); self.events.push(Event::PointerMoved(pos)); } "pointerup" | "pointercancel" if self.pen == Some(id) => { - let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel }; - self.pen_sample(0.0); + let (phase, wheel) = if kind == "pointerup" { + // Lifted, the pen hovers on and keeps what it read of its wheel. + (TouchPhase::End, self.wheel(id, e.tangential)) + } else { + self.wheel = None; + (TouchPhase::Cancel, None) + }; + self.pen_sample(0.0, wheel); self.pen = None; self.touch(PEN_DEVICE, id, phase, pos, None); self.release(pos, e.modifiers); @@ -204,6 +256,13 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } + // Left the hover range (a leave onto no element, on the canvas or off it) + // or canceled: the pen reads its wheel afresh. Moving onto another element + // keeps what it read. + let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel"; + if gone && self.wheel.is_some_and(|w| w.id == id) { + self.wheel = None; + } return self.pen.is_some(); } } @@ -276,7 +335,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, let z = runner.egui_ctx().zoom_factor(); let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z); let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z); - let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove" + let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove" && e.pointer_type() == "pen" // Safari before 17 hasn't it, and calling a missing method would abort the app. && js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false) @@ -284,7 +343,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, e.get_coalesced_events() .iter() .filter_map(|c| c.dyn_into::().ok()) - .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0))) + .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure())) .collect() } else { vec![] @@ -295,6 +354,8 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, id: e.pointer_id(), button: e.button(), pressure: e.pressure(), + tangential: e.tangential_pressure(), + entered: e.related_target().is_some(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -343,7 +404,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() } } fn reset() { @@ -505,6 +566,128 @@ mod tests { reset(); } + fn pen_at(button: i16, tangential: f32) -> Input<'static> { + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() } + } + + /// The wheels of the readings written since the last call, in order. + fn wheels(p: &mut Pointers) -> Vec> { + p.readings.drain(..).map(|s| s.wheel).collect() + } + + /// The wheel of the source's latest reading. + fn current_wheel(p: &Pointers) -> Option { + p.pen().current().and_then(|s| s.wheel) + } + + /// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the + /// source as 0..1 with each move, once the pen has reported a value other than 0. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + reset(); + let mut p = Pointers::default(); + assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] { + assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true)); + } + assert_eq!( + wheels(&mut p), + [None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)], + "none until reported; then 0 is half way, past the ends is clamped and not a number is none" + ); + assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), Some(0.5), "the lift keeps the wheel"); + reset(); + } + + /// The positions a fast stroke's event coalesced each get a reading with their own wheel and + /// pressure, in order, before their move, and the event's own position comes last with its own. + #[test] + fn coalesced_moves_keep_their_wheel() { + reset(); + let mut p = Pointers::default(); + let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0)); + assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true)); + let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)]; + assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true)); + let moved: Vec = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect(); + let kept = std::mem::take(&mut p.readings); + assert_eq!(moved, [Pos2::ZERO, a, b, c]); + assert_eq!(kept.iter().map(|s| s.wheel).collect::>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]); + assert_eq!(kept.iter().map(|s| s.pressure).collect::>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too"); + reset(); + } + + /// A pen that leaves the hover range, a canceled press, another pen and the other end each + /// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel. + #[test] + fn the_wheel_is_read_afresh_for_each_pen_and_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.pen(); + let learn = |p: &mut Pointers, button: i16| { + assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + }; + let hover = |p: &mut Pointers, id: i32| { + let mut e = pen_at(-1, 0.0); + e.id = id; + e.pressure = 0.0; + assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true)); + }; + learn(&mut p, 0); + hover(&mut p, 7); + assert_eq!(current_wheel(&p), Some(0.5), "a lift into hover keeps it"); + p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true); + hover(&mut p, 7); + assert_eq!(current_wheel(&p), None, "left the hover range"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), None, "a canceled press"); + hover(&mut p, 7); + assert_eq!(current_wheel(&p), None, "after a canceled press"); + learn(&mut p, 0); + hover(&mut p, 8); + assert_eq!(current_wheel(&p), None, "another pen"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), None, "the other end"); + assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + p.readings.clear(); + for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] { + let mut other = pen_at(0, 0.5); + (other.pointer_type, other.id) = (pointer_type, 10); + p.feed(kind, &other, Pos2::ZERO, &[], true); + assert_eq!(feed.current(), None, "{pointer_type} {kind}"); + assert!(p.readings.is_empty(), "{pointer_type} {kind}"); + } + reset(); + } + + /// A hovering pen that moves off the canvas onto another element and back keeps what it read + /// of its wheel; one that leaves the hover range off the canvas reads it afresh. + #[test] + fn the_wheel_survives_crossing_the_canvas_edge() { + reset(); + let mut p = Pointers::default(); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + let mut hover = pen_at(-1, 0.0); + hover.pressure = 0.0; + let mut onto = pen_at(-1, 0.0); + (onto.pressure, onto.entered) = (0.0, true); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false)); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), Some(0.5), "moved onto another element and back"); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + p.feed("pointerleave", &hover, Pos2::ZERO, &[], false); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), None, "left the hover range off the canvas"); + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index bc9945e513..1c3e7f39e7 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -69,7 +69,7 @@ vectorcraft-render = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSView", "NSWindow"] } # Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit. objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 83d488a243..b91282e7da 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -243,14 +243,3 @@ pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec) { } } } - -/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as -/// typed). winit's IME toggle only clears its own copy, so the IME would type it again. -#[cfg(target_os = "macos")] -fn discard_marked_text() { - if let Some(mtm) = objc2::MainThreadMarker::new() - && let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm) - { - ic.discardMarkedText(); - } -} diff --git a/apps/vectorcraft/src/launch_profile.rs b/apps/vectorcraft/src/launch_profile.rs index 2cc32f39dd..12615dd81d 100644 --- a/apps/vectorcraft/src/launch_profile.rs +++ b/apps/vectorcraft/src/launch_profile.rs @@ -124,10 +124,13 @@ pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: O /// The arguments a child of this process starts with: a nightly launch hands its profile on, so the /// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and /// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged. +/// Only `single_instance` starts a child, and macOS does not build it. +#[cfg(not(target_os = "macos"))] pub fn child_args(files: &[String]) -> Vec { child_args_for(current(), files) } +#[cfg(not(target_os = "macos"))] fn child_args_for(profile: &Profile, files: &[String]) -> Vec { let mut args: Vec = match profile { Profile::Stable => Vec::new(), @@ -245,12 +248,14 @@ mod tests { } } + #[cfg(not(target_os = "macos"))] #[test] fn a_stable_child_gets_the_file_delimiter_only() { let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]); assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"])); } + #[cfg(not(target_os = "macos"))] #[test] fn a_nightly_child_inherits_the_selected_profile() { let root = PathBuf::from(absolute()); diff --git a/apps/vectorcraft/tests/it/automation_args.rs b/apps/vectorcraft/tests/it/automation_args.rs index 4d33caaa82..2c4fd1ea60 100644 --- a/apps/vectorcraft/tests/it/automation_args.rs +++ b/apps/vectorcraft/tests/it/automation_args.rs @@ -1,5 +1,4 @@ use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; /// Invalid roots must exit before desktop initialization on every platform, including a CI /// machine with no display. A regression must fail rather than hang with a window open. @@ -7,9 +6,14 @@ fn rejects(args: &[&str], message: &str) { rejects_with_env(args, &[], message); } +/// Runs the desktop binary without a display, so on Linux a regression exits with a display +/// error, which the exact stderr check rejects, instead of opening a window. fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { - let mut child = Command::new(crate::bin()) + let child = Command::new(crate::bin()) .args(args) + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .env_remove("WAYLAND_SOCKET") .env_remove("VECTORCRAFT_CONTROL_PORT") .env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT") .env_remove("VECTORCRAFT_AUTOMATION_WRITE_ROOT") @@ -20,21 +24,7 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { .stderr(Stdio::piped()) .spawn() .unwrap(); - // Long enough for the binary to start on a loaded machine (the workspace's other tests run - // meanwhile), short enough to catch a desktop that started instead of exiting. - let deadline = Instant::now() + Duration::from_secs(30); - let timed_out = loop { - if child.try_wait().unwrap().is_some() { - break false; - } - if Instant::now() >= deadline { - child.kill().unwrap(); - break true; - } - std::thread::sleep(Duration::from_millis(10)); - }; - let out = child.wait_with_output().unwrap(); - assert!(!timed_out, "{args:?}: desktop started or did not exit promptly"); + let out = crate::exit_output(child, &format!("{args:?}: the desktop started instead of exiting")); assert!(!out.status.success(), "{args:?}"); assert!(out.stdout.is_empty(), "{args:?}: {:?}", out.stdout); // Exact stderr excludes unrelated startup warnings or display errors that could otherwise diff --git a/apps/vectorcraft/tests/it/help.rs b/apps/vectorcraft/tests/it/help.rs index 5f53f920b4..578defe6b4 100644 --- a/apps/vectorcraft/tests/it/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -1,15 +1,12 @@ //! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a //! terminal, SSH or an agent's shell it used to open the window (or hang without a display). -use std::io::Read; use std::process::{Command, Output, Stdio}; -use std::sync::mpsc; -use std::time::{Duration, Instant}; /// Runs the desktop binary without a display and with a control port it cannot parse, so a /// regression exits with that error instead of opening a window. fn run(args: &[&str], env: &[(&str, &str)]) -> Output { - let mut child = Command::new(crate::bin()) + let child = Command::new(crate::bin()) .args(args) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") @@ -22,28 +19,7 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output { .stderr(Stdio::piped()) .spawn() .unwrap(); - // Both pipes end when the binary exits, however long a loaded machine takes to start it. The - // deadline only stops a binary that is still running. - let deadline = Instant::now() + Duration::from_secs(120); - let stdout = read_to_end(child.stdout.take().unwrap()); - let stderr = read_to_end(child.stderr.take().unwrap()); - let recv = |rx: &mpsc::Receiver>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now())); - let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else { - child.kill().unwrap(); - panic!("{args:?}: the app started instead of printing its usage"); - }; - Output { status: child.wait().unwrap(), stdout, stderr } -} - -/// Reads `pipe` to its end on another thread. -fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver> { - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let mut buf = Vec::new(); - let _ = pipe.read_to_end(&mut buf); - let _ = tx.send(buf); - }); - rx + crate::exit_output(child, &format!("{args:?}: the app started instead of printing its usage")) } fn prints_usage(args: &[&str], env: &[(&str, &str)]) { diff --git a/apps/vectorcraft/tests/it/main.rs b/apps/vectorcraft/tests/it/main.rs index 658f4d49f6..441e994c66 100644 --- a/apps/vectorcraft/tests/it/main.rs +++ b/apps/vectorcraft/tests/it/main.rs @@ -2,6 +2,11 @@ // Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::Read; +use std::process::{Child, Output}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + mod automation_args; mod help; @@ -12,3 +17,70 @@ fn bin() -> std::path::PathBuf { .map(std::path::PathBuf::from) .unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into()) } + +/// Waits for `child`, spawned with piped stdout and stderr, to exit and returns its output. Both +/// pipes end when the binary exits, however long a loaded machine takes to start it. The deadline +/// only stops a binary that is still running: the test then fails with `started`. +fn exit_output(child: Child, started: &str) -> Output { + exit_output_by(child, started, Instant::now() + Duration::from_secs(120)) +} + +/// [`exit_output`] with the deadline given. A binary that has exited by the deadline passes even +/// when its output arrives after it; the output then has 10 seconds more to arrive. +fn exit_output_by(mut child: Child, started: &str, deadline: Instant) -> Output { + let stdout = read_to_end(child.stdout.take().unwrap()); + let stderr = read_to_end(child.stderr.take().unwrap()); + let (mut out, mut err) = (None, None); + if !receive([(&stdout, &mut out), (&stderr, &mut err)], deadline) && child.try_wait().unwrap().is_none() { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("{started}"); + } + receive([(&stdout, &mut out), (&stderr, &mut err)], Instant::now() + Duration::from_secs(10)); + let (Some(stdout), Some(stderr)) = (out, err) else { + panic!("{started}: the binary exited, but its output pipes stayed open"); + }; + Output { status: child.wait().unwrap(), stdout, stderr } +} + +/// A pipe's reader and the slot that holds its output once it arrives. +type Pipe<'a> = (&'a mpsc::Receiver>, &'a mut Option>); + +/// Fills each empty slot from its reader, waiting until `until` at the latest. Returns whether +/// every slot is filled. +fn receive(pipes: [Pipe<'_>; 2], until: Instant) -> bool { + let mut filled = true; + for (rx, slot) in pipes { + if slot.is_none() { + *slot = rx.recv_timeout(until.saturating_duration_since(Instant::now())).ok(); + } + filled &= slot.is_some(); + } + filled +} + +/// Reads `pipe` to its end on another thread. +fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = pipe.read_to_end(&mut buf); + let _ = tx.send(buf); + }); + rx +} + +/// A binary that exits before the deadline passes even when a process it started keeps its +/// output pipes open past the deadline. +#[cfg(unix)] +#[test] +fn exit_output_accepts_an_exit_whose_output_arrives_after_the_deadline() { + use std::process::{Command, Stdio}; + let mut child = + Command::new("sh").args(["-c", "sleep 1 & exit 0"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + // `sh` has exited; the `sleep` it started still holds both pipes for about a second. + child.wait().unwrap(); + let out = exit_output_by(child, "an exited binary was reported as running", Instant::now()); + assert!(out.status.success()); + assert!(out.stdout.is_empty() && out.stderr.is_empty()); +} diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 1a6ca42642..6cd009ca54 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1563,6 +1563,15 @@ fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) let decoration_sq = decoration_reach * decoration_reach; let mut near_decoration = false; for sp in &path.subpaths { + // A closed lone anchor has no segment, and a cap can draw a dot on it: the full check + // decides a click near it. + if sp.closed + && sp.segment_count() == 0 + && let Some(a) = sp.anchors.first() + && (a.p - p).hypot2() <= radius_sq.max(decoration_sq) + { + near_decoration = true; + } for i in 0..sp.segment_count() { let c = sp.segment(i); if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) { diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index e9d5296470..54ba72fe93 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, use blend_spec::{blend_color_shift, blend_ramp}; pub use envelope::{ EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds, - envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, - envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, + envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_margin_lengths, + envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, }; pub use expand::{ Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with, @@ -975,6 +975,17 @@ mod tests { assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round())); // Margins an `f32` can't hold are none. assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None); + // A straight line along an axis has margins across it, as shares of its length, and maps + // from its box with them; a point has none. + let line = + Node::path(NodeId(4), vectorcraft_geom::shapes::line(Point::new(10.0, 20.0), Point::new(110.0, 20.0)), crate::Appearance::default_art()); + let line = [Arc::new(line)]; + let stroked_line = Rect::new(10.0, 15.0, 110.0, 25.0); + let across = envelope_stroke_margin(stroked_line, Rect::new(10.0, 20.0, 110.0, 20.0)).unwrap(); + assert!(across[0] > 0.0 && across[1] > 0.0 && across[2] == 0.0 && across[3] == 0.0, "{across:?}"); + let from = src(&line, Affine::IDENTITY, EnvelopeOptions { bounds_margin: across, ..on }); + assert!((from.y0 - 15.0).abs() + (from.y1 - 25.0).abs() + (from.x0 - 10.0).abs() + (from.x1 - 110.0).abs() < 1e-4, "{from:?}"); + assert_eq!(envelope_stroke_margin(stroked_line, Rect::new(60.0, 20.0, 60.0, 20.0)), None); assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none()); let saved = serde_json::to_value(on).unwrap(); diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index a0ad0eb1e4..2fda2934b9 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -95,7 +95,9 @@ pub struct EnvelopeOptions { /// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art. pub distort_pattern_fills: bool, /// With Distort Appearance, how far the box the content maps from reaches past its geometric - /// bounds at the top, bottom, left and right, as shares of their height and width. An envelope + /// bounds at the top, bottom, left and right, as shares of their height and width; when the + /// height or width is shorter than 1e-6 pt, the margins along that side are shares of the other side + /// ([`envelope_margin_lengths`]). An envelope /// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes /// have none. Leaving Edit Contents measures them again when the strokes reach differently. #[serde(skip_serializing_if = "crate::skip::is_default")] @@ -140,7 +142,8 @@ impl EnvelopeOptions { if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) { return r; } - let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]); + let Some([v, _, h, _]) = envelope_margin_lengths(r) else { return r }; + let grown = crate::marks::outset(r, [top * v, bottom * v, left * h, right * h]); if grown.is_finite() { grown } else { r } } } @@ -457,19 +460,28 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect } } -/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for -/// content with no width or no height, or for margins an `f32` can't hold. +/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with +/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the +/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight +/// line along an axis has margins across it. `None` when neither side has a length. +pub fn envelope_margin_lengths(plain: Rect) -> Option<[f64; 4]> { + let long = |l: f64| l.is_finite() && l >= 1e-6; + let (h, w) = match (long(plain.height()), long(plain.width())) { + (true, true) => (plain.height(), plain.width()), + (false, true) => (plain.width(), plain.width()), + (true, false) => (plain.height(), plain.height()), + (false, false) => return None, + }; + Some([h, h, w, w]) +} + +/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`, as shares +/// of [`envelope_margin_lengths`]. `None` for content with neither a width nor a height, or for +/// margins an `f32` can't hold. pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> { - if plain.width() < 1e-6 || plain.height() < 1e-6 { - return None; - } - let margin = [ - (plain.y0 - stroked.y0) / plain.height(), - (stroked.y1 - plain.y1) / plain.height(), - (plain.x0 - stroked.x0) / plain.width(), - (stroked.x1 - plain.x1) / plain.width(), - ] - .map(|m| m as f32); + let [v, _, h, _] = envelope_margin_lengths(plain)?; + let margin = + [(plain.y0 - stroked.y0) / v, (stroked.y1 - plain.y1) / v, (plain.x0 - stroked.x0) / h, (stroked.x1 - plain.x1) / h].map(|m| m as f32); margin.iter().all(|m| m.is_finite()).then_some(margin) } diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 301a6002be..a7cd7986c4 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -498,6 +498,31 @@ fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() { } } +/// The dot a round or projecting cap draws for a closed lone anchor reaches half the stroke's +/// width round the anchor under every join, miter and bevel joins included, which measure the +/// stroke along its segments. +#[test] +fn a_lone_anchors_dot_reaches_half_the_stroke_width_under_every_join() { + use crate::appearance::{LineCap, LineJoin}; + use vectorcraft_geom::{Point, SubPath}; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + for join in [LineJoin::Miter, LineJoin::Bevel, LineJoin::Round] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let mut subpaths = square.subpaths.clone(); + subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], true)); + let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art()); + let s = p.appearance.stroke_mut().unwrap(); + (s.cap, s.join, s.width) = (cap, join, 4.0); + let visual = p.visual_bounds().unwrap(); + if cap == LineCap::Butt { + assert!(visual.x1 < 13.0, "{join:?} {cap:?}: the visual box {visual:?} reaches toward a lone anchor that draws nothing"); + } else { + assert!(visual.x1 >= 32.0 - 1e-9 && visual.y1 >= 10.0, "{join:?} {cap:?}: the visual box {visual:?} leaves out the dot's reach"); + } + } + } +} + /// A group's box from its members' boxes grows by the group's own strokes, leaves out members /// without a box, and is `None` when none has one. #[test] diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 0178af8460..d72048dc0a 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -17,15 +17,16 @@ //! other stop there, showing their previews). use std::borrow::Cow; +use std::cell::Cell; use std::collections::BTreeSet; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_geom::{Affine, PathData, Rect, SubPath}; -use vectorcraft_color::Paint; +use vectorcraft_color::{Color, Paint}; -use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; +use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; /// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or /// an EPS file's art, shown as one locked object. @@ -123,12 +124,27 @@ impl PlacedDocument { } /// The art the object shows, as plain objects with `n`'s id: one group, its resources named - /// as [`Document::with_placed_art`] adds them (nothing until that has read it). + /// as [`Document::with_placed_art`] adds them (nothing until that has read it). While + /// [`Crossed`] is on for this thread, its box crossed from corner to corner instead + /// ([`Self::crossed_art`]). pub fn art(&self, n: &Node) -> Vec { + if crossed() { + return vec![self.crossed_art(n)]; + } let prefix = prefix(&self.key); read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect() } + /// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the + /// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document + /// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art. + pub fn crossed_art(&self, n: &Node) -> Node { + let q = self.corners(); + let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]); + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))]) + } + /// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with /// `prefix`. fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option { @@ -470,6 +486,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc>) -> Option = const { Cell::new(false) }; +} + +/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed +/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the +/// file's art when made with `false`; once dropped, the setting before it applies again. A +/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images +/// in Outline Mode, so that effects and live objects make their art from the crossed box. +#[must_use] +pub struct Crossed(bool); + +impl Crossed { + pub fn set(on: bool) -> Self { + Self(CROSSED.with(|c| c.replace(on))) + } +} + +impl Drop for Crossed { + fn drop(&mut self) { + CROSSED.with(|c| c.set(self.0)); + } +} + +/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]). +pub fn crossed() -> bool { + CROSSED.with(Cell::get) +} + /// `p`'s file as read already (else its preview's), without reading it. pub fn read_cached(p: &PlacedDocument) -> Option> { let mut c = cache(); diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 8115d00954..f83b0e9329 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -291,9 +291,12 @@ impl StrokeLayer { // past them are measured. match self.body_along(&segs, side, out) { Some(body) => out = out.union(body), - // A subpath with no length paints at most its caps' dot. + // A subpath with no length paints at most its caps' dot. A closed subpath with + // no segment, a lone anchor, has its dot at that anchor under a round or + // projecting cap. None if !butt => { - let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)); + let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p)); + let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone); out = dot.map_or(out, |d| out.union(d.inflate(side, side))); } None => {} @@ -353,13 +356,18 @@ impl StrokeLayer { /// wider side of a farther one can paint past the nearest. pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { let reach = self.reach() + tol; - if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) { + if self.width.is_nan() || self.width <= 0.0 { return false; } + let els = bp.elements(); + // The box of the segments leaves out a closed subpath of one anchor, which has none: away + // from the segments only the dot a cap draws for such a subpath can paint. + if !bp.bounding_box().inflate(reach, reach).contains(p) { + return self.draws_dots() && subpaths(bp).into_iter().any(|(r, closed)| self.dot_contains(bp, rule, (&els[r], closed), p, tol)); + } if head_ends(self, bp).into_iter().any(|(at, out, end)| self.head_contains(at, out, end, p, tol)) { return true; } - let els = bp.elements(); // Aligned strokes paint on one side of the path only. let on_side = |region: Option, d: f64| region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside); // Every dash gets the caps, as wide as the stroke where the dash ends: round ones reach as @@ -371,7 +379,13 @@ impl StrokeLayer { LineCap::Square => Some(std::f64::consts::SQRT_2), }; for (r, closed) in subpaths(bp) { - let segs = drawn(&els[r]); + let segs = drawn(&els[r.clone()]); + if segs.is_empty() { + if self.dot_contains(bp, rule, (&els[r], closed), p, tol) { + return true; + } + continue; + } let (half, region) = self.body(closed); let full = half * self.profile_max() * dash_caps.unwrap_or(1.0); // Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile @@ -442,6 +456,32 @@ impl StrokeLayer { false } + /// Does this stroke draw a dot for a subpath that never leaves its first point? A round or a + /// projecting cap draws one on a stroke without a dash pattern or a width profile. + fn draws_dots(&self) -> bool { + self.cap != LineCap::Butt && self.profile.is_none() && !self.dash.as_ref().is_some_and(Dash::is_dashed) + } + + /// Is `p` within `tol` of the dot this stroke draws for the subpath `els` (`closed`: a closed + /// one) of `bp`, filled with `rule`, when every point of the subpath is its first point + /// ([`Self::draws_dots`])? A round cap draws a disc there and a projecting cap a square along + /// the x axis, as wide as the stroke's body ([`StrokeLayer::body`]). Inside and outside + /// strokes of a closed subpath paint on their own side of `bp` only. + fn dot_contains(&self, bp: &BezPath, rule: FillRule, (els, closed): (&[vectorcraft_geom::PathEl], bool), p: Point, tol: f64) -> bool { + if !self.draws_dots() || vectorcraft_geom::kurbo::segments(els.iter().copied()).any(|s| has_length(&s)) { + return false; + } + let Some(at) = els.first().and_then(vectorcraft_geom::PathEl::end_point) else { return false }; + let (half, region) = self.body(closed); + let v = p - at; + let d = v.hypot(); + let on_dot = match self.cap { + LineCap::Square => v.x.abs().max(v.y.abs()) <= half + tol, + _ => d <= half + tol, + }; + on_dot && region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside) + } + /// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]), /// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs` /// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of @@ -998,4 +1038,40 @@ mod tests { assert!(hit::hit_test(&d, Point::new(108.0, 150.0), opt).is_none(), "an unfilled interior"); assert_eq!(d.node(id).unwrap().visual_bounds(), Some(Rect::new(90.0, 90.0, 210.0, 210.0))); } + + /// A round cap draws a disc and a projecting cap a square on a subpath that never leaves its + /// first point, a closed lone anchor or a line to the same point: a click on it hits the path, + /// and one past it misses. A butt cap draws nothing there. + #[test] + fn clicks_hit_the_dot_of_a_lone_anchor() { + let at = Point::new(150.0, 120.0); + let mut lone = BezPath::new(); + lone.move_to(at); + lone.close_path(); + let mut zero = BezPath::new(); + zero.move_to(at); + zero.line_to(at); + let (on_edge, corner, past) = (Point::new(154.5, 120.0), Point::new(154.0, 124.0), Point::new(156.0, 120.0)); + for (name, bp) in [("closed lone anchor", &lone), ("zero-length line", &zero)] { + let round = stroke(10.0, |s| s.cap = LineCap::Round); + let square = stroke(10.0, |s| s.cap = LineCap::Square); + assert!(round.hits(bp, FillRule::NonZero, at, 0.1) && round.hits(bp, FillRule::NonZero, on_edge, 0.1), "{name}: round dot"); + assert!(!round.hits(bp, FillRule::NonZero, corner, 0.1) && !round.hits(bp, FillRule::NonZero, past, 0.1), "{name}: past the disc"); + assert!(square.hits(bp, FillRule::NonZero, corner, 0.1), "{name}: the square's corner"); + assert!(!square.hits(bp, FillRule::NonZero, past, 0.1), "{name}: past the square"); + assert!(!stroke(10.0, |_| {}).hits(bp, FillRule::NonZero, on_edge, 0.1), "{name}: a butt cap draws no dot"); + } + // In a document: a click on the dot of a closed lone anchor hits the path's stroke, and a + // marquee over the anchor selects it. + let mut d = Document::new(300.0, 300.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0); + ap.stroke_mut().unwrap().cap = LineCap::Round; + d.insert(Some(l), 0, Node::path(id, PathData::from_bezpath(&lone), ap)).unwrap(); + let opt = hit::HitOptions { tol: 0.5, ..Default::default() }; + let h = hit::hit_test(&d, Point::new(153.5, 121.0), opt).expect("a click on the dot"); + assert_eq!((h.leaf, h.kind), (id, hit::HitKind::Stroke)); + assert!(hit::hit_test(&d, Point::new(157.0, 120.0), opt).is_none(), "past the dot"); + assert_eq!(hit::marquee(&d, Rect::new(140.0, 110.0, 160.0, 130.0), None, false), vec![id]); + } } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 13a9c5c13b..8138474736 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -82,7 +82,7 @@ pub(crate) fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: & if !has_geometry(effects) || path.is_empty() { return (path.clone(), crate::Carry::default()); } - let b = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath()); + let b = path.bounds().unwrap_or_default(); apply_geometry_carrying(effects, path, b, ctx) } diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 02cf4b6205..5c31278493 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -58,10 +58,61 @@ pub fn raster_px_range(id: &str, key: &str) -> Option Option> { + let doc = catalog_index().get(id)?.params; + let starts = |at: usize| starts_key(doc, at); + doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { + let rest = doc.get(at + key.len()..)?; + let rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?; + for word in rest.split_whitespace() { + let opens = word.starts_with('('); + if let Some((lo, hi)) = word.trim_start_matches('(').split_once("..") { + let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches([',', ';', ')', '}']).parse::().ok()?); + return (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi); + } + if opens { + return None; + } + if word.ends_with([',', '}']) { + return None; + } + } + None + }) +} + +/// The choices parameter `key` of effect `id` is documented with (`key: "a"|"b"`, a note in +/// parentheses allowed after a choice: `key: "a" (note)|"b"`); `None` when its documentation gives +/// fewer than two. +pub(crate) fn documented_choices(id: &str, key: &str) -> Option> { + let doc = catalog_index().get(id)?.params; + doc.match_indices(key).map(|(at, _)| at).filter(|at| starts_key(doc, *at)).find_map(|at| { + let rest = doc.get(at + key.len()..)?; + let mut rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?; + let mut choices = vec![]; + while let Some((choice, after)) = rest.strip_prefix('"').and_then(|r| r.split_once('"')) { + choices.push(choice); + let after = match after.strip_prefix(" (") { + Some(note) => note.get(note.find(')')? + 1..)?, + None => after, + }; + match after.strip_prefix('|') { + Some(next) => rest = next, + None => break, + } + } + (choices.len() >= 2).then_some(choices) + }) +} + /// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`). fn documented_range(id: &str, key: &str, unit: &str) -> Option> { let doc = catalog_index().get(id)?.params; - let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); + let starts = |at: usize| starts_key(doc, at); let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { let rest = doc.get(at + key.len()..)?; rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ') @@ -71,6 +122,12 @@ fn documented_range(id: &str, key: &str, unit: &str) -> Option bool { + doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| matches!(c, '{' | ' ' | ',')) +} + /// The distance parameters of effect `id` (none for unknown effects). fn lengths_of(id: &str) -> Lengths { let always = |always| Lengths { always, absolute: &[] }; @@ -257,7 +314,7 @@ pub fn effect_catalog() -> Vec { "{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]]; placed gradients move and scale from the object's bounds to its distorted bounds)}", json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}), ), - g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})), + g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % -200..200 (0; -200 puckers, 200 bloats)}", json!({"amount": 0.0})), g( "distort.roughen", "Roughen…", @@ -808,7 +865,7 @@ pub fn effect_catalog() -> Vec { "adjust.temperatureTint", "Temperature/Tint…", ADJUST, - "{temperature: -100 (cooler) .. 100 (warmer) (0), tint: -100 (greener) .. 100 (more magenta) (0)} recolours as Brightness/Contrast does", + "{temperature: -100..100 (0; -100 cooler, 100 warmer), tint: -100..100 (0; -100 greener, 100 more magenta)} recolours as Brightness/Contrast does", json!({"temperature": 0.0, "tint": 0.0}), ), ]); diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index bcc2ce3804..f5344d1fb3 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -462,6 +462,7 @@ fn builds_within(id: &str) -> bool { fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData { use util::{join, num}; if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) { + crate::params::check_returned_effects(); let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage }; return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone()); } diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 74a24c2442..24b0e06ff3 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -350,7 +350,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { let mut m = src.clone(); if let Some((path, rule)) = geometry(src) { - let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath()); + let bounds = path.bounds().unwrap_or_default(); let (g, carry) = crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) }); m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false }; diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 216e541caf..f4d05db96f 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -135,6 +135,6 @@ pub use geometry::{ #[cfg(test)] pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within}; pub use params::{ - any_plugin_paints_output, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, is_raster, merged_params, - new_effect, plugin_revision, scale_effect, upgrade_params, + any_plugin_paints_output, check_returned_effect, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, + is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params, }; diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index d97c16b554..bd7237227b 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -139,6 +139,201 @@ pub fn new_effect(id: &str, params: &Value) -> Option { Some(Effect { id: id.to_string(), params, visible: true }) } +/// Checks an effect record that a painted live-effect plug-in returns on a piece, or on one of its +/// fills or strokes (`row`) ([`vectorcraft_plugins::painted::CheckEffect`]): a built-in effect other +/// than a 3D or Pathfinder effect, a raster effect only on a fill or stroke, and parameters that effect takes. A +/// parameter is one its defaults or its parameter documentation name, of the type its default has, +/// within the range its documentation gives ([`crate::catalog::any_documented_range`]) and one of the +/// choices it lists ([`crate::catalog::documented_choices`]); a texture is one as `effect.list` +/// gives it, and an SVG filter's XML one drawable filter. A plug-in effect, the plug-in itself +/// included, is refused, so the effects a plug-in returns never run a plug-in. +pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { + if e.id.starts_with(vectorcraft_plugins::effect::PREFIX) { + return Err("plug-in effects are not allowed in returned effects".into()); + } + let Some(info) = catalog_index().get(e.id.as_str()) else { + return Err(format!("unknown effect {:?}", e.id)); + }; + if is_three_d(&e.id) { + return Err("3D effects are not allowed in returned effects".into()); + } + if is_pathfinder(&e.id) { + return Err("Pathfinder effects are not allowed in returned effects; a piece is one path, with nothing to combine".into()); + } + if row && !is_raster(&e.id) { + return Err(format!("{:?} is not a raster effect; a fill or stroke takes raster effects only", e.id)); + } + let given = match &e.params { + Value::Null => return Ok(()), + Value::Object(m) => m, + _ => return Err("`params` must be an object".into()), + }; + let defaults = info.defaults.as_object(); + for (key, v) in given { + let default = defaults.and_then(|d| d.get(key)); + if default.is_none() && !documents_key(info.params, key) { + return Err(format!("`{key}` is not a parameter of {:?}", e.id)); + } + let kind = |v: &Value| std::mem::discriminant(v); + // A `color` is checked as a color, in any form the effect draws ([`is_color`]). + let color = key == "color" && default.is_some_and(Value::is_string); + // Curves' `points` is also taken as [[x, y], …], as the effect draws it. + let curve = e.id == "adjust.curves" && key == "points" && v.is_array(); + if let Some(d) = default + && !d.is_null() + && !color + && !curve + && kind(d) != kind(v) + { + return Err(format!("`{key}` must be of the type its default {d} has")); + } + let range = crate::catalog::any_documented_range(&e.id, key); + if let (Some(r), Some(x)) = (range, v.as_f64()) + && !r.contains(&x) + { + return Err(format!("`{key}` must be from {} to {}", r.start(), r.end())); + } + if let Some(choices) = crate::catalog::documented_choices(&e.id, key) + && !v.as_str().is_some_and(|v| choices.contains(&v)) + { + return Err(format!("`{key}` must be one of \"{}\"", choices.join("\", \""))); + } + } + if let Some(t) = given.get(crate::pixel::TEXTURE_IMAGE) + && t.as_str().is_none_or(|t| crate::pixel::texture(t).is_none()) + { + return Err("`textureImage` must be a texture as effect.list gives it".into()); + } + check_returned_values(&e.id, given) +} + +/// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in +/// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and +/// `name`; a Free Distort's four `corners`; Curves' `points` as pairs from 0 to 255; a Transform's whole +/// `copies` and `reference`; a Warp's `version`; a `color` the effect can draw; a +/// shadow's or glow's blend `mode`; a Levels or Curves `channel`; a Radial +/// Blur's center; and the type of each parameter without a default. +fn check_returned_values(id: &str, given: &Map) -> Result<(), String> { + let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number()); + let switch = |key: &str| given.get(key).is_some_and(|v| !v.is_boolean()); + if id == crate::SVG_FILTER { + if let Some(xml) = given.get("xml") { + crate::svg_filter::check(xml.as_str().ok_or("`xml` must be a string")?)?; + } + if given.get("scale").is_some_and(|s| !s.as_f64().is_some_and(|k| (0.001..=1000.0).contains(&k))) { + return Err("`scale` must be a number from 0.001 to 1000".into()); + } + if given + .get("origin") + .is_some_and(|o| !o.as_array().is_some_and(|o| o.len() == 2 && o.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)))) + { + return Err("`origin` must be [x, y] in points".into()); + } + if given.get("axes").is_some_and(|a| crate::svg_filter::valid_axes(a).is_none()) { + return Err("`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0".into()); + } + if given.contains_key("name") && !given.contains_key("xml") { + return Err("an SVG filter is named by its id: give `xml` with `name`".into()); + } + } + let pair = |p: &Value| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))); + if id == "distort.freeDistort" && given.get("corners").is_some_and(|c| !c.as_array().is_some_and(|c| c.len() == 4 && c.iter().all(pair))) { + return Err("`corners` must be four [x, y] pairs of numbers".into()); + } + if id == "adjust.curves" && given.get("points").is_some_and(|p| !is_curve_points(p)) { + return Err("`points` must be \"x,y x,y …\" or [[x, y], …] pairs of numbers from 0 to 255".into()); + } + if id == "distort.transform" + && let Some(key) = ["copies", "reference"].into_iter().find(|k| given.get(*k).and_then(Value::as_f64).is_some_and(|x| x.fract() != 0.0)) + { + return Err(format!("`{key}` must be a whole number")); + } + if id.starts_with("warp.") && given.get("version").is_some_and(|v| crate::warp_version(v).is_none()) { + return Err(format!("`version` must be 0 or {}", crate::WARP_NET)); + } + let takes_color = catalog_index().get(id).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string)); + if takes_color && given.get("color").is_some_and(|v| !is_color(v)) { + return Err("`color` must be a #rrggbb color, [r, g, b] from 0 to 1 or a color object".into()); + } + let takes_blend_mode = catalog_index().get(id).is_some_and(|info| info.params.contains("mode: blend mode")); + if takes_blend_mode && given.get("mode").is_some_and(|v| v.as_str().and_then(crate::raster::named_blend_mode).is_none()) { + return Err("`mode` must be a blend mode, such as \"multiply\" or \"screen\"".into()); + } + if matches!(id, "adjust.levels" | "adjust.curves") && given.get("channel").is_some_and(|v| !v.as_str().is_some_and(crate::is_channel)) { + return Err(format!("`channel` must be one of {}", crate::CHANNELS.join(", "))); + } + if id == "blur.radial" { + for key in ["centerX", "centerY"] { + if given.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) { + return Err(format!("`{key}` must be a number from 0 to 1")); + } + } + } + let numbers: &[&str] = match id { + "stylize.scribble" => &["variation"], + "path.outlineStroke" => &["width"], + _ => &[], + }; + if let Some(key) = numbers.iter().find(|k| number(k)) { + return Err(format!("`{key}` must be a number")); + } + if id == "blur.gaussian" && switch("linear") { + return Err("`linear` must be true or false".into()); + } + Ok(()) +} + +/// Can Curves read `v` as its `points`: `"x,y x,y …"` (pairs split by whitespace or `;`) or +/// `[[x, y], …]`, each number from 0 to 255? +fn is_curve_points(v: &Value) -> bool { + let level = |x: f64| (0.0..=255.0).contains(&x); + match v { + Value::String(s) => s + .split(|c: char| c.is_whitespace() || c == ';') + .filter(|p| !p.is_empty()) + .all(|p| p.split_once(',').is_some_and(|(x, y)| [x, y].into_iter().all(|n| n.trim().parse::().is_ok_and(level)))), + Value::Array(a) => a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|n| n.as_f64().is_some_and(level)))), + _ => false, + } +} + +/// Can an effect read `v` as its `color`: a hex color or name [`Color::from_hex`] reads, `[r, g, b]` +/// with three numbers from 0 to 1 first, or a color object with its components from 0 to 1 (a Lab +/// color's lightness from 0 to 100, and finite a and b)? +/// +/// [`Color::from_hex`]: vectorcraft_doc::color::Color::from_hex +fn is_color(v: &Value) -> bool { + use vectorcraft_doc::color::Color; + let unit = |x: f32| (0.0..=1.0).contains(&x); + match v { + Value::String(s) => Color::from_hex(s).is_some(), + Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|c| c.as_f64().is_some_and(|c| (0.0..=1.0).contains(&c))), + Value::Object(_) => match serde_json::from_value::(v.clone()) { + Ok(Color::Rgb { r, g, b }) => [r, g, b].into_iter().all(unit), + Ok(Color::Cmyk { c, m, y, k }) => [c, m, y, k].into_iter().all(unit), + Ok(Color::Gray { k }) => unit(k), + Ok(Color::Lab { l, a, b }) => (0.0..=100.0).contains(&l) && a.is_finite() && b.is_finite(), + Err(_) => false, + }, + _ => false, + } +} + +/// Does parameter documentation `doc` (`{edgeWidth: pt 1..14 (2), …}`) name parameter `key`? +fn documents_key(doc: &str, key: &str) -> bool { + doc.match_indices(key).any(|(at, _)| { + let before = doc.get(..at).and_then(|s| s.chars().last()); + let after = doc.get(at + key.len()..).unwrap_or_default(); + matches!(before, Some('{' | ' ' | ',' | '|')) && (after.starts_with(':') || after.starts_with('?')) + }) +} + +/// Makes [`check_returned_effect`] how this process checks the effect records painted live-effect +/// plug-ins return ([`vectorcraft_plugins::painted::set_effect_check`]). +pub(crate) fn check_returned_effects() { + vectorcraft_plugins::painted::set_effect_check(check_returned_effect); +} + /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see /// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which /// keep their share of the object so. A distance left at its default is written out scaled; one diff --git a/crates/effects/src/preview.rs b/crates/effects/src/preview.rs index 8d330a606b..9f7e36a429 100644 --- a/crates/effects/src/preview.rs +++ b/crates/effects/src/preview.rs @@ -435,7 +435,7 @@ fn reshapes(n: &Node) -> bool { fn path_art(n: &Node) -> Option { let (path, rule) = leaf_geometry(n)?; let ctx = GeomContext::of(n); - let g = apply_geometry_with(&n.appearance.effects, &path, path.to_bezpath().bounding_box(), &ctx); + let g = apply_geometry_with(&n.appearance.effects, &path, path.bounds().unwrap_or_default(), &ctx); let piece = |geometry: PathData, items: Vec| { let mut ap: Appearance = (*n.appearance).clone(); ap.items = items; @@ -454,7 +454,7 @@ fn path_art(n: &Node) -> Option { if own.is_empty() || plain.iter().any(|i| paints(i)) { pieces.push(piece(g.clone(), plain.into_iter().cloned().collect())); } - let bounds = g.to_bezpath().bounding_box(); + let bounds = g.bounds().unwrap_or_default(); for item in own { let geometry = apply_geometry_with(item.effects(), &g, bounds, &ctx.item(item)); pieces.push(piece(geometry, vec![item.clone()])); diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index 6948d0f977..c72391e56d 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -365,8 +365,13 @@ impl Rasterize { /// Parse a blend mode name (`"multiply"`, `"Screen"`, `"color-burn"`…). pub fn blend_mode(s: &str) -> BlendMode { + named_blend_mode(s).unwrap_or(BlendMode::Normal) +} + +/// The blend mode `s` names as [`blend_mode`] reads it; `None` when it names none. +pub(crate) fn named_blend_mode(s: &str) -> Option { let key: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); - BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key).unwrap_or(BlendMode::Normal) + BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key) } /// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object). diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index ee68067d2f..4d1c7b420f 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; use vectorcraft_doc::live::Hooks; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params}; @@ -659,7 +659,7 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { let fx = item.effects(); let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + crate::apply_geometry_bez(fx, &g, vectorcraft_geom::path::anchored_curve_bounds(&g).unwrap_or_default(), &ctx.item(item)) } else { g.clone() }; @@ -1260,7 +1260,7 @@ fn as_art_opts( ) -> Option { if let Some(t) = copied_raster_at(n) { let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart); - return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n)); + return copied_raster_art(paint_doc, n, t, (apart, true), &outlined, None).map(|art| dressed_keeping_effects(art, n)); } let fx = geometry_effects(n); let mut art = match &n.kind { @@ -1382,13 +1382,26 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node { /// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through /// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame /// and an instance as its symbol's art, whose members take their own geometry effects first -/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art. -fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option) -> Option { +/// ([`crate::group::members_as_drawn`]). With `items`, the pieces a path's fills and strokes make +/// of it ([`transform_items`]) are made before it is copied; without, its fills and strokes keep +/// their effects for their own stage. Given `check`, a budget and a flag, the art keeps to that +/// budget in place of [`Budget::EFFECTS`], and the flag is set to `false` when an effect leaves a +/// path with its shape or makes fewer copies than it asks for ([`reshape_leaves_checked`]); the +/// art is then incomplete. `None` when `outlined` gives no art. +fn copied_raster_art( + doc: Option<&Document>, + n: &Node, + t: usize, + (apart, items): (bool, bool), + outlined: &dyn Fn(&Node) -> Option, + mut check: Option<(Budget, &mut bool)>, +) -> Option { + let budget = check.as_ref().map_or(Budget::EFFECTS, |(b, _)| *b); let (before, rest) = n.appearance.effects.split_at(t); let mut source = n.clone(); source.appearance.effects = before.to_vec(); let piece = match copied_raster_at(&source) { - Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?, + Some(at) => copied_raster_art(doc, &source, at, (apart, items), outlined, check.as_mut().map(|(b, c)| (*b, &mut **c)))?, None if needs_outline(&source) => { let mut art = outlined(&source)?; if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() { @@ -1404,11 +1417,15 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou None => { let mut art = one_piece(&source); let rows = has_copied_row_raster(&source); - let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc); + let fx = geometry_effects(&source); + let carry = + reshape_leaves_checked(&mut art, &fx, &source.appearance.effects, budget, (apart, rows), doc, check.as_mut().map(|(_, c)| &mut **c)); if apart { hoist_copies(&mut art); } - transform_items(&mut art, doc); + if items { + transform_items(&mut art, doc); + } let mut ran = source.appearance.effects.clone(); if carry.skipped() { carry.hide_skipped(&mut ran); @@ -1425,8 +1442,13 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou // The raster effects follow the copies below; Scale Strokes & Effects scales the others. let mut scaling = copy_scaling(options); scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); - let max = Budget::EFFECTS.at_least(art_cost(&art)); + let max = budget.at_least(art_cost(&art)); copy_art(&mut art, m, copies, scaling, max); + if let Some((_, complete)) = check.as_mut() + && art.children().map_or(0, Vec::len) <= copies + { + **complete = false; + } if let Some(children) = art.children_mut() { // The original is last, and each copy above it is mapped once more by `m`. let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); @@ -1445,7 +1467,8 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou } } let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); - let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc); + let rows = has_copied_row_raster(n); + let carry = reshape_leaves_checked(&mut art, &later, &n.appearance.effects, budget, (apart, rows), doc, check.map(|(_, c)| c)); let mut ran = n.appearance.effects.clone(); if carry.skipped() { carry.hide_skipped(&mut ran); @@ -1493,7 +1516,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option return None; } if let Some(t) = copied_raster_at(n) { - return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n)); + return copied_raster_art(doc, n, t, (false, true), &|_| None, None).map(|art| dressed_keeping_effects(art, n)); } if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) { // One element: its pieces never knock each other out. @@ -1625,12 +1648,27 @@ fn hoist_copies(art: &mut Node) { /// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked /// masks keeps its shape under that effect. fn reshape_leaves_apart( + art: &mut Node, + fx: &[&Effect], + owner: &[Effect], + budget: Budget, + flags: (bool, bool), + doc: Option<&Document>, +) -> crate::Carry { + reshape_leaves_checked(art, fx, owner, budget, flags, doc, None) +} + +/// [`reshape_leaves_apart`] that, given `complete`, stops at the first effect that leaves a path in +/// the art with its shape or makes fewer copies than it asks for, past `budget` ([`Ran::kept`], +/// [`Ran::short`]), and sets `complete` to `false`; the art is then partly reshaped. +fn reshape_leaves_checked( art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, (apart, rows): (bool, bool), doc: Option<&Document>, + mut complete: Option<&mut bool>, ) -> crate::Carry { let mut whole = crate::Carry::default(); if fx.is_empty() { @@ -1668,11 +1706,18 @@ fn reshape_leaves_apart( let params = merged_params(&e.id, &e.params); // Where a live-effect plug-in sits, which it is listed by when it is deferred. let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); - let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held }; + let strict = complete.is_some(); + let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held, strict }; // Art with linked masks keeps its shape under an effect that a mask in it could not take // as the art it masks did, so no mask is left apart from its art. let before = masked.then(|| (art.clone(), used)); let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0); + if (ran.kept || ran.short) + && let Some(complete) = complete.as_deref_mut() + { + *complete = false; + return whole; + } if (ran.masks || ran.short) && let Some((was, cost)) = before { @@ -1704,7 +1749,8 @@ fn reshape_leaves_apart( /// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of /// each linked mask before the first effect, by the id of the object it masks, and whether one of /// the object's effects holds the raster effects in its art back from its Transform effects -/// ([`follow_art`]). +/// ([`follow_art`]), and whether a Transform effect that makes fewer copies of anything in the art +/// than it asks for is reported ([`Ran::short`]) wherever it is (`strict`). struct Step<'a> { e: &'a Effect, params: &'a serde_json::Value, @@ -1716,6 +1762,7 @@ struct Step<'a> { doc: Option<&'a Document>, wholes: &'a HashMap, held: bool, + strict: bool, } /// What [`Step::run`] did to a piece of art. @@ -1728,7 +1775,8 @@ struct Ran { /// took the effect, or could have ([`Step::reshape_masks`]). masks: bool, /// A Transform effect made fewer copies of a path, image or symbol instance than it asks for - /// (past the budget or out of reach), where a linked mask could take a different number. + /// (past the budget or out of reach), where a linked mask could take a different number, or + /// anywhere in the art for a [`Step`] with `strict`. short: bool, /// How what paints the art as a whole follows the effect, when it does. whole: Option, @@ -1840,7 +1888,8 @@ impl Step<'_> { { if !own { *used = copy_art(art, m, copies, copy_scaling(options), max); - return Ran { kept: false, took: true, masks: false, short: false, whole: None }; + let short = self.strict && art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies); + return Ran { kept: false, took: true, masks: false, short, whole: None }; } // A mask's art: its copies keep to what the rest of the art leaves of `max`, and the // linked mask of the art itself takes them too. That mask's art stays in `used`, as @@ -1861,7 +1910,7 @@ impl Step<'_> { if watch && !own { masked_ids(art, false, &mut covered); } - let counts = |id: NodeId| watch && (own || covered.contains(&id)); + let counts = |id: NodeId| self.strict || (watch && (own || covered.contains(&id))); let mut short = false; let mut took = false; for_each_leaf(art, &mut |leaf| { @@ -1902,7 +1951,7 @@ impl Step<'_> { if options.objects { moved_ids.insert(leaf.id); } - short |= counts(leaf.id) && copied(leaf) <= copies; + short |= copies > 0 && counts(leaf.id) && copied(leaf) <= copies; } else { kept_ids.insert(leaf.id); } @@ -2517,7 +2566,8 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling /// path or compound path, as one of its object's effects with reference box `bounds`: `leaf` /// becomes a group with its id and name of one object for each piece returned, in order, each with /// the piece's geometry and the leaf's appearance with the piece's fills and strokes in place of -/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces +/// its own ([`vectorcraft_plugins::painted::appearance`]), and the piece's opacity, blending mode +/// and effects ([`dress_piece`]). The swatches and patterns the pieces /// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost /// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are /// refused, or they would pass `budget`. A deferred run is listed by `at`. @@ -2531,28 +2581,112 @@ fn paint_leaf( at: Option, ) -> Option { let (path, rule) = leaf_geometry(leaf)?; + crate::params::check_returned_effects(); let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; - let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); + let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { return None; } - let children = pieces - .iter() - .map(|p| { - let mut one = leaf.clone(); - one.name = None; - one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into(); - set_geometry(&mut one, p.path.clone(), p.rule); - Arc::new(one) - }) - .collect(); + let mut children = Vec::with_capacity(pieces.len()); + for p in pieces.iter() { + let mut one = leaf.clone(); + one.name = None; + one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into(); + set_geometry(&mut one, p.path.clone(), p.rule); + // The pieces' own geometry effects keep to what the pieces before them leave of the budget. + made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?); + children.push(Arc::new(one)); + } let mut g = Node::group(leaf.id, children); g.name = leaf.name.clone(); *leaf = g; Some(made) } +/// Gives `one`, the object a painted piece becomes, the piece's `look`: its opacity times the +/// object's, its blending mode, and its effects after the object's own. The visible geometry effects +/// among them, and only those, reshape the piece at once ([`reshape_leaves_checked`], with `doc`), so they run +/// before the source's later effects and the effects of its fills and strokes stay for their own +/// stage; the object becomes a group with its id around the reshaped piece, carrying its +/// transparency and effects. The piece's raster effects stay on it and draw on it, except that when +/// they are listed before a Transform effect that makes copies ([`copied_raster_at`]), each copy +/// carries its own, moved, turned, reflected and scaled with it ([`copied_raster_art`]). When the object +/// has a blending mode other than Normal and the piece gives one, the same one included, the object +/// becomes a group with its blending mode around the piece, so both apply. Returns what the reshaped piece costs +/// past its own path; `None` when its geometry effects would cost more than `room` past it: they stop at the first +/// effect that does not fit, and `one` is then incomplete. +pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, room: Budget, doc: Option<&Document>) -> Option { + use vectorcraft_doc::color::BlendMode; + let none = Budget { anchors: 0, lines: 0 }; + if look.is_empty() { + return Some(none); + } + let outer = look.blend.filter(|_| one.blend != BlendMode::Normal).map(|_| one.blend); + if let Some(o) = look.opacity { + one.opacity *= o; + } + if let Some(b) = look.blend { + one.blend = b; + } + // A Transform effect that makes copies, with raster effects listed before it: each copy is an + // object of its own carrying those raster effects, as an object's copies are + // ([`copied_raster_art`]). The object's own effects paint around all of them, then the piece's + // from the Transform effect on. + let mut probe = one.clone(); + probe.appearance.effects = look.effects.clone(); + let mut extra = none; + if let Some(t) = copied_raster_at(&probe) { + let before = art_cost(one); + let mut complete = true; + let art = copied_raster_art(doc, &probe, t, (false, false), &|_| None, Some((room.plus(before), &mut complete)))?; + #[cfg(test)] + DRESSED.with(|d| d.set(d.get().plus(art_cost(&art)))); + extra = art_cost(&art).minus(before); + if !complete || !room.fits(extra) { + return None; + } + let mut effects = std::mem::take(&mut one.appearance.effects); + effects.extend(art.appearance.effects.iter().cloned()); + let mut art = dressed(art, one); + art.appearance.effects = effects; + *one = art; + } else { + let shape: Vec = look.effects.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect(); + // The raster effects before a Transform effect follow it, as an object's do once its + // geometry effects are applied ([`crate::raster::without_geometry`]); hidden records stay + // as they are. + one.appearance.effects.extend(crate::raster::followed(&look.effects).iter().filter(|e| !(e.visible && is_geometry(&e.id))).cloned()); + if !shape.is_empty() { + let before = art_cost(one); + let mut art = one_piece(one); + let mut complete = true; + reshape_leaves_checked(&mut art, &shape.iter().collect::>(), &shape, room.plus(before), (false, false), doc, Some(&mut complete)); + #[cfg(test)] + DRESSED.with(|d| d.set(d.get().plus(art_cost(&art)))); + extra = art_cost(&art).minus(before); + if !complete || !room.fits(extra) { + return None; + } + let mut art = dressed(art, one); + art.appearance.effects = one.appearance.effects.clone(); + *one = art; + } + } + if let Some(blend) = outer { + let mut g = Node::group(one.id, vec![Arc::new(one.clone())]); + g.blend = blend; + *one = g; + } + Some(extra) +} + +#[cfg(test)] +thread_local! { + /// What the art [`dress_piece`] has reshaped on this thread has cost, all together. + pub(crate) static DRESSED: std::cell::Cell = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) }; +} + /// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the /// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most /// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths. @@ -2572,7 +2706,8 @@ fn piece_share() -> Budget { /// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index` /// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of /// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills -/// and strokes; one that gives none keeps the leaf's. Returns +/// and strokes; one that gives none keeps the leaf's. Each path takes its piece's opacity, blending +/// mode and effects ([`dress_piece`]). Returns /// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, /// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass /// `budget`. A deferred run is listed by `at`. @@ -2588,9 +2723,10 @@ fn paint_piece( at: Option, ) -> Option { let (path, rule) = leaf_geometry(leaf)?; + crate::params::check_returned_effects(); let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; - let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); + let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { return None; } @@ -2613,6 +2749,7 @@ fn paint_piece( let mut one = leaf.clone(); one.appearance.items = items; set_geometry(&mut one, p.path.clone(), p.rule); + made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?); children.push(Arc::new(one)); } *leaf = Node::group(leaf.id, children); @@ -2691,7 +2828,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let Some((path, rule)) = leaf_geometry(leaf) else { return }; let original = leaf.clone(); let ctx = GeomContext::of(&original); - let bounds = path.to_bezpath().bounding_box(); + let bounds = path.bounds().unwrap_or_default(); // A path of the leaf's geometry painted by `items` alone, without the leaf's transparency and // object effects (the group keeps them). let piece = |items: Vec| { @@ -2766,18 +2903,34 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let it = one.items.pop().unwrap_or(it); let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) }; let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) }; + crate::params::check_returned_effects(); let painted = vectorcraft_plugins::effect::apply_painted(plugin, ¶ms, &g, tb, rule, paints, doc) - .map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::>()) + .map(|pieces| { + pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::>() + }) .filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus))); - // A failed run draws the fill or stroke on the geometry it was given. - let returned = painted.unwrap_or_else(|| vec![(g.clone(), rule, vec![it])]); - let mut group: Vec> = vec![]; - for (path, rule, items) in returned.into_iter().filter(|(_, _, items)| !items.is_empty()) { - *used = used.plus(piece_cost(&path)); - let mut p = piece(items); - set_geometry(&mut p, path, rule); - group.push(Arc::new(p)); - } + // The paths the pieces become, with their own geometry effects applied, and what they + // cost; `None` as soon as a piece's own geometry effects would pass `room`. + let build = |returned: Vec<(PathData, FillRule, Vec, vectorcraft_plugins::painted::Look)>| { + let returned: Vec<_> = returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()).collect(); + let mut made = returned.iter().map(|(path, ..)| piece_cost(path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); + let mut group: Vec> = vec![]; + for (path, rule, items, look) in returned { + let mut p = piece(items); + set_geometry(&mut p, path, rule); + made = made.plus(dress_piece(&mut p, &look, room.minus(made), doc)?); + group.push(Arc::new(p)); + } + Some((group, made)) + }; + // A failed run, or pieces whose own geometry effects would pass the budget, draws the + // fill or stroke on the geometry it was given, at that geometry's own cost. + let (group, made) = painted.and_then(build).unwrap_or_else(|| { + let mut p = piece(vec![it]); + set_geometry(&mut p, g.clone(), rule); + (vec![Arc::new(p)], piece_cost(&g)) + }); + *used = used.plus(made); let mut p = Node::group(leaf.id, group); transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc); pieces.push(Arc::new(p)); diff --git a/crates/effects/src/stroke/tests_reach.rs b/crates/effects/src/stroke/tests_reach.rs index 5c66c9fe9d..c222e53734 100644 --- a/crates/effects/src/stroke/tests_reach.rs +++ b/crates/effects/src/stroke/tests_reach.rs @@ -38,6 +38,12 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) { let painted = region.bounding_box(); let bounds = st.bounds_on(bp, bp.bounding_box()); assert!(bounds.inflate(0.05, 0.05).contains_rect(painted), "{what}: paints {painted:?} outside {bounds:?}"); + check_clicks(bp, st, ®ion, what); +} + +/// Check that points of `region`, what `st` paints along `bp`, hit as [`check`] says. +fn check_clicks(bp: &BezPath, st: &StrokeLayer, region: &BezPath, what: &str) { + let painted = region.bounding_box(); let tol = if st.profile.is_some() { 1.0 } else { 0.25 }; // Off the outline's own coordinates, so no sample sits level with a vertex. let (mut x, mut checked) = (painted.x0 + 0.371, 0); @@ -45,7 +51,7 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) { let mut y = painted.y0 + 0.293; while y <= painted.y1 { let p = Point::new(x, y); - if fill_contains(®ion, FillRule::EvenOdd, p) { + if fill_contains(region, FillRule::EvenOdd, p) { assert!(st.hits(bp, FillRule::NonZero, p, tol), "{what}: painted {p:?} doesn't hit"); checked += 1; } @@ -140,6 +146,58 @@ fn custom_heads() -> Vec { vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])] } +/// Paths with a subpath that never leaves its first point, which a round or projecting cap draws +/// as a dot at (140, 130): a closed lone anchor, a line to the same point, open and closed, and a +/// curve with every handle on the point, alone and after a closed triangle. +fn dot_paths() -> Vec { + let at = Point::new(140.0, 130.0); + let mut lone = BezPath::new(); + lone.move_to(at); + lone.close_path(); + let mut line = BezPath::new(); + line.move_to(at); + line.line_to(at); + let mut closed_line = line.clone(); + closed_line.close_path(); + let mut curve = BezPath::new(); + curve.move_to(at); + curve.curve_to(at, at, at); + curve.close_path(); + let mut beside = paths()[2].clone(); + beside.extend(lone.iter()); + vec![lone, line, closed_line, curve, beside] +} + +/// A click on the dot a round or projecting cap draws for a subpath that never leaves its first +/// point hits the path, and where no dot is drawn (butt caps, dashes, width profiles, an inside +/// stroke of a closed subpath) a click beside the point misses. +#[test] +fn clicks_hit_the_dot_a_cap_draws_for_a_subpath_with_no_length() { + let beside = Point::new(142.0, 130.0); + let mut painted = 0; + for (pi, bp) in dot_paths().iter().enumerate() { + for align in [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + for profile in [None, Some(WidthProfile::lens())] { + for dash in [None, Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false })] { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 6.0); + (st.align, st.cap, st.profile, st.dash) = (align, cap, profile.clone(), dash.clone()); + let what = format!("path {pi} {align:?} {cap:?} profile {} dashed {}", profile.is_some(), dash.is_some()); + let region = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath(); + if !fill_contains(®ion, FillRule::EvenOdd, beside) { + assert!(!st.hits(bp, FillRule::NonZero, beside, 0.25), "{what}: a click beside the point hits, where no dot is drawn"); + continue; + } + painted += 1; + check_clicks(bp, &st, ®ion, &what); + } + } + } + } + } + assert_eq!(painted, 22, "dots drawn"); +} + #[test] fn bounds_and_clicks_cover_every_arrowhead() { let bp = &paths()[0]; diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index f6afd42b7c..07efb0c8bd 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -6,6 +6,7 @@ use super::*; mod clipfx; mod imageoutline; +mod loneanchor; mod painted; mod rasterfollow; mod scale; diff --git a/crates/effects/src/tests/loneanchor.rs b/crates/effects/src/tests/loneanchor.rs new file mode 100644 index 0000000000..6b1b571364 --- /dev/null +++ b/crates/effects/src/tests/loneanchor.rs @@ -0,0 +1,118 @@ +//! Geometry effects on a path with a lone anchor work from the path's bounds with that anchor +//! included ([`PathData::bounds`]), as the selection's box, Align and Transform Each measure the +//! path, wherever the effects are applied. + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol}; + +use super::*; + +/// A 10 pt line from the origin and a lone anchor at (100, 50): its bounds are (0, 0) to +/// (100, 50), and the line alone measures (0, 0) to (10, 0). +fn marked() -> PathData { + PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false), + SubPath::polyline(&[Point::new(100.0, 50.0)], false), + ]) +} + +/// The Transform effect at 200%, about the center of the box it is given. +fn scale() -> Effect { + fx("distort.transform", json!({"scaleH": 200, "scaleV": 200})) +} + +/// `marked` with a 1 pt black stroke, and `scale` on the object (`on_stroke` false) or on its +/// stroke. +fn node(on_stroke: bool) -> Node { + let mut n = Node::path(NodeId(5), marked(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + if on_stroke { + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(scale()); + } + } else { + n.appearance.effects.push(scale()); + } + n +} + +/// The first point of each subpath of each path under `n`. +fn starts(n: &Node, out: &mut Vec) { + if let NodeKind::Path { path, .. } = &n.kind { + out.extend(path.subpaths.iter().filter_map(|s| s.anchors.first()).map(|a| a.p)); + } + for c in n.children().into_iter().flatten() { + starts(c, out); + } +} + +/// Does a path under `n` start where the line scaled about (50, 25) starts, (-50, -25), and +/// none where the line scaled about its own center (5, 0) starts, (-5, 0)? +fn scaled_about_the_bounds(n: &Node) -> bool { + let mut pts = vec![]; + starts(n, &mut pts); + let at = |x: f64, y: f64| pts.iter().any(|p| close(p.x, x, 1e-6) && close(p.y, y, 1e-6)); + assert_eq!(apply_geometry(&[scale()], &marked(), marked().bounds().unwrap()).subpaths[0].anchors[0].p, Point::new(-50.0, -25.0)); + at(-50.0, -25.0) && !at(-5.0, 0.0) +} + +#[test] +fn expand_appearance_scales_about_bounds_with_the_lone_anchor() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + d.insert(Some(l), 0, node(false)).unwrap(); + let baked = bake_document(&d).expect("the effect bakes"); + let layer = &baked.layers[0]; + assert!(scaled_about_the_bounds(layer), "{layer:?}"); +} + +/// A stroke's Transform effect with Scale Strokes & Effects on makes the stroke a path of its own +/// when the object's own effects are reshaped, its geometry after the stroke's effects before it. +#[test] +fn a_stroke_effect_scales_about_bounds_with_the_lone_anchor() { + let mut n = node(true); + n.appearance.effects = vec![fx("distort.transform", json!({}))]; + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(fx("distort.transform", json!({"strokes": true}))); + } + let art = reshape(None, &n, None).expect("the effects make art"); + assert!(scaled_about_the_bounds(&art), "{art:?}"); +} + +#[test] +fn shape_art_scales_about_bounds_with_the_lone_anchor() { + let art = shape_art(None, &node(false), None).expect("the effect makes art"); + assert!(scaled_about_the_bounds(&art), "{art:?}"); +} + +#[test] +fn preview_art_scales_about_bounds_with_the_lone_anchor() { + let d = Document::new(200.0, 200.0); + let symbols = d.symbol_boxes(); + for on_stroke in [false, true] { + let art = crate::preview::drawn_art(&symbols, &node(on_stroke)).expect("the effect makes art"); + assert!(scaled_about_the_bounds(&art), "on the stroke {on_stroke}: {art:?}"); + } +} + +#[test] +fn an_instance_paints_its_art_scaled_about_bounds_with_the_lone_anchor() { + let mut d = Document::new(200.0, 200.0); + d.symbols.push(Symbol { dynamic: false, name: "s".into(), art: Arc::new(node(true)) }); + let mut inst = Node::new(NodeId(9), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + inst.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + if let Some(s) = inst.appearance.stroke_mut() { + s.effects.push(fx("distort.transform", json!({}))); + } + let painted = image_paint(Some(&d), &inst); + let pts: Vec = painted + .iter() + .filter_map(|(bp, _, _)| match bp.elements().first() { + Some(vectorcraft_geom::PathEl::MoveTo(p)) => Some(*p), + _ => None, + }) + .collect(); + assert!(pts.iter().any(|p| close(p.x, -50.0, 1e-6) && close(p.y, -25.0, 1e-6)), "{pts:?}"); + assert!(!pts.iter().any(|p| close(p.x, -5.0, 1e-6) && close(p.y, 0.0, 1e-6)), "{pts:?}"); +} diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 31dadc865e..f04f56425f 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -8,7 +8,7 @@ use vectorcraft_plugins::wat as tpl; use crate::geometry::Budget; use crate::reshape; -use crate::reshape::{HELD_PEAK, PLUGIN_RUNS}; +use crate::reshape::{DRESSED, HELD_PEAK, PLUGIN_RUNS}; /// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id: /// its effect returns `output` whatever it is given. @@ -268,3 +268,449 @@ fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() { let height = |b: Option| b.map_or(0.0, |b| b.height()); assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds()); } + +/// The host takes a built-in effect with parameters it has, of their type and in range, on a piece, +/// and a raster effect on a fill or stroke; it refuses a plug-in effect, a 3D effect, a Pathfinder +/// effect (a piece is one path, with nothing to combine), an unknown effect or parameter, a value +/// of another type or out of range, and a geometry effect on a fill or stroke. +#[test] +fn returned_effects_are_built_in_effects_with_their_own_parameters() { + let e = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true }; + let check = crate::check_returned_effect; + assert_eq!(check(&e("path.offsetPath", json!({"offset": 4.0})), false), Ok(())); + assert_eq!(check(&e("path.offsetPath", serde_json::Value::Null), false), Ok(())); + assert_eq!(check(&e("stylize.dropShadow", json!({"x": 2.0})), true), Ok(())); + assert_eq!(check(&e("brushStrokes.accentedEdges", json!({"edgeWidth": 14.0})), false), Ok(())); + assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(())); + // A parameter documented right after a comma has its range checked too. + assert_eq!(check(&e("artistic.paintDaubs", json!({"sharpness": 25})), false), Ok(())); + // Each documented choice and each end of a documented range passes. + for (id, params) in [ + ("distort.roughen", json!({"points": "smooth"})), + ("distort.roughen", json!({"points": "corner"})), + ("distort.zigZag", json!({"points": "corner"})), + ("distort.puckerBloat", json!({"amount": -200})), + ("distort.puckerBloat", json!({"amount": 200})), + ("adjust.temperatureTint", json!({"temperature": -100, "tint": 100})), + ("stylize.dropShadow", json!({"mode": "color-burn"})), + ("stylize.outerGlow", json!({"mode": "Normal"})), + // A `color` is also taken as [r, g, b] 0..1 or a color object, as the effects draw it. + ("stylize.dropShadow", json!({"color": [1.0, 0.0, 0.0]})), + ("stylize.dropShadow", json!({"color": [1, 0, 0]})), + ("stylize.outerGlow", json!({"color": {"model": "gray", "k": 0.5}})), + ("stylize.innerGlow", json!({"color": {"model": "cmyk", "c": 0, "m": 1, "y": 0, "k": 0}})), + ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 100, "a": -128, "b": 127}})), + // Curves' `points` is also taken as [[x, y], …], and a Transform's whole numbers as such. + ("adjust.curves", json!({"points": [[0, 255], [255, 0]]})), + ("adjust.curves", json!({"points": "0,0; 64,32 255,255"})), + ("distort.transform", json!({"copies": 2, "reference": 0.0})), + ] { + assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}"); + } + // Every effect's own defaults pass the check, so each documented range holds its default. + for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id) && !crate::is_pathfinder(i.id)) { + assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id); + } + for (effect, row) in [ + (e("distort.transform", json!({"copies": 1001})), false), + (e("path.offsetPath", json!({"offset": null})), false), + (e("plugin.test.effects.self", json!({})), false), + (e("threeD.extrude", json!({})), false), + (e("pathfinder.add", serde_json::Value::Null), false), + (e("pathfinder.divide", json!({"precision": 1.0})), false), + (e("stylize.nope", json!({})), false), + (e("path.offsetPath", json!({"inset": 4.0})), false), + (e("path.offsetPath", json!({"offset": "4"})), false), + (e("brushStrokes.accentedEdges", json!({"edgeWidth": 15.0})), false), + (e("artistic.paintDaubs", json!({"sharpness": 41})), false), + (e("path.offsetPath", json!([4.0])), false), + (e("path.offsetPath", json!({"offset": 4.0})), true), + ] { + assert!(check(&effect, row).is_err(), "{effect:?} on a fill or stroke: {row}"); + } + let why = check(&e("pathfinder.add", serde_json::Value::Null), false).unwrap_err(); + assert!(why.contains("Pathfinder effects are not allowed"), "{why}"); + // The values checked for one effect are refused with the parameter named. + for (id, params, key) in [ + (crate::SVG_FILTER, json!({"axes": [1, 0, 0, 0]}), "axes"), + (crate::SVG_FILTER, json!({"scale": 0.0}), "scale"), + (crate::SVG_FILTER, json!({"origin": [1.0]}), "origin"), + (crate::SVG_FILTER, json!({"name": "f"}), "name"), + ("warp.arc", json!({"version": 99}), "version"), + ("stylize.dropShadow", json!({"color": "#zz0000"}), "color"), + ("stylize.dropShadow", json!({"color": [1.0, "0", 0.0]}), "color"), + ("stylize.innerGlow", json!({"color": {"model": "rgb"}}), "color"), + ("stylize.outerGlow", json!({"color": true}), "color"), + // Color components are from 0 to 1, Lab's lightness from 0 to 100. + ("stylize.dropShadow", json!({"color": [2, -1, 0]}), "color"), + ("stylize.dropShadow", json!({"color": [0.5, 0.5, 1.01]}), "color"), + ("stylize.outerGlow", json!({"color": {"model": "rgb", "r": 2.0, "g": 0.0, "b": 0.0}}), "color"), + ("stylize.innerGlow", json!({"color": {"model": "gray", "k": -0.5}}), "color"), + ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 101, "a": 0, "b": 0}}), "color"), + ("adjust.curves", json!({"points": [[0, 255], [255]]}), "points"), + ("adjust.curves", json!({"points": ["0,0", "255,255"]}), "points"), + // Curves' points are read as "x,y" or [x, y] pairs, each number from 0 to 255. + ("adjust.curves", json!({"points": "not-points"}), "points"), + ("adjust.curves", json!({"points": "0,0 255,-1"}), "points"), + ("adjust.curves", json!({"points": [[0, 300], [255, 0]]}), "points"), + ("distort.transform", json!({"copies": 1.5}), "copies"), + ("distort.transform", json!({"reference": 4.5}), "reference"), + ("adjust.levels", json!({"channel": "cyan"}), "channel"), + ("blur.radial", json!({"centerX": 1.5}), "centerX"), + ("blur.gaussian", json!({"linear": 1}), "linear"), + ("pixelate.colorHalftone", json!({"channel1": 400.0}), "channel1"), + ("distort.twist", json!({"angle": 4000.0}), "angle"), + ("distort.freeDistort", json!({"corners": []}), "corners"), + ("distort.freeDistort", json!({"corners": [[0, 0], [1, 0], [1, 1], [0]]}), "corners"), + ("distort.roughen", json!({"points": "invalid"}), "points"), + ("distort.zigZag", json!({"points": "Corner"}), "points"), + ("path.offsetPath", json!({"joins": "square"}), "joins"), + (crate::RASTERIZE, json!({"colorModel": "cmyk"}), "colorModel"), + (crate::CROP_MARKS, json!({"style": 1}), "style"), + ("distort.puckerBloat", json!({"amount": -201}), "amount"), + ("distort.puckerBloat", json!({"amount": 201}), "amount"), + ("adjust.temperatureTint", json!({"temperature": 101}), "temperature"), + ("adjust.temperatureTint", json!({"tint": -101}), "tint"), + ("stylize.dropShadow", json!({"mode": "not-a-mode"}), "mode"), + ("stylize.innerGlow", json!({"mode": "???"}), "mode"), + ] { + let why = check(&e(id, params.clone()), false).expect_err(&format!("{id} {params}")); + assert!(why.contains(key), "{id} {params}: {why}"); + } +} + +/// A painted effect on a fill whose piece fits the budget, but whose piece's own Transform copy +/// would not fit beside the source: the fill is drawn on the source's path, and nothing is drawn +/// where the piece would be. +#[test] +fn a_piece_s_own_geometry_effects_keep_to_the_budget() { + let id = "test.effects.look.budget"; + let source = drawn_share(0.45, 0.0); + let piece = json!({"path": drawn_share(0.3, 2_000.0), "effects": [{"id": "distort.transform", "params": {"copies": 1, "moveH": 10.0}}]}); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = Node::path(NodeId(9), source.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + let art = reshape(None, &n, None).unwrap(); + let mut bounds = vec![]; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + bounds.push(b); + } + }); + assert!(!bounds.is_empty() && bounds.iter().all(|b| b.x1 < 2_000.0), "{bounds:?}"); + vectorcraft_plugins::registry::remove(id); +} + +/// Where [`many_heavy_pieces`] puts its effect. +#[derive(Clone, Copy, Debug)] +enum HeavyOn { + /// The object's own effects. + Object, + /// The square's fill, as its only effect. + Fill, + /// The square's fill, after a painted effect that returns the square. + LaterOnFill, +} + +/// Ten painted pieces, each drawn with 4% of the effects' budget, each with a Transform effect that +/// makes 14 copies of it (60% of the budget per piece), from an effect on a square `on`: they would +/// pass the budget together, so the square is drawn as it was. The pieces' own geometry effects keep +/// to what the pieces before them left: the art reshaped for them costs less than the budget +/// together, and so does the art drawn. +fn many_heavy_pieces(on: HeavyOn) { + let id = format!("test.effects.look.heavy{on:?}").to_lowercase(); + let pieces: Vec<_> = (0..10) + .map(|k| json!({"path": drawn_share(0.04, 1_000.0 * f64::from(k)), "effects": [{"id": "distort.transform", "params": {"copies": 14, "moveH": 10.0}}]})) + .collect(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": pieces }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)); + let first = format!("{id}.first"); + install_painting(&first, &json!({"objects": [{"path": square}]})); + let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let heavy = Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }; + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + match on { + HeavyOn::Object => n.appearance.effects.push(heavy), + HeavyOn::Fill => n.appearance.items[fill].effects_mut().push(heavy), + HeavyOn::LaterOnFill => { + n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{first}"), params: json!({}), visible: true }); + n.appearance.items[fill].effects_mut().push(heavy); + } + } + DRESSED.with(|d| d.set(Budget { anchors: 0, lines: 0 })); + let art = reshape(None, &n, None).unwrap(); + let dressed = DRESSED.with(std::cell::Cell::get); + assert!(Budget::EFFECTS.fits(dressed), "{on:?}: the pieces' own effects made {dressed:?}"); + let (mut bounds, mut drawn) = (vec![], Budget { anchors: 0, lines: 0 }); + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + bounds.push(p.bounds()); + drawn = drawn.plus(Budget::of(p)); + } + }); + // On a fill, the fill and the stroke are paths of their own. + assert!(!bounds.is_empty() && bounds.iter().all(|b| *b == square.bounds()), "{on:?}: {bounds:?}"); + assert!(Budget::EFFECTS.fits(drawn), "{on:?}: the art costs {drawn:?}"); + vectorcraft_plugins::registry::remove(&id); + vectorcraft_plugins::registry::remove(&first); +} + +/// [`many_heavy_pieces`] from the object's own effect. +#[test] +fn heavy_pieces_of_an_object_s_effect_stop_within_the_budget() { + many_heavy_pieces(HeavyOn::Object); +} + +/// [`many_heavy_pieces`] from an effect on a fill. +#[test] +fn heavy_pieces_of_a_fill_s_effect_stop_within_the_budget() { + many_heavy_pieces(HeavyOn::Fill); +} + +/// [`many_heavy_pieces`] from a later effect on a fill. +#[test] +fn heavy_pieces_of_a_later_effect_on_a_fill_stop_within_the_budget() { + many_heavy_pieces(HeavyOn::LaterOnFill); +} + +/// A piece's own geometry effect reshapes it before the source's later effects run, and those run +/// on it once: the square at 120, 40 grown by a 10 pt Offset Path, then moved 100 pt right by the +/// source's Transform effect. The piece's opacity and blending mode stay on the path it becomes. +#[test] +fn later_source_effects_run_after_generated_effects_once() { + let id = "test.effects.look.offset"; + let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5, "blend": "Multiply", + "effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]}); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.appearance.effects.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + n.appearance.effects.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + let art = reshape(None, &n, None).unwrap(); + let (mut paths, mut looks) = (vec![], vec![]); + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + paths.push(p.bounds()); + } + if c.opacity != 1.0 || c.blend != vectorcraft_doc::color::BlendMode::Normal { + looks.push((c.opacity, c.blend)); + } + }); + assert_eq!(paths.len(), 1, "{paths:?}"); + // Once, on the piece and what holds it. + assert_eq!(looks, [(0.5, vectorcraft_doc::color::BlendMode::Multiply)]); + let b = paths[0].unwrap(); + assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}"); + vectorcraft_plugins::registry::remove(id); +} + +/// A piece's look reshapes it by its own geometry effects alone: the Transform effect of the fill +/// it carries stays on the fill for its own stage and does not move the piece now. +#[test] +fn a_piece_s_look_runs_only_its_own_geometry_effects() { + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + n.appearance.items[fill].effects_mut().push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + let look = vectorcraft_plugins::painted::Look { + effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }], + ..Default::default() + }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); + let mut paths = vec![]; + n.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + paths.push((b, c.appearance.items.iter().map(|i| i.effects().len()).sum::())); + } + }); + assert_eq!(paths.len(), 1, "{paths:?}"); + let (b, kept) = paths[0]; + assert!((b.x0 + 10.0).abs() < 0.5 && (b.x1 - 30.0).abs() < 0.5, "{b:?}"); + assert_eq!(kept, 1, "the fill keeps its Transform effect"); +} + +/// A piece's blending mode on an object that blends in the same mode keeps both: the object +/// becomes a group in its mode around the piece in the piece's. +#[test] +fn a_piece_s_blending_mode_nests_in_the_object_s_same_mode() { + use vectorcraft_doc::color::BlendMode; + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.blend = BlendMode::Multiply; + let look = vectorcraft_plugins::painted::Look { blend: Some(BlendMode::Multiply), ..Default::default() }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); + let mut blends = vec![]; + n.walk(&mut |c| blends.push(c.blend)); + assert_eq!(blends, [BlendMode::Multiply, BlendMode::Multiply]); +} + +/// A piece with an opacity, a blending mode and a geometry effect draws them once: the group the +/// reshaped piece becomes carries them, and the path inside it draws at full opacity in Normal. +#[test] +fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() { + use vectorcraft_doc::color::BlendMode; + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let look = vectorcraft_plugins::painted::Look { + opacity: Some(0.5), + blend: Some(BlendMode::Screen), + effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }], + }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); + let (mut opacity, mut blends) = (1.0f32, vec![]); + n.walk(&mut |c| { + opacity *= c.opacity; + if c.blend != BlendMode::Normal { + blends.push(c.blend); + } + }); + assert!((opacity - 0.5).abs() < 1e-6, "{opacity}"); + assert_eq!(blends, [BlendMode::Screen]); +} + +/// A piece's raster effect listed before its Transform effect follows the Transform, as an +/// object's does: a Drop Shadow before a scale of 200% keeps twice its offset. A hidden record +/// stays as it is. +#[test] +fn a_piece_s_raster_effects_follow_its_transform_effect() { + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let hidden = Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: false }; + let look = vectorcraft_plugins::painted::Look { + effects: vec![ + Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true }, + hidden.clone(), + Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true }, + ], + ..Default::default() + }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); + let mut kept = vec![]; + n.walk(&mut |c| kept.extend(c.appearance.effects.iter().cloned())); + let shadow = kept.iter().find(|e| e.id == "stylize.dropShadow").expect("the piece keeps its Drop Shadow"); + let at = |k: &str| shadow.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN); + assert!((at("x") - 6.0).abs() < 1e-9 && (at("y") - 8.0).abs() < 1e-9, "{shadow:?}"); + assert_eq!(kept.iter().filter(|e| **e == hidden).count(), 1, "{kept:?}"); + assert!(kept.iter().all(|e| e.id != "distort.transform"), "{kept:?}"); +} + +/// A piece's raster effect listed before a Transform effect that makes copies goes on each copy, +/// as an object's does: every copy carries its own Drop Shadow, scaled with it, and the art around +/// the copies carries none. +#[test] +fn each_copy_of_a_piece_carries_its_own_raster_effects() { + let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true }; + let copying = Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200, "copies": 1}), visible: true }; + let square = + || Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + // The offsets of the Drop Shadows the nodes under `art` carry, and how many `art` itself + // carries. + let shadows = |art: &Node| { + let offsets = |c: &Node| { + c.appearance + .effects + .iter() + .filter(|e| e.id == "stylize.dropShadow") + .map(|e| { + let at = |k: &str| e.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN); + ((at("x") * 1000.0).round() as i64, (at("y") * 1000.0).round() as i64) + }) + .collect::>() + }; + let mut inside = vec![]; + for c in art.children().into_iter().flatten() { + c.walk(&mut |d| inside.extend(offsets(d))); + } + inside.sort_unstable(); + (inside, offsets(art).len()) + }; + let mut object = square(); + object.appearance.effects = vec![shadow.clone(), copying.clone()]; + let expected = shadows(&crate::reshape::own_effects_art(None, &object).expect("the object's copies are drawn")); + assert_eq!(expected.0.len(), 2, "{expected:?}"); + assert_eq!(expected.1, 0, "{expected:?}"); + let mut n = square(); + let look = vectorcraft_plugins::painted::Look { effects: vec![shadow, copying], ..Default::default() }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed"); + assert_eq!(shadows(&n), expected); +} + +/// A piece whose copies, each with its own raster effects, would pass the room left to it is +/// refused rather than drawn with fewer copies than its Transform effect asks for. +#[test] +fn a_piece_s_copies_with_raster_effects_keep_to_its_room() { + let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)); + let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let look = vectorcraft_plugins::painted::Look { + effects: vec![ + Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true }, + Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 5}), visible: true }, + ], + ..Default::default() + }; + // Room for one more square: not for five. + assert!(crate::reshape::dress_piece(&mut n, &look, Budget::of(&square), None).is_none()); +} + +/// A piece's Transform effect with no copies and Scale Strokes & Effects on moves the piece: no +/// copies were asked for, so none are missing. +#[test] +fn a_piece_s_transform_without_copies_scaling_strokes_moves_it() { + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let look = vectorcraft_plugins::painted::Look { + effects: vec![Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 0, "strokes": true}), visible: true }], + ..Default::default() + }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed"); + let mut paths = vec![]; + n.walk(&mut |c| paths.extend(c.path_data().and_then(PathData::bounds))); + assert_eq!(paths.len(), 1, "{paths:?}"); + assert!((paths[0].x0 - 30.0).abs() < 0.5 && (paths[0].x1 - 50.0).abs() < 0.5, "{paths:?}"); +} + +/// The same on a fill: the plug-in and the Transform effect after it are the fill's. The piece's +/// Offset Path runs on it alone, so the plug-in runs once and the square moves once. +#[test] +fn a_fill_s_later_effects_run_after_its_piece_s_effects_once() { + let id = "test.effects.look.rowoffset"; + let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5, + "effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]}); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + let fx = n.appearance.items[fill].effects_mut(); + fx.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + fx.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + let art = reshape(None, &n, None).unwrap(); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) + && c.appearance.items.iter().any(|i| i.is_fill() && crate::paints(i)) + { + paths.push(b); + } + }); + assert_eq!(paths.len(), 1, "{paths:?}"); + let b = paths[0]; + assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}"); + vectorcraft_plugins::registry::remove(id); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6732c973f4..eb751c26d2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -120,8 +120,10 @@ vectorcraft-testkit = { workspace = true } proptest = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -# How many times an open reads a PDF. +# How many times an open reads a PDF, and the work its import takes. vectorcraft-pdf = { workspace = true, features = ["read-count"] } +# The work `.ai` blends take to be checked and made live. +vectorcraft-eps = { workspace = true, features = ["work-count"] } # How many times the symbol list is read to find symbols by name, and how many objects are # measured against locked artboards. vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fbe46f41c8..36eb9f0d0f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -964,6 +964,8 @@ pub use variablecmds::utf16_order_without_mark; /// file: its size limit, its text, its cells and the data `graph.setData` takes from them. pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +/// The kind of variable that drives an object's content (`variable.setBinding`). +pub(crate) use variablecmds::content_kind; /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 580f2d7a30..c787ba68cd 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -38,7 +38,7 @@ mod dynamic; mod symbolism; mod symbols; -pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; +pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint}; use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..efcb425091 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -766,10 +766,12 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and +/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its -/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. -fn frame_marker(n: &Node) -> Option { +/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing +/// and that has no other appearance. +pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| match i { @@ -781,7 +783,9 @@ fn frame_marker(n: &Node) -> Option { let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; let at_corners = sp.anchors.len() == 4 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)) + // Each side, the closing one included, joins two corners that share an edge. + && sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y); (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index aa3cf36cba..56cf4f5b96 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1601,7 +1601,8 @@ impl Clipboard { /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's /// filter of its name; one that draws another definition than that filter takes the document's /// filter when pasted back into the document it came from, and elsewhere keeps its own under a - /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would + /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an + /// effect of the document that draws the same definition under a name no filter has gives that name. When that name would /// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else /// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits. fn filter_links(&self, d: &Document, same_doc: bool) -> Result> { @@ -1627,6 +1628,8 @@ impl Clipboard { } let mut taken: BTreeSet = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect(); let mut effects_read = false; + // The filter effects of the document, by name and definition. + let mut held_effects = BTreeSet::new(); let mut links = BTreeMap::new(); for (name, xml) in found { let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue }; @@ -1640,14 +1643,28 @@ impl Clipboard { effects_read = true; for root in d.art_roots() { node_filter_names(root, &mut taken); + node_filters(root, &mut held_effects); } for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) { node_filter_names(a, &mut taken); + node_filters(a, &mut held_effects); } for g in &d.graphic_styles { appearance_filter_names(&g.appearance, &mut taken); + appearance_filters(&g.appearance, &mut held_effects); } } + // An effect of the document that already draws this filter under a name no filter + // of the document has (one pasted or loaded before) gives its name, so pasting or + // loading the same filter again adds no other name. + let earlier = held_effects.iter().find(|(n, x)| { + !d.svg_filters.iter().any(|f| &f.name == n) + && vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x) + }); + if let Some((n, x)) = earlier { + links.insert((name, xml), (n.clone(), x.clone())); + continue; + } // Free names made from the starts of the name, longest first, then free letters and // digits, then other single printable ASCII characters: the first under which the // filter still draws. @@ -1845,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, let clip = Clipboard::with_used(src, &used, &library, vec![]); let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::>()); let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + // Graphs in the symbols added draw with the designs `d` kept, as pasted ones do. + crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs); let mut placed: Vec = vec![]; for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] { for s in list { @@ -1857,6 +1876,35 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, Ok(placed) } +/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the +/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as +/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to +/// them (a resource `d` has under the same name and with the same contents is used; another is +/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s; +/// an SVG filter whose name `d` gives another filter is renamed). +pub(crate) fn import_looks( + src: &Document, + d: &mut Document, + look: &Appearance, + attrs: &Map, +) -> Result<(Appearance, Map)> { + let library = OnceCell::new(); + let defs = Defs::of(src, &library); + let mut used = Used::default(); + used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]); + // The look goes on an empty path, so that its SVG filters are renamed where `d` gives their + // names other filters, as a pasted object's are. + let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone()); + let clip = Clipboard::with_used(src, &used, &library, vec![carrier]); + let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + // Graphs in the symbols added draw with the designs `d` kept, as pasted ones do. + crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs); + let (mut look, mut attrs) = (look.clone(), attrs.clone()); + out.relink.appearance(&mut look); + out.relink.attrs(&mut attrs); + Ok((look, attrs)) +} + /// The resources graph designs `names` of `src` use, through the definitions they lead to. fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used { let mut used = Used::default(); diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 5344159583..1ed09da2ee 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -593,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap, c /// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks, /// effect colors and the series paints and label styles that graphs keep included), symbols, /// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included), -/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and -/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art -/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern -/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray +/// graphic styles (their effects included), brushes (their art and a Hue Shift key color), +/// character and paragraph styles (their fill and stroke) and swatches through the color settings +/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and +/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of +/// graphic styles, brushes and text styles convert without being counted. Gray /// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any /// other and separate through the CMYK profile, unless `grays` puts them on the black plate /// ([`mode_converter`]). Lab colors @@ -608,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - convert_colors(d, &mode_converter(mode, intent, grays)) + let conv = mode_converter(mode, intent, grays); + let changed = convert_colors(d, &conv); + convert_style_colors(d, &conv); + changed } /// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index 1815e33349..b9f304ddf4 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result Result<()> { +pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> { if fonts.len() > COMPOSITE_FONTS_MAX { return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); } @@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec) -> Result<() if before == after { return Ok(()); } + let changed = register(s, &before, &after); + let r = s.edit(label, |d, _| set_fonts(d, &after, &changed)); + sync(s); + r +} + +/// Before an edit makes `after` the active document's composite fonts (it has `before`), register +/// them in the font database and forget the ones taken out → the lowercased names of the fonts that +/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not. +pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec { let changed: Vec = before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect(); // A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name // listed here that the document doesn't define. s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase())); let db = FontDb::global(); - for f in &before { + for f in before { if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) { db.remove_composite_font(&f.name); } } - for f in &after { + for f in after { db.set_composite_font(f); } - let r = s.edit(label, |d, _| { - *d.composite_fonts = after.clone(); - each_text_mut(d, &mut |t| { - if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { - refresh_bounds(t); - } - Ok(()) - }) - }); - sync(s); - r + changed +} + +/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again. +pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> { + *d.composite_fonts = after.to_vec(); + each_text_mut(d, &mut |t| { + if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { + refresh_bounds(t); + } + Ok(()) + }) +} + +/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts +/// adds a font. +pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec { + let mut after = fonts.to_vec(); + match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { + Some(a) => *a = f.clone(), + None => after.push(f.clone()), + } + after } fn set(s: &mut Session, p: &Value) -> Result { @@ -377,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result { if apply { let mut after = s.doc()?.doc.composite_fonts.to_vec(); for f in &fonts { - match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { - Some(a) => *a = f.clone(), - None => after.push(f.clone()), - } + after = with_font(&after, f); } check_set(&after, C)?; replace(s, "Import Composite Fonts", after)?; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 45242affa3..5ac5a3bb51 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6013,6 +6013,58 @@ fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_tha assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); } +/// A symbol a loaded look or text style brings, through the pattern it paints with, draws its +/// graph with the document's design of that name, as a pasted one does. +#[test] +fn a_symbol_a_loaded_look_or_text_style_brings_draws_its_graph_with_the_documents_design() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].clone(); + src.execute("object.pattern.make", &json!({"name": "Charts", "edit": false, "ids": [instance]})).unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [r]})).unwrap(); + let t = src.execute("text.create", &json!({"x": 10, "y": 80, "text": "Charts"})).unwrap()["id"].clone(); + src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [t]})).unwrap(); + src.execute("charStyle.new", &json!({"name": "Charted", "id": t})).unwrap(); + let source = (*src.doc().unwrap().doc).clone(); + let look = source.node(NodeId(r)).unwrap().appearance.clone(); + assert!(source.pattern("Charts").is_some()); + + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns = |d: &vectorcraft_doc::Document| -> Vec { + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect() + }; + for styles in [false, true] { + // A document whose "Coin" is a rectangle and an ellipse. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if styles { + crate::cmd::clipboard::resources::import_text_styles(&source, d, true, false).unwrap(); + } else { + crate::cmd::clipboard::resources::import_looks(&source, d, &look, &serde_json::Map::new()).unwrap(); + } + assert_eq!(columns(d), [2, 2, 2, 2], "styles {styles}: drawn with the document's design"); + } +} + #[test] fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 7d23f34a77..b44a26e645 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -199,7 +199,7 @@ pub fn specs() -> Vec { "Envelope Info", [], None, - "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", + "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, a side shorter than 1e-6 pt taking the other side's, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", has_doc, env_info ), diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index ffea03187d..f43221120c 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -286,9 +286,9 @@ impl Session { return; } let read = self.read_selection_paints(); - let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed)); + let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed(), p.stroke_mixed())); let (fill, stroke) = self.proxy_paints(); - let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed); + let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed()); let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width); // A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it. if !fill_mixed && !self.tool_paints(false) { @@ -323,7 +323,7 @@ impl Session { Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) }); } let paints = st.selection_paints()?.clone(); - (!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints) + (!paints.in_live_paint() && self.fill_mesh_points().is_empty()).then_some(paints) } } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 8272f7d8cb..c71c362a61 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -15,10 +15,10 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit}; +use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; pub fn specs() -> Vec { vec![ @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Edit Profile", [], None, - "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", + "{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", always, edit_profile ), @@ -72,10 +72,19 @@ pub fn specs() -> Vec { "Reset Profile", [], None, - "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", + "{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", always, reset_profile ), + cmd!( + "file.newProfiles.applyDefaults", + "Use Profile Defaults", + [], + None, + "{name: a built-in category of file.newPresets (not Recent or Saved)} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when applying the profile leaves the document unchanged). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}", + has_doc, + apply_defaults + ), ] } @@ -1113,3 +1122,98 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result { }; Ok(json!({ "name": name, "reset": reset })) } + +/// `file.newProfiles.applyDefaults`: the active document takes the Default Graphic Style and +/// [Normal Character Style] of profile `name`, and new art is reset to them. +fn apply_defaults(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.applyDefaults"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let mode = s.doc()?.doc.color_mode; + let (mut src, warnings) = match s.read_profile(name) { + Ok(Some(p)) => (p.doc, p.warnings), + // The shipped profile: the defaults of a new document in this color mode. + Ok(None) => (Document::new_with_mode(1.0, 1.0, mode), vec![]), + Err(e) => return Err(bad(C, format!("the {name} profile can't be read: {e}"))), + }; + if src.color_mode != mode { + super::colormgmt::set_color_mode(&mut src, mode, true, None, super::colormgmt::Grays::Profile); + } + // A profile without a Default Graphic Style gives the shipped one, as a new document from it + // starts with the shipped fill and stroke. + let look = match src.graphic_style(DEFAULT_GRAPHIC_STYLE) { + Some(g) => g.clone(), + None => Document::new_with_mode(1.0, 1.0, mode).graphic_style(DEFAULT_GRAPHIC_STYLE).cloned().unwrap_or_else(shipped_default_style), + }; + let normal = super::textstyles::style_attrs(&src, false, super::textstyles::NORMAL_CHAR).unwrap_or_default(); + let chars = s.prefs.override_char_color; + // A composite font the style names comes with it, in place of the document's of its name, as + // Import Composite Fonts brings it. + let family = normal.get("font_family").and_then(Value::as_str); + let fonts_before = s.doc()?.doc.composite_fonts.to_vec(); + let fonts = family + .and_then(|f| CompositeFont::named(&src.composite_fonts, f)) + .map(|f| super::compositefonts::with_font(&fonts_before, f)) + .filter(|after| *after != fonts_before); + if let Some(after) = &fonts { + super::compositefonts::check_set(after, C)?; + } + let fonts_changed = match &fonts { + Some(after) => super::compositefonts::register(s, &fonts_before, after), + None => vec![], + }; + let apply = |d: &mut Document| -> Result<()> { + if let Some(after) = &fonts { + super::compositefonts::set_fonts(d, after, &fonts_changed)?; + } + let before = d.clone(); + let (appearance, attrs) = super::clipboard::resources::import_looks(&src, d, &look.appearance, &normal)?; + let attrs = if attrs.is_empty() { + attrs + } else { + super::textstyles::stored_style_attrs(d, false, &attrs) + .ok_or_else(|| bad(C, format!("the {name} profile's [Normal Character Style] has attributes charStyle.new does not take")))? + }; + let new = GraphicStyle { appearance, ..look.clone() }; + match d.graphic_style_index(DEFAULT_GRAPHIC_STYLE) { + Some(i) if d.graphic_styles[i].same_look(&new) => {} + Some(i) => super::style::redefine_in(d, &before, i, new, None, chars), + None => { + let id = d.next_graphic_style_id(); + d.graphic_styles.insert(0, GraphicStyle { name: DEFAULT_GRAPHIC_STYLE.to_string(), id, ..new }); + } + } + super::textstyles::redefine_normal_char(d, &attrs) + }; + // An undo step only when the document changes; Undo puts the new-art paints back too. + let paint_before = super::colormgmt::new_art_colors_before(s)?; + let mut run = || -> Result { + let mut trial = (*s.doc()?.doc).clone(); + apply(&mut trial)?; + let changed = trial != *s.doc()?.doc; + if changed { + s.edit("Use Profile Defaults", |d, _| apply(d))?; + } + Ok(changed) + }; + let changed = run(); + if fonts.is_some() { + super::compositefonts::sync(s); + } + let changed = changed?; + super::newart::reset(s); + // The selection's appearance does not replace the defaults just set. + s.note_defaults_only(); + if changed || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + super::colormgmt::record_new_art_colors(s, paint_before)?; + } + let mut out = json!({ "name": name, "changed": changed }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) +} + +/// The shipped Default Graphic Style: white fill, 1 pt black stroke. +fn shipped_default_style() -> GraphicStyle { + GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, vectorcraft_doc::Appearance::default_art()) +} diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index d93c4b4a0b..7756cada1d 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -398,20 +398,62 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' /// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or /// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a /// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with -/// [`SelectionPaints::add`]. +/// [`SelectionPaints::add`], and the objects taken out of it with [`SelectionPaints::remove`]. #[derive(Clone, Debug, Default)] pub(crate) struct SelectionPaints { - fill: Option, - pub(crate) fill_mixed: bool, - stroke: Option, - pub(crate) stroke_mixed: bool, - weight: Option, - pub(crate) weight_mixed: bool, - /// An object is a face or edge of a Live Paint group, or lies inside one + fill: Tally, + stroke: Tally, + weight: Tally, + /// The objects that are a face or edge of a Live Paint group, or lie inside one /// ([`live_paint_covered`]). - pub(crate) in_live_paint: bool, - /// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]). - pub(crate) may_hold_mesh: bool, + in_live_paint: usize, + /// The objects that are a gradient mesh or a container ([`Session::fill_mesh_points`]). + may_hold_mesh: usize, +} + +/// The first value met, how many of the values met are the same as it, and how many were met. +#[derive(Clone, Debug)] +struct Tally { + first: Option, + same: usize, + all: usize, +} + +impl Default for Tally { + fn default() -> Self { + Self { first: None, same: 0, all: 0 } + } +} + +impl Tally { + fn add(&mut self, value: T, same: impl Fn(&T, &T) -> bool) { + self.all += 1; + match &self.first { + Some(f) if same(f, &value) => self.same += 1, + Some(_) => {} + None => (self.first, self.same) = (Some(value), 1), + } + } + /// Take out a value met before. → false when the values left must be met again to know which + /// differ: every value the same as the first one is gone, and others are left. + fn remove(&mut self, value: &T, same: impl Fn(&T, &T) -> bool) -> bool { + let Some(f) = &self.first else { return false }; + if self.all == 0 { + return false; + } + self.all -= 1; + if same(f, value) { + self.same = self.same.saturating_sub(1); + } + if self.same == 0 { + self.first = None; + return self.all == 0; + } + true + } + fn mixed(&self) -> bool { + self.same < self.all + } } impl SelectionPaints { @@ -422,31 +464,76 @@ impl SelectionPaints { p } - /// Read objects `ids` of `doc` too. + /// Do the fills differ? + pub(crate) fn fill_mixed(&self) -> bool { + self.fill.mixed() + } + + /// Do the strokes differ? + pub(crate) fn stroke_mixed(&self) -> bool { + self.stroke.mixed() + } + + /// Do the stroke weights differ? + pub(crate) fn weight_mixed(&self) -> bool { + self.weight.mixed() + } + + /// Is an object a face or edge of a Live Paint group, or inside one? + pub(crate) fn in_live_paint(&self) -> bool { + self.in_live_paint > 0 + } + + /// Is an object a gradient mesh or a container? + pub(crate) fn may_hold_mesh(&self) -> bool { + self.may_hold_mesh > 0 + } + + /// Read objects `ids` of `doc` too: ids that are not read yet, each named once. pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) { - fn meet(first: &mut Option, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) { - match first { - Some(f) => *mixed |= !same(f, &value), - None => *first = Some(value), + self.each(doc, ids, true); + } + + /// Take out objects `ids` of `doc`, read before in the same document: ids that are read, each + /// named once. → false when the objects left must be read again ([`Tally::remove`]); the + /// paints are then wrong. + pub(crate) fn remove(&mut self, doc: &Document, ids: &[NodeId]) -> bool { + self.each(doc, ids, false) + } + + /// [`Self::add`] (`add`) or [`Self::remove`]. + fn each(&mut self, doc: &Document, ids: &[NodeId], add: bool) -> bool { + let mut ok = true; + let mut meet = |tally: &mut Tally, value: Paint| { + if add { + tally.add(value, same_in_proxy); + } else { + ok &= tally.remove(&value, same_in_proxy); } - } - // As in `proxy_mixed_with`: every node with an added id, in tree order. + }; + // As in `proxy_mixed_with`: every node with one of the ids, in tree order. let (mut fills, mut strokes) = (vec![], vec![]); for n in doc.nodes_in_order(ids.iter().copied()) { painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } for n in fills { - meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy); + meet(&mut self.fill, proxy_paint(n, false, None)); } for n in strokes { - meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy); + meet(&mut self.stroke, proxy_paint(n, true, None)); } - // As in `stroke_mixed`: the node each added id names. - for id in ids { + // As in `stroke_mixed`: the node each id names. + let step = |count: &mut usize, yes: bool| { + if yes { + *count = if add { *count + 1 } else { count.saturating_sub(1) }; + } + }; + let mut seen = std::collections::HashSet::new(); + for id in ids.iter().filter(|id| seen.insert(**id)) { let Some(n) = doc.node(*id) else { continue }; - self.in_live_paint |= in_live_paint(doc, *id); - self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container(); + step(&mut self.in_live_paint, in_live_paint(doc, *id)); + step(&mut self.may_hold_mesh, matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); let mut nodes = vec![]; painted(n, true, true, &mut nodes); for n in nodes { @@ -455,10 +542,15 @@ impl SelectionPaints { _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; for w in widths { - meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b); + if add { + self.weight.add(w, |a, b| a == b); + } else { + ok &= self.weight.remove(&w, |a, b| a == b); + } } } } + ok } } @@ -1161,7 +1253,7 @@ impl Session { /// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured /// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting /// with both the fill and the stroke). - fn note_defaults_only(&mut self) { + pub(crate) fn note_defaults_only(&mut self) { let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true)); self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None }); } @@ -1275,7 +1367,7 @@ impl DocState { /// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group. pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet { - if self.selection_paints().is_some_and(|p| !p.in_live_paint) { + if self.selection_paints().is_some_and(|p| !p.in_live_paint()) { return std::collections::HashSet::new(); } live_paint_covered(&self.doc, ids) @@ -1527,7 +1619,7 @@ impl Session { // Only gradient meshes have points to pick: a selection with no mesh and no container that // could hold one skips reading the tool's options. let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); - let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh); + let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh()); if st.selection.symbol_part.is_some() || none_may() { return vec![]; } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index a93c4da50d..dcc3eade04 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -260,6 +260,8 @@ thread_local! { pub(crate) static PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Whether [`known`] is skipped on this thread ([`uncached`]). static UNCACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The cells [`distance`] worked out on this thread: one for each pair of characters it compared. + pub(crate) static DISTANCE_CELLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Whether [`read_descriptions`] keeps what `doc` says. @@ -330,6 +332,8 @@ fn no_required_id_beside_ids(doc: &str) -> bool { /// The edits (insert, delete, replace, swap of neighbours) that turn `a` into `b`, ignoring case. fn distance(a: &str, b: &str) -> usize { let (a, b): (Vec, Vec) = (a.chars().map(|c| c.to_ascii_lowercase()).collect(), b.chars().map(|c| c.to_ascii_lowercase()).collect()); + #[cfg(test)] + DISTANCE_CELLS.with(|n| n.set(n.get().saturating_add(a.len().saturating_mul(b.len())))); let (mut before, mut prev): (Vec, Vec) = (Vec::new(), (0..=b.len()).collect()); for (i, ca) in a.iter().enumerate() { let mut row = vec![i + 1]; diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index d464be5d6f..cb2b52b28d 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -19,6 +19,7 @@ use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_pai use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; +use super::brushsym::frame_marker; use super::edit::{outermost, selected_roots}; use super::pathops::Beside; use super::{ @@ -43,10 +44,19 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch and options; an unpainted rectangle at the back of the art (or at the back of one selected group, as pattern.placeArt places it) becomes the tile and is left out of the tile art, otherwise the tile keeps its size and moves as far as the art's bounds moved from the old tile art's (with Size Tile to Art on, the tile fits the new art); every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art and tile match the pattern's already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), + cmd!( + "pattern.placeArt", + "Place Pattern Art", + [], + None, + "{name, x?, y?} place a copy of pattern `name`'s tile art, as dragging its swatch from the Swatches panel onto an empty part of the canvas does: one group with an unpainted rectangle of the tile at its back, centered on (x, y) (default: the center of the first artboard) in the layer new art goes into, and selected; object.pattern.replaceArt reads the rectangle back as the tile; the pattern does not change; one undo step; refused while a pattern is edited and for a pattern with no art → {id}", + can_replace_pattern_art, + pattern_place_art + ), cmd!( "object.pattern.edit", "Edit Pattern", @@ -434,41 +444,102 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { const C: &str = "object.pattern.replaceArt"; let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); let roots = roots(s, p, C)?; let d = &s.doc()?.doc; - let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; - if roots.is_empty() { + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + let (src, marked) = tile_and_art(roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect()); + if src.is_empty() { return Err(bad(C, "select the art for the pattern tile")); } - let src: Vec> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect(); if paints_pattern(d, &src, &name) { return Err(bad(C, format!("art painted with `{name}` can't be its tile"))); } + let mut next = def.clone(); + next.tile = match (marked, vectorcraft_doc::live::nodes_bounds(&def.art), vectorcraft_doc::live::nodes_bounds(&src)) { + (Some(tile), ..) => tile, + (None, Some(was), Some(now)) => def.tile + (now.origin() - was.origin()), + (None, ..) => def.tile, + }; + next.art = src.clone(); + if next.size_tile_to_art { + next.fit_tile_to_art(); + } + let tile = next.tile; // Copies made from the same next id are equal when the art matches the tile art. let fresh = |art: &[Arc]| copies(&mut Document::clone(d), art); - if fresh(&old) == fresh(&src) { + if tile == def.tile && fresh(&def.art) == fresh(&src) { return Ok(json!({ "name": name })); } s.edit("Replace Pattern Art", |d, _| { let art: Vec> = copies(d, &src).into_iter().map(Arc::new).collect(); if let Some(def) = d.pattern_mut(&name) { def.art = art; - if def.size_tile_to_art { - def.fit_tile_to_art(); - } + def.tile = tile; } Ok(()) })?; Ok(json!({ "name": name })) } +/// The tile art and the tile that art `src` (in paint order) gives a pattern: an unpainted +/// rectangle at the back of the art ([`frame_marker`]), or at the back of a lone plain group as +/// `pattern.placeArt` places it, is the tile and is left out of the art, and that group's members +/// are the art. Without such a rectangle the art is `src` and there is no tile. +fn tile_and_art(src: Vec>) -> (Vec>, Option) { + let mut art = src; + if let [g] = art.as_slice() + && let NodeKind::Group { children, clip: false } = &g.kind + && children.first().is_some_and(|c| frame_marker(c).is_some()) + && **g == Node::group(g.id, children.clone()) + { + art = children.clone(); + } + match art.first().and_then(|c| frame_marker(c)) { + Some(tile) => (art.split_off(1), Some(tile)), + None => (art, None), + } +} + +/// `pattern.placeArt`: a copy of pattern `name`'s tile art in one group, with an unpainted +/// rectangle of its tile at the back, centered on (`x`, `y`) (default: the center of the first +/// artboard) in the layer new art goes into, and selected, as one undo step. The pattern does not +/// change; `object.pattern.replaceArt` reads the rectangle back as the tile ([`tile_and_art`]). +fn pattern_place_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "pattern.placeArt"; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + if def.art.is_empty() { + return Err(bad(C, "no artwork")); + } + let unpainted = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0); + let marker = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(def.tile), unpainted); + let mut art = Node::group(NodeId(0), std::iter::once(Arc::new(marker)).chain(def.art.iter().cloned()).collect()); + if let Some(r) = art.geometric_bounds_with(&d.symbol_boxes()) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Pattern Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + /// What a piece of art uses by name, for [`paints_pattern`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Uses<'a> { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index e787899cd2..d1c86a4f62 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -49,6 +49,9 @@ pub(crate) mod docx; mod rtf; pub(super) mod text; +#[cfg(test)] +pub(crate) use doc::PRLS_READ; + use std::sync::Arc; use serde_json::{Value, json}; diff --git a/crates/engine/src/cmd/place/doc.rs b/crates/engine/src/cmd/place/doc.rs index fda21d11b0..ad07db7ae7 100644 --- a/crates/engine/src/cmd/place/doc.rs +++ b/crates/engine/src/cmd/place/doc.rs @@ -487,10 +487,18 @@ fn operand_len(sprm: u16, rest: &[u8]) -> Option { }) } +#[cfg(test)] +thread_local! { + /// The Prls [`each_prl`] read on this thread. + pub(crate) static PRLS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Calls `f` with each Prl of `grpprl`: its sprm and its operand. fn each_prl(grpprl: &[u8], mut f: impl FnMut(u16, &[u8])) { let mut at = 0; while let Some(sprm) = u16_at(grpprl, at) { + #[cfg(test)] + PRLS_READ.with(|n| n.set(n.get() + 1)); let rest = grpprl.get(at + 2..).unwrap_or_default(); let Some((n, op)) = operand_len(sprm, rest).and_then(|n| Some((n, rest.get(..n)?))) else { return }; // A variable operand's bytes follow its size. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 53d9c3ff29..5f1964ec0d 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -128,6 +128,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if m.appearance_output { + v["appearanceOutput"] = json!(true); + } if let Some(script) = p.script() { v["runtime"] = json!(m.runtime.name()); v["script"] = json!(script); @@ -1615,8 +1618,14 @@ impl Drop for FolderPending { /// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`: /// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report. -#[cfg(not(target_arch = "wasm32"))] fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + start_folder_files(s, folder, None, record) +} + +/// [`start_folder`] for the one file `only` of `folder` when it is given, without listing the +/// folder ([`registry::FolderLoad::list_file`]). +#[cfg(not(target_arch = "wasm32"))] +fn start_folder_files(s: &Session, folder: &str, only: Option<&std::path::Path>, record: Option) -> FolderPending { let pending = |load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }; if let Err(e) = crate::file_access::check_read(folder) { @@ -1637,11 +1646,15 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending }) }; // The modules start loading once the loads queued before them are done. - pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()}))) + let listed = match only { + Some(file) => registry::FolderLoad::list_file(file, allow), + None => registry::FolderLoad::list(std::path::Path::new(folder), allow), + }; + pending(listed.map_err(|e| json!({"folder": folder, "error": e.to_string()}))) } #[cfg(target_arch = "wasm32")] -fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { +fn start_folder_files(s: &Session, folder: &str, _: Option<&std::path::Path>, record: Option) -> FolderPending { let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"})); FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false } } @@ -1659,6 +1672,13 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S { for id in load.install_ready(s.plugin_folder_approver()) { s.attach_plugin_storage(turn, &id); + // A `plugin.reload` of the plug-in store's own folder installed a stored file that + // failed before. + if let Some(p) = registry::get(&id) + && let Some(source) = p.source() + { + crate::store::clear_stored_failure(std::path::Path::new(source)); + } } // A disabled plug-in's file matched by its id is saved in the same turn. if load.disabled_changed() && s.store_disabled_plugins_in(turn) { @@ -1790,12 +1810,206 @@ fn shown_report(mut report: Value) -> Value { report } -fn list(_: &mut Session, _: &Value) -> Result { +fn list(s: &mut Session, _: &Value) -> Result { let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone())); let disabled: Vec = safe_mode::disabled().iter().map(shown_item).collect(); - Ok( - json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}), - ) + let failed: Vec = failed_loads(s).iter().map(shown_failure).collect(); + Ok(json!({ + "plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), + "folder": folder, + "failed": failed, + "safeMode": safe_mode::active(), + "disabled": disabled, + })) +} + +/// Where a plug-in that didn't load was loaded from. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum LoadedFrom { + /// The session's plug-in store. + Store, + /// The Additional Plug-ins Folder, or the folder `plugin.reload` loaded last. + Folder, +} + +impl LoadedFrom { + fn name(self) -> &'static str { + match self { + LoadedFrom::Store => "store", + LoadedFrom::Folder => "folder", + } + } +} + +/// A plug-in file that didn't load in this process: the file, why, and where it was loaded from. +type FailedLoad = (String, String, LoadedFrom); + +/// The plug-in files that didn't load in this process and that a retry may load: those of the +/// session's plug-in store ([`crate::store::failed_stored_plugins`]), then those of the folder last +/// loaded ([`FOLDER`]). A disabled plug-in (it is listed in `disabled`) and one that another install +/// or removal of its id replaced while it loaded are left out. +fn failed_loads(s: &Session) -> Vec { + let mut failed: Vec = s + .plugin_dir + .as_deref() + .map(crate::store::failed_stored_plugins) + .unwrap_or_default() + .into_iter() + .map(|(path, why)| (path.display().to_string(), why, LoadedFrom::Store)) + .collect(); + if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref() + && let Some(rows) = report.get("failed").and_then(Value::as_array) + { + for row in rows { + let (Some(file), Some(why)) = (row.get("file").and_then(Value::as_str), row.get("error").and_then(Value::as_str)) else { continue }; + // A `plugin.reload` of the plug-in store's own folder lists its stored files once, as + // stored files. + let stored = failed.iter().any(|(f, _, from)| *from == LoadedFrom::Store && std::path::Path::new(f) == std::path::Path::new(file)); + if why != registry::DISABLED && why != registry::SUPERSEDED && !stored { + failed.push((file.to_string(), why.to_string(), LoadedFrom::Folder)); + } + } + } + // A file turned off since it failed (`plugin.setEnabled`, listed in `disabled`) or skipped in this + // launch, and a stored file whose plug-in id is, are left out. + let off = safe_mode::disabled(); + let stems: std::collections::BTreeSet = + off.iter().filter_map(|i| i.id.clone()).chain(safe_mode::skipped_ids()).map(|id| crate::store::file_stem(&id)).collect(); + failed.retain(|(file, _, from)| { + let item = safe_mode::Item::file(file.clone()); + let by_id = + *from == LoadedFrom::Store && std::path::Path::new(file).file_stem().is_some_and(|s| stems.contains(s.to_string_lossy().as_ref())); + !by_id && !safe_mode::skipped(&item) && !off.iter().any(|i| i.same(&item)) + }); + failed +} + +/// How many plug-in files didn't load in this process and may load on a retry ([`failed_loads`]): +/// Object › Plug-ins › Plug-ins That Didn't Load… is enabled while there is one. +pub fn failed_load_count(s: &Session) -> usize { + failed_loads(s).len() +} + +/// A [`FailedLoad`] as a reply shows it: a file outside the automation read roots by its file name, +/// in its error too. +fn shown_failure((file, why, from): &FailedLoad) -> Value { + json!({"file": shown_file(file), "error": shown_error(file, why), "from": from.name()}) +} + +/// The error `why` about the plug-in file `file` as a reply shows it: the file, and then its folder, +/// outside the automation read roots by their names, as [`shown_report`] shows a folder's errors. +fn shown_error(file: &str, why: &str) -> String { + let folder = std::path::Path::new(file).parent().map(|f| f.display().to_string()).filter(|f| !f.is_empty()); + let why = why.replace(file, &shown_file(file)); + match folder { + Some(folder) => why.replace(folder.as_str(), &shown_file(&folder)), + None => why, + } +} + +/// `plugin.retry`: loads again the plug-in file `file` that didn't load (as `plugin.list`'s `failed` +/// names it), or every one of them without `file`, each as the load it failed in loads it: a stored +/// file as the plug-in store loads its files, and a folder file as `plugin.reload` loads the folder's +/// → `{retried: [{file, loaded, id?, error?}]}`. +fn retry(s: &mut Session, p: &Value) -> Result { + const C: &str = "plugin.retry"; + let failed = failed_loads(s); + let picked: Vec = match p.get("file") { + None => failed, + Some(v) => { + let file = + v.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "`file` must be a file plugin.list's failed names"))?; + // A file outside the automation read roots is named by its file name, when no other + // failed file has it. + let exact: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| f == file).collect(); + let named: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| shown_file(f) == file).collect(); + match (exact.as_slice(), named.as_slice()) { + ([one], _) | ([], [one]) => vec![(*one).clone()], + _ => return Err(bad(C, format!("{file} is not a plug-in that failed to load (see plugin.list's failed)"))), + } + } + }; + safe_mode::check().map_err(err)?; + // Loads started earlier install first, so a retry's module replaces theirs. + s.finish_plugin_loads(); + let mut retried = Vec::with_capacity(picked.len()); + for (file, _, from) in &picked { + let outcome = match from { + LoadedFrom::Store => retry_stored(s, file), + LoadedFrom::Folder => retry_folder_file(s, file), + }; + let shown = shown_file(file); + retried.push(match outcome { + Ok(id) => json!({"file": shown, "loaded": true, "id": id}), + Err(why) => json!({"file": shown, "loaded": false, "error": shown_error(file, &why)}), + }); + } + Ok(json!({ "retried": retried })) +} + +/// Loads the stored plug-in `file` again → the id it installed with, or why it didn't. +fn retry_stored(s: &mut Session, file: &str) -> std::result::Result { + let path = std::path::Path::new(file); + // Under automation read roots, a file outside them is not read again, as a folder file isn't. + crate::file_access::check_read(file)?; + let installed = s.retry_stored_plugin(path); + if let Some(why) = crate::store::stored_failure(path) { + return Err(why); + } + match installed { + Some(id) => { + clear_folder_failure(path); + Ok(id) + } + None if !path.is_file() => Err("the file is no longer in the plug-in store".into()), + // Disabled, or replaced by another install of its id while it loaded. + None => Err("it didn't install".into()), + } +} + +/// Takes `path` out of the folder report's failed files: a stored module may also have failed in +/// a `plugin.reload` of the store's own folder. +pub(crate) fn clear_folder_failure(path: &std::path::Path) { + if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + && let Some(rows) = report.get_mut("failed").and_then(Value::as_array_mut) + { + rows.retain(|row| row.get("file").and_then(Value::as_str).is_none_or(|f| std::path::Path::new(f) != path)); + } +} + +/// Loads the file `file` of the folder last loaded again, as `plugin.reload` loads each file, and +/// updates that folder's report: the file is listed as loaded or, with the new error, as failed → +/// the id it installed with, or why it didn't. +fn retry_folder_file(s: &mut Session, file: &str) -> std::result::Result { + let path = std::path::Path::new(file); + let folder = path.parent().map(|f| f.display().to_string()).unwrap_or_default(); + let load = start_folder_files(s, &folder, Some(path), None); + let report = s.finish_plugin_load(PluginLoad::Folder(load)); + let loaded: Vec = report.get("loaded").and_then(Value::as_array).cloned().unwrap_or_default(); + let failed: Vec = report.get("failed").and_then(Value::as_array).cloned().unwrap_or_default(); + // A retry that couldn't load the file (its folder can't be read) reports only an error and + // leaves its row as it is. + if report.get("failed").is_some() + && let Some((last, _, r, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + && std::path::Path::new(last.as_str()) == std::path::Path::new(&folder) + { + if let Some(rows) = r.get_mut("failed").and_then(Value::as_array_mut) { + rows.retain(|row| row.get("file").and_then(Value::as_str) != Some(file)); + rows.extend(failed.iter().cloned()); + } + if let Some(ids) = r.get_mut("loaded").and_then(Value::as_array_mut) { + for id in &loaded { + if !ids.contains(id) { + ids.push(id.clone()); + } + } + } + } + if let Some(id) = loaded.first().and_then(Value::as_str) { + return Ok(id.to_string()); + } + let why = failed.first().and_then(|row| row.get("error")).and_then(Value::as_str).or_else(|| report.get("error").and_then(Value::as_str)); + Err(why.unwrap_or("it didn't install").to_string()) } /// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch, @@ -1811,15 +2025,16 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result { })) } -/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name +/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source` or in `failed`: one they name /// by its file name (outside the automation read roots) is found by that name, when no other listed /// file has it. -fn listed_file(file: String) -> String { +fn listed_file(s: &Session, file: String) -> String { let mut listed: Vec = safe_mode::disabled() .into_iter() .chain(safe_mode::previous()) .filter_map(|i| i.file) .chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string))) + .chain(failed_loads(s).into_iter().map(|(f, _, _)| f)) .collect(); listed.sort(); listed.dedup(); @@ -1854,7 +2069,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None }; (registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored) } - (None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None), + (None, Some(file)) => (safe_mode::Item::file(listed_file(s, file)), None), (None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")), }; let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect(); @@ -1971,7 +2186,7 @@ fn clear_cache(_: &mut Session, p: &Value) -> Result { } /// This module's commands: `plugin.list`, `.info`, `.run`, `.install`, `.inspect`, `.remove`, -/// `.reload`, `.clearCache`, `.safeMode` and `.setEnabled`. +/// `.reload`, `.retry`, `.clearCache`, `.safeMode` and `.setEnabled`. pub fn specs() -> Vec { vec![ cmd!( @@ -1979,7 +2194,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), 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), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), 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), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), 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), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), 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 ), @@ -2046,6 +2261,15 @@ pub fn specs() -> Vec { always, reload ), + cmd!( + query "plugin.retry", + "Retry Plug-in", + [], + None, + "{file?: a file plugin.list's failed names (under automation read roots, a file outside them by the file name shown, when no other failed file has it)} load again the plug-in file that didn't load, or every file plugin.list's failed names when file is left out (desktop; a stored file loads as the plug-in store loads its files, and a folder file as plugin.reload loads the folder's, with the same checks; under automation read roots, a file outside them is not read and reports why; a folder file's row in plugin.list's folder report changes to loaded or to its new error; an error in Safe Mode, or when file isn't one that failed) → {retried: [{file, loaded: bool, id? (the plug-in it installed), error? (why it didn't load again)}]}", + always, + retry + ), cmd!( query "plugin.safeMode", "Safe Mode", @@ -2060,7 +2284,7 @@ pub fn specs() -> Vec { "Enable on Re-launch", [], None, - "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", + "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source or failed names it (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", always, set_enabled ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 3d5723b7d3..3d49db0f2a 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -489,6 +489,7 @@ pub(super) const ALLOWED: &[&str] = &[ "pattern.delete", "pattern.list", "pattern.options", + "pattern.placeArt", "pattern.transform", "perspective.attach", "perspective.draw", @@ -736,6 +737,7 @@ pub(super) const ALLOWED: &[&str] = &[ "variable.makeTextDynamic", "variable.makeVisibilityDynamic", "variable.rename", + "variable.setBinding", "variable.sort", "variable.unbind", ]; diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index efbdb10a20..cd2f804331 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -294,7 +294,7 @@ impl Line { let mut origins = |text: String| -> Vec { bare.text = text; let t = bare.probe(system_layout); - let lay = vectorcraft_text::layout(FontDb::global(), &t); + let lay = lay_out(&t); lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() }; let joined = origins(ms.iter().map(|m| m.ch).collect()); @@ -534,7 +534,7 @@ impl Line { let mut origins = |text: String| -> Vec { bare.text = text; let t = bare.probe(system_layout); - let lay = vectorcraft_text::layout(FontDb::global(), &t); + let lay = lay_out(&t); lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() }; // With no spaces. @@ -723,7 +723,7 @@ fn round_tracking(t: f64) -> f64 { /// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, /// more space than whole spaces make); `None` when the type draws every glyph in its place. fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> Option { - let lay = vectorcraft_text::layout(FontDb::global(), t); + let lay = lay_out(t); let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); // With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one, // may sit that much further (as a fraction of the size) from where the type draws it. @@ -998,6 +998,20 @@ fn max_wrap_work() -> usize { WRAP_LIMIT.with(|c| c.get()) } +#[cfg(test)] +thread_local! { + /// The glyphs [`lay_out`] laid out on this thread. + static GLYPHS_LAID_OUT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Type `t` laid out, for a check of where it draws its glyphs. +fn lay_out(t: &TextObject) -> vectorcraft_text::TextLayout { + let lay = vectorcraft_text::layout(FontDb::global(), t); + #[cfg(test)] + GLYPHS_LAID_OUT.with(|n| n.set(n.get().saturating_add(lay.glyphs.len()))); + lay +} + /// Lines farther apart than this many times their size do not join into one object. const MAX_LEADING: f64 = 3.0; @@ -1159,7 +1173,7 @@ impl Block { let matches: Vec = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect(); // Aligned at its end or center, point type starts its first line elsewhere: the type moves // so its first glyph is where the first outline is. - let lay = vectorcraft_text::layout(FontDb::global(), &t); + let lay = lay_out(&t); if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) { let at = t.xf * (g.xf * Point::ORIGIN); t.xf = kurbo::Affine::translate(m.origin - at) * t.xf; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index b386758690..5f89bc1284 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -692,21 +692,28 @@ fn timing_with_hundreds_of_cjk_outlines() { #[test] fn a_long_tracked_line_is_checked_in_time() { // Even tracking is kept on the line; the layout check of a long line must not lay out the rest - // of the line again after each window. - let text = "abe".repeat(150); - let mut s = session(); - let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); - s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); - s.execute("select.set", &json!({"ids": [id]})).unwrap(); - let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); - s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let t0 = std::time::Instant::now(); - let r = s.execute("type.retype", &json!({})).unwrap(); - let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); - assert_eq!(texts, vec![text], "the whole line is one object: {r}"); - assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); - assert_eq!(r["unmatched"], json!([])); - eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); + // of the line again after each window: a line ten times as long lays out no more than twice as + // many glyphs per glyph. + let laid_out = |text: &str| { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + super::GLYPHS_LAID_OUT.set(0); + let r = s.execute("type.retype", &json!({})).unwrap(); + let laid = super::GLYPHS_LAID_OUT.get(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts, vec![text], "the whole line is one object: {r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); + assert_eq!(r["unmatched"], json!([])); + laid + }; + let short = laid_out(&"abe".repeat(15)); + let long = laid_out(&"abe".repeat(150)); + assert!(short > 0, "the line is laid out to be checked"); + assert!(long <= 20 * short, "450 glyphs: {long} laid out; 45 glyphs: {short}"); } /// Every path in the document flattened into lines `tol` from its curves, each contour started at diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 36f54934c0..05fa6ce85f 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -545,40 +545,50 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { - let id = d.graphic_style_id(i); - let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look }); - // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the - // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the - // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); - let (follow, edited): (Vec, Vec) = - linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); - set_link(d, &edited, None); - // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and - // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its - // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps - // its look and its link. - let mut follow_marks = super::graph::series_group_marks(d, &follow); - let edited: HashSet = edited.into_iter().collect(); - let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); - follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); - super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); - let g = d.graphic_styles[i].clone(); - let mut shared = None; - for nid in &follow_marks { - apply_style(d, *nid, &g, &mut shared, chars); - } - super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); - super::graph::capture_label_rows(d, &follow_marks); - if let Some(src) = src { - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); - } + redefine_in(d, &before, i, look, src, chars); Ok(()) })?; Ok(json!({ "name": name })) } +/// Replace graphic style `i` of `d` with the fills, strokes, effects and transparency of `look`, +/// keeping its name and id, as Redefine Graphic Style does: the objects still linked to it follow +/// the new definition, edited ones are unlinked and keep their look, and object `src` (the one the +/// look comes from, if any) becomes linked. `before` is `d` before the edit; `chars` is Override +/// Character Color. +pub(crate) fn redefine_in(d: &mut Document, before: &Document, i: usize, look: GraphicStyle, src: Option, chars: bool) { + let id = d.graphic_style_id(i); + let name = d.graphic_styles[i].name.clone(); + let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name, id, ..look }); + // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the + // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the + // source or as a linked object: the graph draws it again from the design. + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); + let (follow, edited): (Vec, Vec) = + linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); + set_link(d, &edited, None); + // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and + // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its + // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps + // its look and its link. + let mut follow_marks = super::graph::series_group_marks(d, &follow); + let edited: HashSet = edited.into_iter().collect(); + let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); + super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); + let g = d.graphic_styles[i].clone(); + let mut shared = None; + for nid in &follow_marks { + apply_style(d, *nid, &g, &mut shared, chars); + } + super::appearance::capture_series_writes(before, d, &follow_marks, (true, true), (true, true), false, true); + super::graph::capture_label_rows(d, &follow_marks); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } +} + fn style_break_link(s: &mut Session, p: &Value) -> Result { let ids = super::appearance::whole_targets(s, p, "graphicStyle.breakLink")?; s.edit("Break Link to Graphic Style", |d, _| { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d7657df16e..b632dbd3ba 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -336,16 +336,17 @@ fn with_attrs(base: &T, attrs: &Map( cur: &T, attrs: fn(&T) -> Map, old: &Map, new: &Map, base: &Map, + old_base: &Map, ) -> T { // Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept. let Some(mut m) = to_map(cur) else { return cur.clone() }; @@ -353,7 +354,7 @@ fn restyle( let pair = |m: &Map| KINSOKU.map(|k| m.get(k).cloned()); let own = pair(&m); for (k, v) in new { - if old.get(k).is_none_or(|o| m.get(k) == Some(o)) { + if m.get(k) == old.get(k).or_else(|| old_base.get(k)) { m.insert(k.clone(), v.clone()); } } @@ -369,7 +370,7 @@ fn restyle( // style's keeps its own. let has = |m: &Map| KINSOKU.iter().any(|k| m.contains_key(*k)); if has(old) || has(new) { - let follows = !has(old) || pair(old) == own; + let follows = pair(if has(old) { old } else { old_base }) == own; let to = if !follows { own } else if has(new) { @@ -494,10 +495,16 @@ fn uses_of(uses: &std::collections::HashMap, usize>, kind: Kind, fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) -> Result<()> { let target = (name != kind.normal()).then_some(name.to_string()); let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); - let base = match kind { - Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?), - Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?), + // What the text had under the old definition where it sets nothing: Normal's (its old + // definition when Normal is the style redefined) over the defaults. + let old_normal = if target.is_none() { old } else { &normal }; + let over_defaults = |attrs: &Map| -> Result> { + Ok(match kind { + Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), attrs, &kind.cmd("edit"))?), + Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), attrs, &kind.cmd("edit"))?), + }) }; + let (base, old_base) = (over_defaults(&normal)?, over_defaults(old_normal)?); each_text_mut(d, &mut |t| { let mut changed = false; // The first character whose leading the new definition changed. @@ -505,8 +512,10 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { @@ -520,7 +529,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map { for pa in t.para_styles_mut() { if pa.style_name == target { - *pa = restyle(pa, para_attrs, old, new, &base); + *pa = restyle(pa, para_attrs, old, new, &base, &old_base); changed = true; } } @@ -963,17 +972,31 @@ fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map def.attrs = new_attrs.clone(), - None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }), - } - update_users(d, kind, &name, &old, &new_attrs)?; - Ok(()) - })?; + s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| set_definition(d, kind, &name, &old, &new_attrs))?; ok() } +/// Give style `name` of `d` the attributes `new_attrs` (it had `old`), and the text in it that +/// follows the old definition the new one (users keep their overrides). +fn set_definition(d: &mut Document, kind: Kind, name: &str, old: &Map, new_attrs: &Map) -> Result<()> { + match kind.defs_mut(d).iter_mut().find(|s| s.name == name) { + Some(def) => def.attrs = new_attrs.clone(), + None => kind.defs_mut(d).push(TextStyleDef { name: name.to_string(), attrs: new_attrs.clone() }), + } + update_users(d, kind, name, old, new_attrs) +} + +/// Redefine `[Normal Character Style]` of `d` with `attrs` (attributes as `charStyle.new` stores +/// them), as Redefine Character Style does: the type in it takes the new attributes and keeps its +/// overrides. Nothing changes when `attrs` is the current definition. +pub(crate) fn redefine_normal_char(d: &mut Document, attrs: &Map) -> Result<()> { + let old = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); + if *attrs == old { + return Ok(()); + } + set_definition(d, Kind::Char, NORMAL_CHAR, &old, attrs) +} + fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "redefine")?.to_string(); let attrs = selection_attrs(s, p, kind, "redefine")?.ok_or_else(|| bad(&kind.cmd("redefine"), "select text to redefine the style from"))?; diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index c0a92a20e3..49e50ca14c 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -525,6 +525,23 @@ fn editing_character_style_clears_removed_size_without_losing_local_override() { assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0)); } +/// A size a style starts to set reaches the text that had the size the style left it (Normal's, +/// or the default when Normal itself is redefined), and not text with a size of its own. +#[test] +fn a_size_a_character_style_starts_to_set_keeps_local_overrides() { + for name in ["Body", NORMAL_CHAR] { + let (mut s, id) = session_with_text("One two"); + if name != NORMAL_CHAR { + s.execute("charStyle.new", &json!({"name": name, "attrs": {}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": name, "id": id})).unwrap(); + } + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 36.0})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": name, "attrs": {"size": 24.0}})).unwrap(); + let r = runs(&s, id); + assert_eq!((r[0].style.size, r[1].style.size), (24.0, 36.0), "{name}"); + } +} + #[test] fn replacing_character_style_attrs_clears_removed_size() { let (mut s, id) = session_with_text("Text"); diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index b863ec5edf..217c967fc1 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -455,6 +455,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result { Ok(json!({"unbound": n})) } +/// The kind of variable that drives the content of `n`: text for type, image for an image object +/// and graph for a graph root. `None` for other objects, which have only a visibility slot. +pub(crate) fn content_kind(n: &vectorcraft_doc::Node) -> Option { + match &n.kind { + NodeKind::Text(_) => Some(VariableKind::Text), + NodeKind::Image(_) => Some(VariableKind::Image), + _ if n.extras().graph.is_some() => Some(VariableKind::Graph), + _ => None, + } +} + +/// The variables of `kind` bound to `id`, in the order they are defined. +fn bound_of_kind(vars: &Variables, id: NodeId, kind: VariableKind) -> Vec { + let Some(bound) = vars.bindings.get(&id) else { return Vec::new() }; + vars.variables.iter().filter(|v| v.kind == kind && bound.contains(&v.name)).map(|v| v.name.clone()).collect() +} + +/// The slot `variable.setBinding` names: an object's visibility, or its content. +fn slot_kind(doc: &Document, id: NodeId, p: &Value, cmd: &str) -> Result<(&'static str, VariableKind)> { + let node = doc.node(id).ok_or(EngineError::NoNode(id))?; + match str_param(p, "slot") { + Some("visibility") => Ok(("visibility", VariableKind::Visibility)), + Some("content") => { + content_kind(node).map(|k| ("content", k)).ok_or_else(|| bad(cmd, format!("node {} has no content a variable can drive", id.0))) + } + _ => Err(bad(cmd, "`slot` must be `visibility` or `content`")), + } +} + +/// Bind one object's visibility or content to one variable, or to none, in one undo step: the +/// object's other variables of that slot's kind are unbound. The content of type takes a text +/// variable, of a linked image an image variable and of a graph root a graph variable; an embedded +/// image can't be bound to an image variable. The checks of `variable.bind` apply, and nothing +/// changes when one fails. A call that leaves the bindings as they were adds no undo step. +fn set_binding(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.setBinding"; + let id = p.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| bad(C, "`id` must be an object id"))?; + let variable = match p.get("variable") { + None | Some(Value::Null) => None, + Some(v) => Some(named(v.as_str(), "variable", C)?), + }; + let doc = &s.doc()?.doc; + let (slot, kind) = slot_kind(doc, id, p, C)?; + if let Some(name) = &variable { + let have = doc.variables.variable(name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?; + if have != kind { + return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); + } + check_bindable(doc, &[id], kind, C)?; + if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); + } + } + let unbound: Vec = bound_of_kind(&doc.variables, id, kind).into_iter().filter(|n| Some(n) != variable.as_ref()).collect(); + let label = if variable.is_some() { "Bind Variable" } else { "Unbind Variable" }; + edit_variables(s, label, |vars| { + for n in &unbound { + vars.unbind(id, n); + } + if let Some(n) = &variable { + vars.bind(id, n); + } + Ok(()) + })?; + Ok(json!({"id": id.0, "slot": slot, "variable": variable, "unbound": unbound})) +} + /// The `variable` a command names, which must be defined; `None` when it names none. fn defined_variable(s: &Session, p: &Value, cmd: &str) -> Result> { let name = optional_name(p, "variable", cmd)?; @@ -694,13 +761,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// other than a visibility variable, locked or inside a locked layer or group, or, for any /// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. With every bound object locked, no value is -/// written; an update that writes no value adds no undo step. +/// update, so say so rather than picking one. `name` updates that row instead, and leaves the +/// active row as it is. With every bound object locked, no value is written; an update that +/// writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); + let given = match p.get("name") { + None => None, + Some(v) => Some(named(v.as_str(), "name", C)?), + }; let st = s.doc()?; - let Some(name) = st.doc.variables.active_dataset.clone() else { + let Some(name) = given.or_else(|| st.doc.variables.active_dataset.clone()) else { return Err(bad(C, "no active data set")); }; if !anything_bound(&st.doc) { @@ -985,6 +1057,15 @@ pub fn specs() -> Vec { has_doc, unbind ), + cmd!( + "variable.setBinding", + "Bind Variable", + [], + None, + "{id, slot: visibility|content, variable?} bind the object `id`'s visibility or content to one variable, or with `variable` left out or null to none, in one undo step (none when the bindings stay as they were): the object's other variables of that slot's kind are unbound. The content of type takes a text variable, of a linked image an image variable and of a graph root a graph variable; other objects have no content slot, and an embedded image can't be bound to an image variable. A variable of another kind is refused, and so is art variable.bind refuses → {id, slot, variable, unbound: [name…]}", + has_doc, + set_binding + ), cmd!( "variable.lock", "Lock Variables", @@ -1037,7 +1118,7 @@ pub fn specs() -> Vec { "Update Data Set", ["Window", "Variables"], None, - "{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", + "{all?: bool, name?} write what the bound objects hold now into the active dataset (with `name`, into that dataset, leaving the active one as it is), for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", has_doc, dataset_update ), diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index e22903eade..f87cc07654 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -194,6 +194,33 @@ pub(crate) fn objects_only(sel: &Selection) -> bool { && sel.on_path_member.is_none() } +/// How `after` starts with objects of `before` kept in their order: → how many objects of `after` +/// do, and the objects of `before` that are not among them, in order. +pub(crate) fn kept_from(before: &[NodeId], after: &[NodeId]) -> (usize, Vec) { + let (mut at, mut kept, mut removed) = (0, 0, Vec::new()); + for id in after { + let Some(i) = before[at..].iter().position(|b| b == id) else { break }; + removed.extend_from_slice(&before[at..at + i]); + at += i + 1; + kept += 1; + } + removed.extend_from_slice(&before[at..]); + (kept, removed) +} + +/// The objects of `ids` that are not in `of`, each named once, in order. +fn left_out(ids: &[NodeId], of: &[NodeId]) -> Vec { + if ids.is_empty() { + return vec![]; + } + let mut out: std::collections::HashSet = ids.iter().copied().collect(); + for id in of { + out.remove(id); + } + let mut seen = std::collections::HashSet::new(); + ids.iter().copied().filter(|id| out.contains(id) && seen.insert(*id)).collect() +} + /// What the commands scripts ran did to an open document since the person last opened or saved it /// ([`DocState::by_script`]). #[derive(Clone, Debug)] @@ -471,8 +498,10 @@ impl DocState { self.selection_record().and_then(|r| r.paints.as_ref()) } /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with - /// Lock Guides `guides_locked`. `record` is the record of the selection before: when the - /// selected objects start with its objects, the added objects are read into its paints. + /// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same + /// document: the objects that leave the selection are taken out of its paints and the objects + /// that join it are read into them, unless that reads more objects than reading the selection + /// again would, or the paints left can't be told apart without reading them again. pub(crate) fn record_selection(&mut self, record: Option, guides_locked: bool) { if !objects_only(&self.selection) { self.selection_record = None; @@ -480,16 +509,22 @@ impl DocState { } let objects = &self.selection.objects; self.selection_record = Some(match record { - Some(mut r) if objects.starts_with(&r.objects) => { - let added = &objects[r.objects.len()..]; + Some(mut r) => { if let Some(p) = &mut r.paints { - p.add(&self.doc, added); + let (kept, removed) = kept_from(&r.objects, objects); + let gone = left_out(&removed, objects); + let joined = left_out(&objects[kept..], &r.objects); + if gone.len() + joined.len() > objects.len() || !p.remove(&self.doc, &gone) { + r.paints = None; + } else { + p.add(&self.doc, &joined); + } } - r.objects.extend_from_slice(added); + r.objects.clone_from(objects); r.settled = Some(guides_locked); r } - _ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, + None => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, }); } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5896ff817..abff443d46 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -362,7 +362,8 @@ impl ScriptGate { ScriptGate { also: Some(also), ..self.clone() } } - fn check(&self, path: &str, access: Access) -> Result<(), String> { + /// May `path` be read (or written) through this gate? + pub(crate) fn check(&self, path: &str, access: Access) -> Result<(), String> { if let Some(also) = &self.also { also.check(path, access)?; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6a479adc11..083e054309 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -68,6 +68,20 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session}; mod tags; +mod variables; + +pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; + +/// What [`after_command`] compares with, taken before each command a script runs +/// ([`variables::before_command`]). +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + variables::before_command(h, id) +} + +/// After each command a script runs ([`variables::after_command`]). +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + variables::after_command(h, before); +} /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -118,7 +132,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is -/// open, and the settings of each `DocumentPreset` the run made. +/// open, the settings of each `DocumentPreset` the run made, and the `Variable` and `Dataset` +/// objects it gave out. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -126,6 +141,7 @@ pub(super) struct State { locked: RefCell>, saving: Cell, presets: RefCell>>, + vars: variables::Handles, } impl State { @@ -368,12 +384,27 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result [f64; 5] { + let [high, low] = id_parts(id); + [float(h.run), float(st.uid), high, low, float(st.reverts)] +} + +fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> { + let &[run, uid, high, low, reverts] = handle else { return None }; + let doc = find_doc(h, run, uid)?; + if h.session.borrow().documents().get(doc.index)?.reverts != whole(reverts)? { + return None; + } + Some((doc, id_of(high, low)?)) +} + /// The page item `d` names, which must still be in its document. fn item_of(h: &Host, d: &Data) -> std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if handle.len() != 5 { + return Err(HostError::Type("this is not a page item".into())); + } + let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { @@ -410,8 +441,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &node_handle(h, st, id)), + None => host_ref("Layer", &node_handle(h, st, id)), }, None => Data::Null, } @@ -1958,17 +1989,16 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(handle) = handle.filter(|parts| parts.len() == 5) else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } - let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| { let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -2134,9 +2164,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -2216,6 +2246,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + variables::define_enums(realm)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -2277,6 +2308,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(variables::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags))); classes.push(class("Document", None, document, None)); classes.push(class( @@ -2329,7 +2361,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "sliced", "uRL", "uuid", - "visibilityVariable", "wrapInside", "wrapOffset", "wrapped", @@ -2342,8 +2373,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "PageItem", m)), ); + page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(variables::classes(l)); classes.push(class( "Layer", None, diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs new file mode 100644 index 0000000000..6c405f6051 --- /dev/null +++ b/crates/engine/src/script/dom/variables.rs @@ -0,0 +1,814 @@ +//! Variables and data sets in the script object model: `Document.variables`, `dataSets`, +//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`, +//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the +//! help pages , +//! , +//! , +//! , +//! , +//! and +//! describe them. Every change runs +//! one of the `variable.*` and `dataset.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change +//! made through the object keeps the object working; once the name leaves the document any other +//! way (a delete, a rename by another command, an undo, a kind change by another command, or an +//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or +//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most +//! [`MAX_HANDLES`] of each. +//! - Collections list variables and data sets in the order the document holds them, counted from +//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`. +//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first +//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data +//! set named `Data Set 1` and so on, which becomes the active one. +//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`, +//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file +//! declared without one VectorCraft knows, and cannot be given. +//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order. +//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows +//! its values in the art, as `display()` does. +//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the +//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the +//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all. +//! An embedded image (`RasterItem`) cannot take an image variable. +//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the +//! script may read, or write, as its `File` objects may: the files of the open documents do not +//! count. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; + +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, + handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, +}; +use crate::doc::{DataSet, Node, Variable, VariableKind}; +use crate::file_access::Access; + +/// The error for a `Variable` whose variable left the document, or that came from an earlier run. +pub const STALE_VARIABLE: &str = "Stale variable"; +/// The error for a `Dataset` whose data set left the document, or that came from an earlier run. +pub const STALE_DATASET: &str = "Stale data set"; +/// The most `Variable` objects, and the most `Dataset` objects, one run gives out. +pub const MAX_HANDLES: usize = 10_000; + +/// The kinds, each with the name of its `VariableKind` member. +const KINDS: [(VariableKind, &str); 5] = [ + (VariableKind::Text, "TEXTUAL"), + (VariableKind::Visibility, "VISIBILITY"), + (VariableKind::Image, "IMAGE"), + (VariableKind::Graph, "GRAPH"), + (VariableKind::Unknown, "Unknown"), +]; + +/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a +/// variable (`None` for a data set) and whether it still names it. +struct Entry { + uid: u64, + name: String, + kind: Option, + alive: bool, +} + +/// The objects of one class a run gave out: each one's handle is its index here. +#[derive(Default)] +struct Table { + entries: Vec, + /// The entry that names each document's name, while it does. + live: HashMap<(u64, String), usize>, +} + +impl Table { + /// The entry for `name` of the document `uid`, made when there is none. + fn slot(&mut self, uid: u64, name: &str, kind: Option, what: &str) -> std::result::Result { + if let Some(&at) = self.live.get(&(uid, name.to_string())) + && self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind) + { + return Ok(at); + } + if self.entries.len() >= MAX_HANDLES { + return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run"))); + } + self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true }); + let at = self.entries.len() - 1; + self.live.insert((uid, name.to_string()), at); + Ok(at) + } + + /// The entry `at` no longer names anything. + fn kill(&mut self, at: usize) { + if let Some(e) = self.entries.get_mut(at) { + e.alive = false; + let k = (e.uid, std::mem::take(&mut e.name)); + if self.live.get(&k) == Some(&at) { + self.live.remove(&k); + } + } + } + + /// The entry `at` names `name`, of `kind`, from now on: a rename made through it. + fn rename(&mut self, at: usize, name: &str, kind: Option) { + let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return }; + self.kill(at); + if let Some(e) = self.entries.get_mut(at) { + *e = Entry { uid, name: name.to_string(), kind, alive: true }; + } + self.live.insert((uid, name.to_string()), at); + } + + /// Kills each live entry `keep` refuses. + fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) { + let gone: Vec = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect(); + for at in gone { + self.kill(at); + } + } +} + +/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last +/// checked against it. +#[derive(Default)] +pub(super) struct Handles { + vars: RefCell, + sets: RefCell
, + seen: RefCell>, +} + +/// The data sets of the active document before a command that may replace them (an import), while +/// the run holds a `Dataset`; `None` for any other command. +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() { + return None; + } + let s = h.session.try_borrow().ok()?; + s.active().map(|st| (st.uid, st.doc.variables.datasets.clone())) +} + +/// After each command a script runs: the objects whose variable or data set it removed stop +/// working, so one made again under the same name does not bring them back. An import that leaves +/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset` +/// of that document, also when the new data sets reuse the names; an import that failed, was put +/// back or left the data sets as they were stops none. +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + let hs = &h.dom.vars; + if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { + return; + } + let Ok(s) = h.session.try_borrow() else { return }; + let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid)); + let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); + let changed: HashSet = { + let seen = hs.seen.borrow(); + now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect() + }; + *hs.seen.borrow_mut() = now; + if changed.is_empty() && replaced.is_none() { + return; + } + let mut kinds: HashMap> = HashMap::new(); + let mut sets: HashMap> = HashMap::new(); + for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) { + let vars = &st.doc.variables; + kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect()); + sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect()); + } + hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind); + hs.sets + .borrow_mut() + .sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str())))); +} + +fn kind_text(k: VariableKind) -> Data { + let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n); + text(format!("VariableKind.{name}")) +} + +fn kind_of(d: &Data) -> std::result::Result { + let found = match d { + Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k), + _ => None, + }; + match found { + Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())), + Some(k) => Ok(k), + None => Err(HostError::Type("kind must be a VariableKind value".into())), + } +} + +/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes. +fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("the {what} is too long"))); + } + Ok(s) +} + +/// The `name` field of a command's result. +fn result_name(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None }) +} + +fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer { + let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?; + Ok(host_ref("Variable", &[float(h.run), float(at as u64)])) +} + +fn set_ref(h: &Host, uid: u64, name: &str) -> Answer { + let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?; + Ok(host_ref("Dataset", &[float(h.run), float(at as u64)])) +} + +/// A variable or data set an object names: its document, its handle's index and its name. +struct Named { + doc: Doc, + at: usize, + name: String, + kind: Option, +} + +/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its +/// document. +fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result { + let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) }; + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let stale = || HostError::Error(stale.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?; + let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets }; + let (uid, name, kind) = { + let t = table.borrow(); + let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?; + (e.uid, e.name.clone(), e.kind) + }; + let doc = find_doc(h, float(h.run), float(uid)); + let there = doc.is_some_and(|doc| { + with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() } + }) + }); + match doc { + Some(doc) if there => Ok(Named { doc, at, name, kind }), + _ => { + table.borrow_mut().kill(at); + Err(stale()) + } + } +} + +fn this_var(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), true) +} + +fn this_set(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), false) +} + +/// The index argument of a collection's indexer: a whole number, or `None`. +fn index_arg(d: &Data) -> Option { + match d { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_variables(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Variables", &[float(h.run), float(doc.uid)])) +} + +fn doc_datasets(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)])) +} + +fn doc_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked))) +} + +/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so. +fn doc_set_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) }; + if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked { + on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?; + } + Ok(Data::Undefined) +} + +fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Null), + } +} + +/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active +/// one and the art already shows it. +fn display(h: &Host, set: &Named) -> Answer { + let shown = with_doc(h, set.doc, |_, st| { + let vars = &st.doc.variables; + vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values())) + }); + if !shown { + on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?; + } + Ok(Data::Undefined) +} + +fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + if handle_of(arg(a, 1), "Dataset").is_none() { + return Err(HostError::Type("activeDataset must be a Dataset".into())); + } + let set = named_of(h, arg(a, 1), false)?; + if set.doc.uid != doc.uid { + return Err(HostError::Error("the data set is in another document".into())); + } + display(h, &set) +} + +/// The path of the `File` argument of `what`, which must be a file the script may reach for +/// `access` through its own `File` objects. +fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result { + let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) }; + if path.chars().count() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(format!("{what}: the path is too long"))); + } + let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default()); + gate.check(path, access).map_err(HostError::Error)?; + Ok(path.to_string()) +} + +/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's +/// variables and data sets with the library's. +fn doc_import(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "importVariables", Access::Read)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +/// `exportVariables(file)`: `variable.saveLibrary` into the file. +fn doc_export(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "exportVariables", Access::Write)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +// ---- Variables ---- + +fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Variables") +} + +fn vars_typename(h: &Host, a: &[Data]) -> Answer { + vars_doc(h, a)?; + Ok(text("Variables")) +} + +fn vars_length(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64))) +} + +fn vars_parent(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn vars_at(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) { + Some(v) => var_ref(h, doc.uid, &v), + None => Ok(Data::Undefined), + } +} + +fn vars_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.variables.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.variable(name).cloned()) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v)) +} + +fn vars_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => vars_by_name(h, a), + Data::Number(_) => match vars_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the +/// first free name). → the new variable. +fn vars_add(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + (1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default() + }); + on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?; + var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text }) +} + +/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is +/// none. +fn vars_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Variable ---- + +fn var_typename(h: &Host, a: &[Data]) -> Answer { + this_var(h, a)?; + Ok(text("Variable")) +} + +fn var_parent(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(doc_ref(h, v.doc.uid)) +} + +fn var_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_var(h, a)?.name)) +} + +/// `name = text`: `variable.rename`, which trims it, with no command when the name stays. +fn var_set_name(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == v.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind); + Ok(Data::Undefined) +} + +fn var_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown))) +} + +/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot +/// hold it and drops the variable's values, with no command when the kind stays. +fn var_set_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let kind = kind_of(arg(a, 1))?; + if Some(kind) == v.kind { + return Ok(Data::Undefined); + } + on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?; + h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind)); + Ok(Data::Undefined) +} + +fn var_page_items(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + with_doc(h, v.doc, |_, st| { + let ids: Vec = + st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) + }) +} + +/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values. +fn var_remove(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?; + h.dom.vars.vars.borrow_mut().kill(v.at); + Ok(Data::Undefined) +} + +// ---- Datasets ---- + +fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Datasets") +} + +fn sets_typename(h: &Host, a: &[Data]) -> Answer { + sets_doc(h, a)?; + Ok(text("Datasets")) +} + +fn sets_length(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64))) +} + +fn sets_parent(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn sets_at(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Undefined), + } +} + +fn sets_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.datasets.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone())) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n)) +} + +fn sets_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => sets_by_name(h, a), + Data::Number(_) => match sets_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new +/// data set and makes it the active one. → the new data set. +fn sets_add(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?; + let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?; + set_ref(h, doc.uid, &name) +} + +/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is +/// none. +fn sets_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Dataset ---- + +fn set_typename(h: &Host, a: &[Data]) -> Answer { + this_set(h, a)?; + Ok(text("Dataset")) +} + +fn set_parent(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + Ok(doc_ref(h, d.doc.uid)) +} + +fn set_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_set(h, a)?.name)) +} + +/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays. +fn set_set_name(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == d.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.sets.borrow_mut().rename(d.at, &name, None); + Ok(Data::Undefined) +} + +fn set_display(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + display(h, &d) +} + +/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no +/// command when it already holds what the bound objects hold. +fn set_update(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let same = with_doc(h, d.doc, |_, st| { + let doc = &st.doc; + let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()); + bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values())) + }); + if !same { + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?; + } + Ok(Data::Undefined) +} + +/// `dataset.remove()`: `dataset.delete` of this data set. +fn set_remove(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?; + h.dom.vars.sets.borrow_mut().kill(d.at); + Ok(Data::Undefined) +} + +// ---- Page items ---- + +/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its +/// content. +fn slot_kind(n: &Node, content: bool) -> std::result::Result { + if !content { + return Ok(VariableKind::Visibility); + } + crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into())) +} + +/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's +/// kind bound to the object, in the order the variables are defined, or `null`. +fn binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let found = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned()) + })?; + match found { + Some(v) => var_ref(h, item.doc.uid, &v), + None => Ok(Data::Null), + } +} + +/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of +/// the object's document, or with none for `null`. No command runs when the object already has just +/// that binding of the slot's kind. +fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let variable = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "Variable").is_some() => { + let v = named_of(h, d, true)?; + if v.doc.uid != item.doc.uid { + return Err(HostError::Error("the variable is in another document".into())); + } + Some(v.name) + } + _ => return Err(HostError::Type("give a Variable or null".into())), + }; + let same = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + let held: Vec<&str> = + vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect(); + Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::>()) + })?; + if !same { + let slot = if content { "content" } else { "visibility" }; + edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?; + } + Ok(Data::Undefined) +} + +fn item_visibility(h: &Host, a: &[Data]) -> Answer { + binding(h, a, false) +} + +fn item_set_visibility(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, false) +} + +fn item_content(h: &Host, a: &[Data]) -> Answer { + binding(h, a, true) +} + +fn item_set_content(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, true) +} + +// ---- Registration ---- + +/// The members this module adds to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("variables", get(l, doc_variables)), + ("dataSets", get(l, doc_datasets)), + ("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)), + ("variablesLocked", property(l, doc_locked, doc_set_locked)), + ("importVariables", method(l, doc_import)), + ("exportVariables", method(l, doc_export)), + ]) +} + +/// The members this module adds to `PageItem`. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))]) +} + +/// The members this module adds to the page item class `class`. +pub(super) fn item_members(l: &Link, class: &str) -> Vec<(String, HostMember)> { + match class { + "TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => named(vec![("contentVariable", property(l, item_content, item_set_content))]), + _ => Vec::new(), + } +} + +/// The classes this module adds. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "Variables", + None, + named(vec![ + ("typename", get(l, vars_typename)), + ("length", get(l, vars_length)), + ("parent", get(l, vars_parent)), + ("index", method(l, vars_index)), + ("getByName", method(l, vars_by_name)), + ("add", method(l, vars_add)), + ("removeAll", method(l, vars_remove_all)), + ]), + Some(function(l, vars_at)), + ), + class( + "Variable", + None, + named(vec![ + ("typename", get(l, var_typename)), + ("parent", get(l, var_parent)), + ("name", property(l, var_name, var_set_name)), + ("kind", property(l, var_kind, var_set_kind)), + ("pageItems", get(l, var_page_items)), + ("remove", method(l, var_remove)), + ]), + None, + ), + class( + "Datasets", + None, + named(vec![ + ("typename", get(l, sets_typename)), + ("length", get(l, sets_length)), + ("parent", get(l, sets_parent)), + ("index", method(l, sets_index)), + ("getByName", method(l, sets_by_name)), + ("add", method(l, sets_add)), + ("removeAll", method(l, sets_remove_all)), + ]), + Some(function(l, sets_at)), + ), + class( + "Dataset", + None, + named(vec![ + ("typename", get(l, set_typename)), + ("parent", get(l, set_parent)), + ("name", property(l, set_name, set_set_name)), + ("display", method(l, set_display)), + ("update", method(l, set_update)), + ("remove", method(l, set_remove)), + ]), + None, + ), + ] +} + +/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings. +pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect(); + realm.define_host_object("VariableKind", items) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index c5fffb6574..70c8938ba4 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1354,6 +1354,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); + let before = dom::before_command(host, &id); let r = { let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) @@ -1387,6 +1388,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + dom::after_command(host, before); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 02d57296ce..3d67b3a482 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -2,7 +2,7 @@ use super::{ Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane, objects_in_range, }; -use crate::doc_state::objects_only; +use crate::doc_state::{kept_from, objects_only}; impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one @@ -237,17 +237,19 @@ impl Session { let new_art = st.selection.new_art.clone(); let record = if st.selection_record().is_some() { st.selection_record.take() } else { None }; f(&st.doc, &mut st.selection); - let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before); - // Objects added to objects this checked in the same document, with Lock Guides as it was - // then and no art on a locked artboard to protect, are checked alone, by the rules `prune` - // and `deselect_hidden` apply to an object. + // Objects this checked in the same document, kept in their order, with Lock Guides as it + // was then and no art on a locked artboard to protect, need no check again: only the + // objects after them are checked, by the rules `prune` and `deselect_hidden` apply to an + // object. let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked)) + && objects_only(&st.selection) && st.selection.new_art.is_empty() && st.doc.new_art.get().is_empty() && !st.doc.artboards.iter().any(|a| a.locked); - if added && settled { + if settled { let doc = &st.doc; - let tail = st.selection.objects.split_off(before.len()); + let (kept, _) = kept_from(&before, &st.selection.objects); + let tail = st.selection.objects.split_off(kept); st.selection.objects.extend(tail.into_iter().filter(|id| { doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. }))) })); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index e1a2061ba8..1437e9c56c 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -180,26 +180,28 @@ fn list_files(dir: &Path, ext: &str) -> Vec { /// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it. fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> { let Ok(entries) = std::fs::read_dir(dir) else { return vec![] }; - let mut files: Vec<_> = entries - .filter_map(Result::ok) - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext))) - .filter_map(|p| { - let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; - match m.modified() { - Ok(t) => Some((p, (m.len(), t))), - Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", p.display()); - None - } - } - }) - .collect(); + let mut files: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).filter_map(|p| stamped_file(p, ext)).collect(); files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase())); files.truncate(MAX_STORE_FILES); files } +/// The file `p` with its size and modified time, as [`list_stamped_files`] lists it: `None` unless +/// it is a regular file with the extension `ext`. +fn stamped_file(p: PathBuf, ext: &str) -> Option<(PathBuf, (u64, SystemTime))> { + if !p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)) { + return None; + } + let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; + match m.modified() { + Ok(t) => Some((p, (m.len(), t))), + Err(e) => { + skip_stored(&p, e); + None + } + } +} + /// The content of `path` when it is at most `max` bytes; the file is never read past `max`. pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?; @@ -312,6 +314,8 @@ pub(crate) struct StoredLoad { loads: Loads, /// Outcomes taken from `loads` and not installed yet, in order. loaded: VecDeque>, + /// The ids this load installed, in file-name order. + installed: Vec, /// The next file to install. next: usize, /// The store's grants this load removed, by id, because the module stored for the id lists no @@ -369,6 +373,45 @@ fn after_stored_load(path: &Path) { /// Why a stored plug-in whose file changed between its listing and its install is skipped. const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded"; +/// The stored plug-in files that didn't install in this process, by path, with why +/// ([`skip_stored`]). A file stays listed until it installs or its store is loaded again. +static STORED_FAILED: Mutex> = Mutex::new(BTreeMap::new()); + +/// The stored plug-ins skipped ([`STORED_FAILED`]). +fn stored_failures() -> MutexGuard<'static, BTreeMap> { + STORED_FAILED.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Skips the stored plug-in `path` because of `why`: logs it and lists the file as failed. +fn skip_stored(path: &Path, why: impl std::fmt::Display) { + log::warn!("skipping the stored plug-in {}: {why}", path.display()); + stored_failures().insert(path.to_path_buf(), why.to_string()); +} + +/// The stored plug-in files in the plug-in store `dir` that didn't install in this process, in +/// file-name order, each with why. +pub(crate) fn failed_stored_plugins(dir: &Path) -> Vec<(PathBuf, String)> { + stored_failures().iter().filter(|(p, _)| p.parent() == Some(dir)).map(|(p, why)| (p.clone(), why.clone())).collect() +} + +/// Stops listing the stored plug-in file `path` as failed: a plug-in installed from it. +pub(crate) fn clear_stored_failure(path: &Path) { + stored_failures().remove(path); +} + +/// A plug-in installed from the stored file `path`: it is no longer listed as failed, by the store +/// (a load in another session may have failed on it meanwhile) or by the folder report of a +/// `plugin.reload` of the store's folder. +fn installed_from(path: &Path) { + clear_stored_failure(path); + crate::cmd::plugin::clear_folder_failure(path); +} + +/// Why the stored plug-in `path` didn't install in this process, if it is listed as failed. +pub(crate) fn stored_failure(path: &Path) -> Option { + stored_failures().get(path).cloned() +} + #[cfg(test)] thread_local! { /// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]). @@ -408,11 +451,15 @@ fn list_stored_plugins(rest: &mut VecDeque, left: &mut u64) -> (Vec< let most = *left + taken; if most == 0 { log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); - rest.clear(); + let why = format!("the stored plug-ins hold more than {MAX_PLUGIN_STORE} bytes together"); + let mut failed = stored_failures(); + for (path, _) in std::iter::once((path, stamp)).chain(rest.drain(..)) { + failed.insert(path, why.clone()); + } break; } if len > most { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most)); + skip_stored(&path, too_large(most)); continue; } // An empty file too waits once `left` is used up. @@ -774,7 +821,7 @@ impl Session { pub fn attach_plugin_store(&mut self, dir: PathBuf) { self.finish_plugin_loads(); self.plugin_dir = Some(dir); - self.start_stored_plugins(true); + self.start_stored_plugins(true, None); } /// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user @@ -791,34 +838,58 @@ impl Session { /// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With /// [`Session::load_plugins_in_background`] on, this returns while the modules load. pub fn load_stored_plugins(&mut self) { - self.start_stored_plugins(false); + self.start_stored_plugins(false, None); + } + + /// Loads the stored plug-in `path` again, as [`Session::load_stored_plugins`] loads each file, + /// and waits until it is installed or skipped (`plugin.retry`) → the id it installed, if any. + pub(crate) fn retry_stored_plugin(&mut self, path: &Path) -> Option { + self.finish_plugin_loads(); + self.start_stored_plugins(false, Some(path)) } /// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the - /// folder ([`DISABLED_FILE`]). - fn start_stored_plugins(&mut self, disabled: bool) { - let Some(dir) = self.plugin_dir.clone() else { return }; + /// folder ([`DISABLED_FILE`]); `only`: load that one file of the folder, if it is there. The + /// files it loads stop being listed as failed ([`failed_stored_plugins`]) until they fail again. + /// With `only`, waits for the load → the id it installed, if any. + fn start_stored_plugins(&mut self, disabled: bool, only: Option<&Path>) -> Option { + let dir = self.plugin_dir.clone()?; // A `plugin.install` in another session or process writes the store before this lists it. let held = crate::cmd::plugin::hold_plugin_changes(); let turn = self.plugin_store_turn_for_load(); + match only { + Some(path) => { + stored_failures().remove(path); + } + None => stored_failures().retain(|p, _| p.parent() != Some(dir.as_path())), + } if disabled { let path = dir.join(DISABLED_FILE); let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); safe_mode::set_disabled(saved); } if safe_mode::active() { - return; + return None; } let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64; let mut rest = VecDeque::new(); let disabled: BTreeSet = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect(); - for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) { + // A retry reads its one file without listing the folder again. + let listed: Vec<_> = match only { + Some(path) => stamped_file(path.to_path_buf(), PLUGIN_EXT).filter(|(p, _)| p.parent() == Some(dir.as_path())).into_iter().collect(), + None => list_stamped_files(&dir, PLUGIN_EXT), + }; + // A retried file that isn't there (yet) stays listed, so a later retry can load it. + if let Some(path) = only.filter(|p| listed.is_empty() && stored_failure(p).is_none()) { + skip_stored(path, "it is no longer in the plug-in store"); + } + for (path, stamp) in listed { let item = safe_mode::Item::file(path.display().to_string()); let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref())); if safe_mode::skipped(&item) || by_id { log::info!("skipping the stored plug-in {}: disabled", path.display()); } else if stamp.0 > module { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module)); + skip_stored(&path, too_large(module)); } else { rest.push_back((path, Some(Some(stamp)))); } @@ -830,9 +901,24 @@ impl Session { changes.start(); // The modules load after the turn, once the loads queued before them are done. drop((turn, held)); - let load = - StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left }; + let load = StoredLoad { + dir, + files, + loads: Loads::deferred(jobs), + loaded: VecDeque::new(), + installed: Vec::new(), + next: 0, + retired: BTreeMap::new(), + changes, + rest, + left, + }; + if only.is_some() { + let report = self.finish_plugin_load(PluginLoad::Stored(load)); + return report["loaded"].as_array()?.first()?.as_str().map(str::to_string); + } self.queue_plugin_load(PluginLoad::Stored(load)); + None } /// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the @@ -877,7 +963,7 @@ impl Session { // The worker read the file again once its module loaded ([`list_stored_plugins`]); one // whose stamp changed since then is skipped too. if file_stamp(path).ok() != *stamp { - log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display()); + skip_stored(path, CHANGED_WHILE_LOADING); continue; } match loaded { @@ -901,7 +987,7 @@ impl Session { // grant it, so it wouldn't load at the next launch either. if back.is_some() { if !self.store_grant_in(turn, &m.id, Some(g.clone())) { - log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display()); + skip_stored(path, "couldn't put back its grant"); continue; } load.retired.remove(&m.id); @@ -922,6 +1008,8 @@ impl Session { ) { Ok(Some(p)) => { load.changes.installed(&p); + load.installed.push(p.id().to_string()); + installed_from(path); true } Ok(None) => { @@ -929,7 +1017,7 @@ impl Session { false } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); false } }; @@ -945,9 +1033,7 @@ impl Session { } } } - None => { - log::warn!("skipping the stored plug-in {}: the user hasn't granted this module the permissions it lists", path.display()) - } + None => skip_stored(path, "the user hasn't granted this module the permissions it lists"), } } Ok(plugin) => { @@ -968,11 +1054,13 @@ impl Session { continue; } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); continue; } }; load.changes.installed(&p); + load.installed.push(p.id().to_string()); + installed_from(path); // In the same turn: the grants for the id stop counting, the process's and the // store's, so no session sees the earlier module as approved. A module installed // in its place meanwhile keeps the process's grant recorded for it. @@ -989,7 +1077,7 @@ impl Session { } } } - Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), + Err(e) => skip_stored(path, e), } } } @@ -1073,7 +1161,7 @@ impl Session { } /// Waits for `load`'s modules and installs them as they load, in turns on the store, then - /// ends it → its report (a folder's; `null` for the stored plug-ins). + /// ends it → its report (the installed ids for the stored plug-ins). pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value { load.start(); loop { @@ -1142,7 +1230,7 @@ impl Session { } } - /// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's). + /// Ends `load` once [`PluginLoad::done`], in `turn` → its report. fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value { // The loads queued after it count what it installed as their own: one of theirs replaces // it, as it would have with the loads run one after the other. @@ -1155,7 +1243,7 @@ impl Session { } match load { // A stored load's grants were settled as each module installed. - PluginLoad::Stored(_) => Value::Null, + PluginLoad::Stored(load) => serde_json::json!({"loaded": load.installed}), PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn), } } @@ -1288,9 +1376,19 @@ impl Session { } /// Write the module `bytes` of the plug-in `id` to the store in `turn` → whether they went there - /// (`false` without a folder, and when `turn` isn't held). + /// (`false` without a folder, and when `turn` isn't held). The file written is no longer listed + /// as failed ([`failed_stored_plugins`]). pub(crate) fn store_plugin(&self, turn: &StoreTurn, id: &str, bytes: &[u8]) -> bool { - turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes)) + let name = format!("{}.{PLUGIN_EXT}", file_stem(id)); + turn.held() + && self.plugin_dir.as_deref().is_some_and(|dir| { + let written = put(dir, &name, bytes); + if written { + stored_failures().remove(&dir.join(&name)); + crate::cmd::plugin::clear_folder_failure(&dir.join(&name)); + } + written + }) } /// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and @@ -1496,9 +1594,19 @@ impl Session { } /// 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). + /// folder, and when `turn` isn't held). A file removed is no longer listed as failed + /// ([`failed_stored_plugins`]). pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { - turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)))) + let name = format!("{}.{PLUGIN_EXT}", file_stem(id)); + turn.held() + && self.plugin_dir.as_deref().is_some_and(|dir| { + let gone = take(dir, &name); + if gone { + stored_failures().remove(&dir.join(&name)); + crate::cmd::plugin::clear_folder_failure(&dir.join(&name)); + } + gone + }) } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 94024b4cf5..bc6b04b0dc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -185,6 +185,7 @@ mod script_include; mod script_io; mod script_run; mod script_tags; +mod script_variables; mod script_xmp; mod scripts; mod segment_nudge; @@ -375,15 +376,23 @@ fn unknown_command_names_the_nearest_id() { assert!(e.to_string().contains("did you mean `select.all`?"), "{e}"); } +/// An unknown command id or parameter key of 200,000 characters is answered without measuring +/// its distance to every id and key: it takes no more character comparisons than one of 20. #[test] fn a_long_unknown_command_id_is_answered_at_once() { + use crate::cmd::params::DISTANCE_CELLS; let mut s = session(); - let long = "x".repeat(200_000); - let start = std::time::Instant::now(); - assert!(matches!(s.execute(&long, &json!({})), Err(EngineError::UnknownCommand(_)))); - let e = crate::check_params("file.new", &json!({ long.as_str(): 1 })).unwrap_err(); - assert!(e.to_string().contains("the command takes:"), "{e}"); - assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed()); + let mut compared = |id: &str| { + DISTANCE_CELLS.set(0); + assert!(matches!(s.execute(id, &json!({})), Err(EngineError::UnknownCommand(_))), "{}", id.len()); + let e = crate::check_params("file.new", &json!({ id: 1 })).unwrap_err(); + assert!(e.to_string().contains("the command takes:"), "{e}"); + DISTANCE_CELLS.get() + }; + let short = compared(&"x".repeat(20)); + let long = compared(&"x".repeat(200_000)); + assert!(short > 0, "a 20-character id is measured against the ids near its length"); + assert!(long <= short, "200,000 characters: {long} comparisons, 20 characters: {short}"); } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 81d6b3bc65..b3ca69fbc7 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -721,3 +721,30 @@ fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() { assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); } + +/// `select.toggle` run once for each of `n` selected objects, in the order they were selected, +/// until none is selected → the walks of the tree and the lookups by id it took. +fn remove_one_at_a_time(n: usize) -> (u64, u64) { + let mut s = session(n, square); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + for id in &ids { + s.execute("select.toggle", &json!({"id": id.0})).unwrap(); + } + assert!(s.doc().unwrap().selection.objects.is_empty()); + (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups) +} + +/// Deselecting objects one at a time checks and reads only the object each `select.toggle` takes +/// out: twice as many objects take about twice as many lookups, and the tree is not walked for +/// each one. +#[test] +fn deselecting_objects_one_at_a_time_looks_up_only_the_removed_objects() { + let (walks, lookups) = remove_one_at_a_time(1_000); + let (more_walks, more_lookups) = remove_one_at_a_time(2_000); + assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); + assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); +} diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index b139ee5927..0c6cc8dfdc 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -233,6 +233,43 @@ fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() { assert_eq!(s.paint.fill, blue, "a, b and c are all blue now"); } +fn toggle(s: &mut Session, id: NodeId) { + run(s, "select.toggle", json!({"id": id.0})); +} + +/// Objects taken out one at a time leave the others to be compared: a fill and weight the objects +/// left share loads, one they don't stays as it was. +#[test] +fn objects_taken_out_one_at_a_time_load_only_the_paints_the_objects_left_share() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#00ffff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0); + let d = painted(&mut s, 320.0, "#ff0000", "#00ff00", 5.0); + let red = node(&s, a).appearance.fill_paint(); + select(&mut s, &[a, b, c, d]); + (s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5); + toggle(&mut s, c); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 5.0), "a, b and d share the weight, not the fill"); + s.paint.stroke_width = 0.5; + toggle(&mut s, b); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and d share both"); +} + +/// Taking out every object with the fill met first leaves the other objects' fills to compare. +#[test] +fn taking_out_the_objects_with_the_first_fill_compares_the_fills_left() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#0000ff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0); + let blue = node(&s, b).appearance.fill_paint(); + select(&mut s, &[a, b, c]); + s.paint.fill = Paint::None; + toggle(&mut s, a); + assert_eq!(s.paint.fill, blue, "b and c are both blue"); +} + #[test] fn art_without_paint_leaves_the_proxies_as_they_were() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index b65d4a4b9a..f41253ec22 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -892,6 +892,167 @@ fn a_profiles_normal_character_style_is_the_default_font() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("apply-defaults"); + const GLOW: &str = r#""#; + // The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with + // the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Laser Red", "color": "#ff0000", "global": true})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": GLOW})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"swatch": "Laser Red"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Glow7653"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + let serif = + s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Serif", "font": "Source Serif 4", "size": 9, "color": "#ff0000"})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": serif["id"]})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + // An RGB document made without a profile, with another filter named Glow7653, type in the + // default font and a rectangle linked to its Default Graphic Style. + s.execute("file.new", &json!({"colorMode": "rgb"})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": r#""#})).unwrap(); + let before = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Before"})).unwrap(); + let linked = s.execute("shape.rectangle", &json!({"x": 20, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let default_font = first_run(&s, &before["id"]); + + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "print"})).unwrap(); + assert_eq!((r["name"].clone(), r["changed"].clone()), (json!("Print"), json!(true)), "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + // The swatch comes along, in the document's color mode, and the style paints with it. + let d = &s.doc().unwrap().doc; + let red = d.swatches.iter().find(|w| w.name == "Laser Red").cloned().expect("the style's swatch"); + assert!(matches!(red.paint, Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); + let stroke = s.paint.stroke.clone(); + assert!(matches!(&stroke, Paint::Solid { swatch: Some(w), .. } if w == "Laser Red"), "{stroke:?}"); + // The profile's filter keeps its definition under a free name; the document's keeps its own. + let style = d.graphic_style("Default Graphic Style").cloned().unwrap(); + let filter = style.appearance.effects.iter().find(|e| e.id == "svg.filter").cloned().expect("the style's filter"); + assert_ne!(filter.params["name"], "Glow7653", "{filter:?}"); + assert!(filter.params["xml"].as_str().is_some_and(|x| x.contains("dx=\"3\"")), "{filter:?}"); + assert!(d.svg_filters.iter().any(|f| f.name == "Glow7653" && f.xml.contains("dx=\"9\""))); + // New art takes the profile's look; so does the rectangle linked to the style. + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(look(&s, id), (Paint::None, stroke.clone(), Some(0.25))); + assert_eq!(look(&s, linked), (Paint::None, stroke.clone(), Some(0.25))); + // New type starts in the profile's font, and type in [Normal Character Style] follows it. + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "After"})).unwrap(); + for id in [&made["id"], &before["id"]] { + let st = first_run(&s, id); + assert_eq!((st.font_family.as_str(), st.size), ("Source Serif 4", 9.0)); + // The profile's CMYK red is converted to the document's color mode. + assert!( + matches!(st.fill, Paint::Solid { color: vectorcraft_color::Color::Rgb { r, g, b }, .. } if r > 0.8 && g < 0.3 && b < 0.3), + "a converted red: {:?}", + st.fill + ); + } + // Again: nothing changes and no undo step is recorded. + let step = s.doc().unwrap().history.step(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.doc().unwrap().history.step(), step); + + // A category without a profile file gives the shipped defaults back. + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let print_paint = s.paint.clone(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Web"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + let st = first_run(&s, &before["id"]); + assert_eq!((st.font_family, st.size), (default_font.font_family.clone(), default_font.size)); + // Undo goes back to the Print profile's defaults in the document and for new art; Redo + // brings the shipped ones again. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first_run(&s, &before["id"]).font_family, "Source Serif 4"); + assert_eq!(s.paint, print_paint); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + s.execute("edit.undo", &json!({})).unwrap(); + + // An unknown profile is an error and changes nothing. + let step = s.doc().unwrap().history.step(); + assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err()); + assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err()); + assert_eq!(s.doc().unwrap().history.step(), step); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's +/// defaults that Use Profile Defaults has just set. +#[test] +fn profile_defaults_stay_with_an_unrelated_object_selected() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("apply-defaults-selected"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + s.execute("file.new", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "newArtBasic", "value": false})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open +/// document that composite font too, in place of the document's of the same name. +#[test] +fn profile_defaults_bring_the_composite_font_of_the_default_font() { + let font = |roman: f64| { + json!({"name": "CF Profile 7653", "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "JetBrains Mono", "size": roman}, + }}) + }; + let (mut s, dir) = with_profiles("apply-defaults-composite"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": t["id"]})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font(100.0)]})).unwrap(); + let profile = |s: &Session| s.doc().unwrap().doc.composite_fonts.iter().find(|f| f.name == "CF Profile 7653").map(|f| f.parts.roman.size); + assert_eq!(profile(&s), Some(100.0)); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!(profile(&s), Some(50.0), "the profile's definition"); + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Ab"})).unwrap(); + assert_eq!(first_run(&s, &made["id"]).font_family, "CF Profile 7653"); + let missing = s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().filter(|f| f["missing"] == true).count(); + assert_eq!(missing, 0); + // Again: nothing changes. + let step = s.doc().unwrap().history.step(); + assert_eq!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap()["changed"], false); + assert_eq!(s.doc().unwrap().history.step(), step); + // Undone, the document's own definition is back. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(profile(&s), Some(100.0)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let (mut s, dir) = with_profiles("errors"); diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index bbc71b8dc0..016b5e6373 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -222,8 +222,9 @@ fn blue_rect(s: &mut Session) -> NodeId { } /// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo -/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the -/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles. +/// step: the pattern keeps its name, swatch, place and options, the tile keeps its size and moves as +/// far as the art's bounds moved, art painted with it keeps the paint, and the selected art stays on +/// the canvas, selected. Undo and Redo swap the two tiles. #[test] fn replace_art_gives_a_pattern_new_tile_art() { let mut s = session(); @@ -243,7 +244,9 @@ fn replace_art_gives_a_pattern_new_tile_art() { assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle"); assert_eq!(def.art[0].appearance, node(&s, blue).appearance); assert_ne!(def.art[0].id, blue, "a copy with an id of its own"); - assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay"); + // The red square's bounds start at (0, 0) and the blue rectangle's at (100, 100). + assert_eq!(def.tile, old.tile + vectorcraft_geom::Vec2::new(100.0, 100.0), "the tile moves with the art"); + assert_eq!((def.tile_type, &def.name), (old.tile_type, &old.name), "the options stay"); assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch"); assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern"); assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays"); @@ -282,6 +285,164 @@ fn replace_art_that_matches_the_tile_art_records_nothing() { assert_eq!(doc(&s), &before); } +/// The geometric bounds of object `id`. +fn bounds_of(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +/// Place Pattern Art places a copy of the tile art in a group with an unpainted rectangle of the +/// tile at its back, centered where it is asked for (by default the first artboard's center), in +/// the current layer, selected, as one undo step; the pattern does not change. +#[test] +fn place_art_places_the_tile_art_with_its_tile() { + let mut s = session(); + let red = make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(-5.0, -5.0, 15.0, 15.0)); + let steps = s.doc().unwrap().history.undo.len(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Place Pattern Art"))); + assert_eq!(st.selection.objects.to_vec(), vec![id], "the copy is selected"); + assert_eq!(st.doc.parent_of(id), Some(st.doc.layers[0].id), "in the current layer"); + assert_eq!(doc(&s).pattern("Dots").unwrap(), &def, "the pattern stays as it was"); + let group = node(&s, id); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("a group: {:?}", group.kind) }; + let [marker, art] = children.as_slice() else { panic!("the tile and the art: {children:?}") }; + // The tile, centered on (200, 150), is unpainted; the art keeps its place in the tile. + assert_eq!(marker.geometric_bounds(), Some(Rect::new(190.0, 140.0, 210.0, 160.0))); + assert!(marker.appearance.fill_paint().is_none() && marker.appearance.stroke().is_none_or(|k| k.paint.is_none())); + assert_eq!(art.geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + assert_eq!(art.appearance, def.art[0].appearance); + assert!(art.id != red && art.id != def.art[0].id, "a copy with an id of its own"); + // Without a position: the first artboard's center (the document is 400 × 400). + let centered = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap()); + assert_eq!(bounds_of(&s, centered).center(), Point::new(200.0, 200.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(centered).is_none(), "Undo removes the copies"); +} + +/// The placed copy, edited and given back with Replace Pattern Art, becomes the tile art, and its +/// rectangle becomes the tile: the art keeps its place in the tile, so the pattern draws the same +/// arrangement with the new art. Given back unchanged, nothing is recorded. +#[test] +fn placed_art_given_back_keeps_its_place_in_the_tile() { + let mut s = session(); + make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 210.0, 160.0), "the rectangle is the tile"); + assert_eq!(def.art.len(), 1, "the rectangle is not part of the art: {:?}", def.art); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + let old = before.pattern("Dots").unwrap(); + let place = |tile: Rect, art: &[Arc]| vectorcraft_doc::live::nodes_bounds(art).unwrap().origin() - tile.origin(); + assert_eq!(place(def.tile, &def.art), place(old.tile, &old.art), "the art keeps its place in the tile"); + // Given back again without a change: nothing to record. + let (again, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(doc(&s), &again); + // Edited (the art recolored and the rectangle widened, ungrouped): the new art and tile. + let NodeKind::Group { children, .. } = &node(&s, id).kind else { panic!("a group") }; + let (marker, art) = (children[0].id, children[1].id); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + sel(&mut s, &[id]); + s.execute("object.ungroup", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(marker).is_some() && doc(&s).node(art).is_some(), "ungrouped"); + s.execute("object.transform", &json!({"ids": [marker.0], "matrix": [2, 0, 0, 1, -190, 0]})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [marker.0, art.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 230.0, 160.0), "the widened rectangle is the tile"); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].appearance, node(&s, art).appearance, "the recolored art"); +} + +/// Only an unpainted rectangle at the back of the art is the tile: a painted one, or an unpainted +/// one in front of other art, is tile art like any other, and a rectangle alone leaves no art. +#[test] +fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { + let mut s = session(); + make_dots(&mut s); + let back = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let front = rect(&mut s, 110.0, 110.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [front.0], "color": "#00ff00"})).unwrap(); + // Painted: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "color": "#ffffff"})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted, but in front of the other art: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [back.0], "none": true})).unwrap(); + sel(&mut s, &[back]); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted and at the back: the tile. + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!((def.art.len(), def.tile), (1, Rect::new(100.0, 100.0, 140.0, 140.0))); + // A rectangle alone is a tile with no art. + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); + assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); + // An unpainted path through the four corners of its bounds in a crossing order is not a + // rectangle: art. + let corners = [(200, 200), (240, 240), (240, 200), (200, 240)]; + let anchors: Vec<_> = corners.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let bowtie = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + sel(&mut s, &[bowtie]); + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [bowtie.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.art.len(), 2, "the crossing path is art: {:?}", def.art); + assert_ne!(def.tile, Rect::new(200.0, 200.0, 240.0, 240.0), "the crossing path is not the tile"); +} + +/// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that +/// is not a number, a pattern with no art, while a pattern is edited and on a locked layer. +#[test] +fn place_art_is_refused_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + doc_mut(&mut s).patterns.push(vectorcraft_doc::pattern::PatternDef::new("Empty", vec![])); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let unchanged = |s: &Session, case: &str| { + assert_eq!(doc(s), &before, "{case}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step"); + }; + for (case, p, why) in [ + ("no name", json!({}), "missing name"), + ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`"), + ("x not a number", json!({"name": "Dots", "x": "100"}), "`x` must be a number"), + ("y not a number", json!({"name": "Dots", "y": true}), "`y` must be a number"), + ("no art", json!({"name": "Empty"}), "no artwork"), + ] { + let err = s.execute("pattern.placeArt", &p).unwrap_err(); + assert!(err.to_string().contains(why), "{case}: {err}"); + unchanged(&s, case); + } + let layer = doc(&s).layers[0].id; + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": true})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert_eq!(err.to_string(), "the target layer is locked or hidden"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "locked: unchanged"); + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": false})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "while editing: unchanged"); +} + /// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art, /// while a pattern is edited, and for art painted with the pattern itself, directly, through /// another pattern, through a symbol, through the paints a graph stores, through a graph design a diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 7086c7f92e..94da32aa01 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -1224,9 +1224,16 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to let reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view).unwrap(); let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") }; assert_eq!(p["rect"], json!([10.0, 10.0, 40.0, 20.0])); + assert_eq!(p[vectorcraft_tools::place::SOURCE_INDEX], 0); + assert_eq!(p[vectorcraft_tools::place::CLICK], true); assert!(top_children(&s).is_empty(), "the frontend places it"); assert_eq!(s.tool_options()["names"], json!(["b.png"]), "the cursor goes on to the next file"); - s.execute("file.place", p).unwrap(); + // The frontend consumes the private source identity before placing the file. + let mut p = p.clone(); + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + p.as_object_mut().unwrap().remove(key); + } + s.execute("file.place", &p).unwrap(); // Left out: the second each document was made in. let doc = |s: &Session| { let mut d = (*s.doc().unwrap().doc).clone(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..fd1f803651 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -16,7 +16,7 @@ const DESATURATE_ID: &str = "org.vectorcraft.example.desaturate"; /// Held by the tests that set the Additional Plug-ins Folder preference or run `plugin.reload`: /// the folder last loaded and its report are kept for the whole process, so another test loading /// its own folder between two steps would change what the next step loads or lists. -static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); +pub(super) static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) @@ -622,6 +622,60 @@ fn a_painted_live_effect_draws_its_pieces_with_their_own_paints() { assert_eq!(node(&s, id).appearance.effects[0].id, "plugin.test.engine.paints"); } +/// A piece that an effect declaring `appearanceOutput` returns with 50% opacity, Multiply and +/// Offset Path keeps that look in SVG and PDF export, which leave the document alone, and Expand +/// Appearance writes it as an ordinary path that draws the same, with the opacity and blending +/// mode applied once, in one undo step. +#[test] +fn a_painted_piece_s_look_is_exported_and_expanded() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let piece = json!({"path": square_at(40.0), "fills": [solid("#00ff00")], "opacity": 0.5, "blend": "Multiply", + "effects": [{"id": "path.offsetPath", "params": {"offset": 5}}]}); + let manifest = + r#"{"id":"test.engine.looks","name":"Looks","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{}}"#; + install_wat(&mut s, &tpl::returning(manifest, &json!({ "objects": [piece] }).to_string())); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.looks"})); + assert_eq!(run(&mut s, "plugin.info", json!({"id": "test.engine.looks"}))["lastError"], Value::Null); + let near = |got: [u8; 4], want: [u8; 3]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8); + let img = drawn(&s); + let (inside, grown, outside) = (img.pixel(50, 50), img.pixel(37, 50), img.pixel(32, 50)); + assert!(near(inside, [128, 255, 128]) && near(grown, [128, 255, 128]), "half green, grown by the offset: {inside:?} {grown:?}"); + assert_eq!((outside, img.pixel(15, 15)), (WHITE, WHITE)); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(svg.contains("#00ff00") && svg.contains("multiply") && svg.contains("0.5"), "{svg}"); + let pdf = s.execute("document.export", &json!({"format": "pdf"})).unwrap(); + let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); + assert!(pdf.windows(9).any(|w| w == b"/Multiply"), "the PDF sets the blending mode"); + let back = vectorcraft_pdf::import(&pdf).unwrap(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let read = vectorcraft_render::Renderer::new().render(&back, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts); + let (got_inside, got_grown) = (read.pixel(50, 50), read.pixel(37, 50)); + assert!( + near(got_inside, [128, 255, 128]) && near(got_grown, [128, 255, 128]), + "the PDF's piece is half green and grown: {got_inside:?} {got_grown:?}" + ); + assert_eq!(read.pixel(32, 50), WHITE); + assert_eq!(s.doc().unwrap().doc, before, "export doesn't change the document"); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "effect.expandAppearance", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let (mut opacity, mut multiplies) = (1.0_f32, 0); + s.doc().unwrap().doc.walk(|n| { + assert!(n.appearance.effects.iter().all(|e| !e.id.starts_with("plugin.")), "no plug-in effect left"); + opacity *= n.opacity; + multiplies += usize::from(n.blend == vectorcraft_color::BlendMode::Multiply); + }); + assert_eq!((opacity, multiplies), (0.5, 1), "the look applies once"); + let img = drawn(&s); + assert_eq!((img.pixel(50, 50), img.pixel(37, 50), img.pixel(32, 50)), (inside, grown, outside), "expanded, it draws the same"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(node(&s, id).appearance.effects[0].id, "plugin.test.engine.looks"); +} + /// On a fill, a painted effect returns only fills: they replace that fill on each piece. A result /// that breaks a rule (strokes from an effect on a fill, a swatch the document doesn't have) is /// refused whole: the object is drawn as if the effect weren't there, and `plugin.info` names the @@ -2350,6 +2404,271 @@ fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::P (folder, path) } +/// The rows of `plugin.list`'s `failed` as (file, from). +fn failed_rows(s: &mut Session) -> Vec<(String, String)> { + let list = run(s, "plugin.list", json!({})); + list["failed"].as_array().unwrap().iter().map(|r| (r["file"].as_str().unwrap().to_string(), r["from"].as_str().unwrap().to_string())).collect() +} + +/// A stored module whose load panics is listed as failed while the store's other plug-in installs, +/// and `plugin.retry` installs it once its load no longer panics. +#[test] +fn a_stored_plugin_whose_load_panicked_is_listed_and_loads_on_retry() { + let (folder, broken) = store_with("plugin-store-retry", "test.engine.retrypanics"); + let good = folder.0.join("test.engine.retryloads.wasm"); + std::fs::write(&good, wat::parse_str(tpl::returning(&tpl::manifest("test.engine.retryloads", "filter", "{}"), r#"{"objects":[]}"#)).unwrap()) + .unwrap(); + let file = broken.display().to_string(); + let mut s = session(); + { + let _lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + let target = broken.clone(); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| { + if p == target { + panic!("a load that panics"); + } + })); + s.attach_plugin_store(folder.0.clone()); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + assert!(vectorcraft_plugins::registry::get("test.engine.retryloads").is_some(), "the other stored plug-in installs"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_none()); + let list = run(&mut s, "plugin.list", json!({})); + let row = list["failed"].as_array().unwrap().iter().find(|r| r["file"] == json!(file)).cloned(); + assert!(row.as_ref().is_some_and(|r| r["from"] == "store" && r["error"].as_str().unwrap().contains("panicked")), "{list}"); + + // Under read roots that leave the store out, the client names it by its file name and its file + // isn't read again. + let elsewhere = crate::tests_links::Folder::new("plugin-store-retry-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let name = "test.engine.retrypanics.wasm"; + let r = crate::file_access::confine(roots.as_ref(), || s.execute("plugin.retry", &json!({"file": name}))).unwrap(); + assert_eq!((&r["retried"][0]["file"], &r["retried"][0]["loaded"]), (&json!(name), &json!(false)), "{r}"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_none(), "not loaded outside the roots"); + + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"], json!([{"file": file, "loaded": true, "id": "test.engine.retrypanics"}]), "{r}"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_some(), "installed on retry"); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == file), "no longer listed as failed"); + assert!(s.execute("plugin.retry", &json!({"file": file})).is_err(), "a file that didn't fail is refused"); + run(&mut s, "plugin.remove", json!({"id": "test.engine.retrypanics"})); + run(&mut s, "plugin.remove", json!({"id": "test.engine.retryloads"})); +} + +/// A folder file that didn't load stays listed as failed until a retry loads it, which also moves +/// it to the folder report's loaded ids; `plugin.reload` replaces the folder's failed files with its +/// own and leaves the plug-in store's alone. +#[test] +fn a_folder_plugin_loads_on_retry_and_reload_replaces_only_the_folder_s_failures() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // The file the store keeps the module of plug-in `test.engine.retrystored` in, which isn't a module. + let store = crate::tests_links::Folder::new("plugin-store-retry-reload"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem("test.engine.retrystored"))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let dir = crate::tests_links::Folder::new("plugin-folder-retry"); + let id = "test.engine.retryfolder"; + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + let broken = dir.0.join("later.wasm"); + std::fs::write(&broken, b"\0asm?").unwrap(); + let (file, stored_file) = (broken.display().to_string(), stored.display().to_string()); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + let path = dir.0.display().to_string(); + run(&mut s, "plugin.reload", json!({"path": path})); + let both = failed_rows(&mut s); + assert!(both.contains(&(stored_file.clone(), "store".into())) && both.contains(&(file.clone(), "folder".into())), "{both:?}"); + + // Under read roots that leave the folder out, it isn't read and stays listed. + let elsewhere = crate::tests_links::Folder::new("plugin-folder-retry-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || s.execute("plugin.retry", &json!({"file": "later.wasm"}))).unwrap(); + assert_eq!(r["retried"][0]["loaded"], json!(false), "{r}"); + let why = r["retried"][0]["error"].as_str().unwrap(); + assert!(!why.is_empty() && !why.contains(path.as_str()), "the folder outside the roots isn't named: {r}"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "folder".into())), "still listed after a retry that couldn't read it"); + + // Still broken: it is listed with the new error. + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!((r["retried"][0]["loaded"].clone(), r["retried"].as_array().unwrap().len()), (json!(false), 1), "{r}"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "folder".into()))); + + std::fs::write(&broken, &module).unwrap(); + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"], json!([{"file": file, "loaded": true, "id": id}]), "{r}"); + let list = run(&mut s, "plugin.list", json!({})); + assert_eq!(list["folder"]["loaded"], json!([id]), "{list}"); + assert!(list["folder"]["failed"].as_array().unwrap().is_empty(), "{list}"); + assert_eq!(failed_rows(&mut s), vec![(stored_file.clone(), "store".into())]); + + // A reload that finds it broken again lists it again, and the stored file stays listed. + run(&mut s, "plugin.remove", json!({"id": id})); + std::fs::write(&broken, b"\0asm?").unwrap(); + run(&mut s, "plugin.reload", json!({"path": path})); + let again = failed_rows(&mut s); + assert!(again.contains(&(stored_file.clone(), "store".into())) && again.contains(&(file, "folder".into())), "{again:?}"); + + // Removing the stored module that didn't load takes it off the list. + run(&mut s, "plugin.remove", json!({"id": "test.engine.retrystored"})); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == stored_file), "a removed file is no longer listed"); +} + +/// A stored file that also fails in a `plugin.reload` of the store's own folder is listed once, and a +/// retry by its name installs it and takes it out of the folder report's failed files too. +#[test] +fn a_reload_of_the_store_folder_lists_a_failed_stored_file_once() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryboth"; + let store = crate::tests_links::Folder::new("plugin-store-retry-both"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + let rows = failed_rows(&mut s); + assert_eq!(rows.iter().filter(|(f, _)| std::path::Path::new(f) == stored).count(), 1, "{rows:?}"); + + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"][0]["loaded"], json!(true), "{r}"); + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + assert!(list["folder"]["failed"].as_array().unwrap().is_empty(), "{list}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Removing or replacing a stored module also clears a failure recorded by a reload of the store +/// folder, without clearing another file's failure. +#[test] +fn removing_or_replacing_a_stored_plugin_clears_its_folder_failure() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryreplaced"; + let store = crate::tests_links::Folder::new("plugin-store-retry-replaced"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + let other = store.0.join("other.wasm"); + std::fs::write(&other, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + for replace in [false, true] { + std::fs::write(&stored, b"\0asm?").unwrap(); + s.load_stored_plugins(); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + if replace { + install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + } else { + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!stored.exists(), "the broken module was removed"); + } + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["failed"].as_array().unwrap().iter().any(|row| row["file"] == file), "{list}"); + let rows = list["folder"]["failed"].as_array().unwrap(); + assert!(!rows.iter().any(|row| row["file"] == file), "{list}"); + assert!(rows.iter().any(|row| row["file"] == other.display().to_string()), "the other failure stays: {list}"); + let retry = run(&mut s, "plugin.retry", json!({})); + assert!(!retry["retried"].as_array().unwrap().iter().any(|row| row["file"] == file), "{retry}"); + } + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// An older installed module doesn't make a retry succeed when the failed stored file is gone. +#[test] +fn retrying_a_missing_stored_plugin_does_not_count_its_old_installation() { + let id = "test.engine.retrymissing"; + let (store, stored) = store_with("plugin-store-retry-missing", id); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + let installed = vectorcraft_plugins::registry::get(id).unwrap(); + assert_eq!(installed.source(), Some(file.as_str())); + std::fs::write(&stored, b"\0asm?").unwrap(); + s.load_stored_plugins(); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + std::fs::remove_file(&stored).unwrap(); + // A retry still waits for its own load when startup loads run in the background. + s.load_plugins_in_background(true); + let retry = run(&mut s, "plugin.retry", json!({"file": file})); + let row = &retry["retried"][0]; + assert_eq!(row["loaded"], json!(false), "{retry}"); + assert!(row.get("id").is_none() && row["error"].as_str().is_some_and(|e| !e.is_empty()), "{retry}"); + assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().serial(), installed.serial(), "the old installation stays"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into())), "still listed, so a later retry can load it"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A stored file that also failed in a `plugin.reload` of the store's folder is taken out of the +/// folder report once a store load installs it, here another session attaching the store. +#[test] +fn a_store_load_that_installs_a_failed_file_clears_its_folder_row() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retrystoreload"; + let store = crate::tests_links::Folder::new("plugin-store-retry-storeload"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let mut other = session(); + other.attach_plugin_store(store.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the other session's store load installed it"); + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["folder"]["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + assert!(!list["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A stored file that failed and is then repaired is no longer listed once a `plugin.reload` of the +/// store's own folder installs it. +#[test] +fn a_reload_that_installs_a_failed_stored_file_takes_it_off_the_list() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryreloaded"; + let store = crate::tests_links::Folder::new("plugin-store-retry-reloaded"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the reload installed it"); + let rows = failed_rows(&mut s); + assert!(!rows.iter().any(|(f, _)| std::path::Path::new(f) == stored), "{rows:?}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A file turned off after it failed to load is no longer listed as failed, also when it is turned +/// off by the name `failed` gives a file outside the read roots; turned on again, it is listed. +#[test] +fn a_failed_file_turned_off_is_no_longer_listed() { + // Another test's store load replaces the process's list of disabled plug-ins. + if !in_own_process("a_failed_file_turned_off_is_no_longer_listed") { + return; + } + let store = crate::tests_links::Folder::new("plugin-store-retry-off"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem("test.engine.retryoff"))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + + let elsewhere = crate::tests_links::Folder::new("plugin-store-retry-off-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let name = stored.file_name().unwrap().to_string_lossy().to_string(); + crate::file_access::confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": name, "enabled": false}))).unwrap(); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == file), "a file turned off isn't listed"); + assert!(run(&mut s, "plugin.retry", json!({}))["retried"].as_array().unwrap().is_empty()); + + run(&mut s, "plugin.setEnabled", json!({"file": file, "enabled": true})); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into())), "listed again once on"); +} + /// With loads in the background, attaching a plug-in store returns while a stored module is /// still loading: the plug-in installs once its load is done, at the next plug-in command. #[test] diff --git a/crates/engine/src/tests/prefs_roots.rs b/crates/engine/src/tests/prefs_roots.rs index b9818949f1..379ce9dca0 100644 --- a/crates/engine/src/tests/prefs_roots.rs +++ b/crates/engine/src/tests/prefs_roots.rs @@ -55,6 +55,8 @@ fn holds(v: &Value, path: &str) -> bool { #[test] fn prefs_commands_leave_out_folders_outside_the_read_root() { + // `prefs.set` and `prefs.reset` load the Additional Plug-ins Folder this session names. + let _folder = super::plugins::PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let base = folder("get"); let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out"))); let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5a0c2a94cf..e5b5208589 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1265,6 +1265,28 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +#[test] +fn wrappers_go_stale_after_revert() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert"); + let path = folder.join("saved's art.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = "var d = app.activeDocument, i = d.pageItems[0], l = i.parent; i.name = 'changed'; vc.run('file.revert');"; + let out = log(&mut s, &format!("{held} vc.log(d.pageItems.length); vc.log(d.pageItems[0] === i); vc.log(d.pageItems[0].parent === l);")); + assert_eq!(out, vec![json!(2), json!(false), json!(false)]); + for operation in [ + "i.name", + "i.name = 'wrong'", + "l.name", + "i.move(d.pageItems[1], ElementPlacement.PLACEBEFORE)", + "d.pageItems[1].duplicate(i, ElementPlacement.PLACEBEFORE)", + "d.pageItems[1].move(l, ElementPlacement.PLACEATEND)", + ] { + let source = format!("{held} try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);"); + assert_eq!(log(&mut s, &source), vec![json!("Stale page item"), json!(2)], "{operation}"); + } +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs new file mode 100644 index 0000000000..8f032a2bb8 --- /dev/null +++ b/crates/engine/src/tests/script_variables.rs @@ -0,0 +1,452 @@ +//! Variables and data sets in the script object model: `Document.variables` and `dataSets`, the +//! variables page items are bound to, Lock Variables, and `importVariables` and `exportVariables`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::tests_links::{Folder, RED, place, png, write}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A document with a rectangle and, above it, a type object, so `pageItems[0]` is the type and `pageItems[1]` the rectangle. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + (s, t, r) +} + +fn variables(s: &Session) -> Vec<(String, &'static str)> { + s.active().unwrap().doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind.label())).collect() +} + +#[test] +fn variables_collection_adds_finds_renames_and_removes() { + let (mut s, _, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var v = app.activeDocument.variables; + vc.log(v.length); vc.log(v.typename); vc.log(v.parent.typename); + var a = v.add(), b = v.add(); + vc.log([a.name, b.name, a.kind, v.length].join()); + b.name = 'title'; b.kind = VariableKind.VISIBILITY; + vc.log([b.name, b.kind, v.getByName('title').name, v.index(0).name, v[1].name].join()); + vc.log(v[2] === undefined && v[-1] === undefined && v[0.5] === undefined); + a.remove(); vc.log(v.length); vc.log(b.parent.typename + ',' + b.typename);"#, + ); + assert_eq!( + out, + vec![ + json!(0), + json!("Variables"), + json!("Document"), + json!("Variable1,Variable2,VariableKind.TEXTUAL,2"), + json!("title,VariableKind.VISIBILITY,title,Variable1,title"), + json!(true), + json!(1), + json!("Document,Variable") + ] + ); + assert_eq!(variables(&s), vec![("title".to_string(), "visibility")]); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + assert!(failure(&mut s, "app.activeDocument.variables.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(4);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(true);").contains("name or an index")); +} + +#[test] +fn variable_names_and_kinds_are_checked_before_anything_changes() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "a", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "b", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 'a';").contains("already exists")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = ' ';").contains("newName")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 5;").contains("must be a string")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = 'text';").contains("VariableKind")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = VariableKind.Unknown;").contains("Unknown")); + let long = "x".repeat(5000); + assert!(failure(&mut s, &format!("app.activeDocument.variables[0].name = '{long}';")).contains("too long")); + // Setting what the variable already has runs no command. + log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'a'; v.name = ' a '; v.kind = VariableKind.TEXTUAL;"); + assert_eq!(undo_steps(&s), before); + assert_eq!(variables(&s), vec![("a".to_string(), "text"), ("b".to_string(), "text")]); +} + +#[test] +fn a_variable_object_goes_stale_and_stays_stale_when_the_name_comes_back() { + let (mut s, _, _) = doc(); + let e = failure( + &mut s, + "var v = app.activeDocument.variables.add();\ + vc.run('variable.delete', {names: ['Variable1']}); vc.run('variable.define', {name: 'Variable1', kind: 'text'});\ + v.name;", + ); + assert!(e.contains("Stale variable"), "{e}"); + // A failed run keeps nothing, so the variable is defined outside the script. + s.execute("variable.define", &json!({"name": "Variable1", "kind": "text"})).unwrap(); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; vc.run('variable.rename', {name: 'Variable1', kind: 'image'}); v.kind;"); + assert!(e.contains("Stale variable"), "{e}"); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; v.remove(); vc.run('edit.undo'); v.name;"); + assert!(e.contains("Stale variable"), "{e}"); + // A rename through the object keeps it. + assert_eq!(log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'renamed'; vc.log(v.name);"), vec![json!("renamed")]); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keepvars\nvar held = app.activeDocument.variables[0];").unwrap(); + let e = failure(&mut s, "#targetengine keepvars\nheld.name;"); + assert!(e.contains("Stale variable"), "{e}"); +} + +#[test] +fn collections_from_an_earlier_run_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keepcols\nvar v = app.activeDocument.variables, d = app.activeDocument.dataSets;").unwrap(); + for member in ["v.typename", "v.parent", "v.length", "d.typename", "d.parent", "d.length"] { + let e = failure(&mut s, &format!("#targetengine keepcols\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn content_and_visibility_variables_bind_one_variable_per_slot() { + let (mut s, t, r) = doc(); + for (name, kind) in [("title", "text"), ("other", "text"), ("show", "visibility"), ("hide", "visibility")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, v = d.variables, t = d.pageItems[0], r = d.pageItems[1]; + vc.log(t.contentVariable === null && t.visibilityVariable === null); + t.contentVariable = v.getByName('title'); t.contentVariable = v.getByName('other'); + r.visibilityVariable = v.getByName('show'); r.visibilityVariable = v.getByName('hide'); + vc.log(t.contentVariable.name + ',' + r.visibilityVariable.name); + vc.log(v.getByName('hide').pageItems.length + ',' + v.getByName('hide').pageItems[0].typename); + vc.log(r.contentVariable === undefined);"#, + ); + assert_eq!(out, vec![json!(true), json!("other,hide"), json!("1,PathItem"), json!(true)]); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["other".to_string()])); + assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::>()), Some(vec!["hide".to_string()])); + assert_eq!(undo_steps(&s), before + 1); + // A variable of another kind is refused, and nothing changes; null unbinds that slot only. + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables.getByName('show');"); + assert!(e.contains("visibility variable"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[1].visibilityVariable = d.variables.getByName('title');"); + assert!(e.contains("text variable"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].contentVariable = 'title';").contains("Variable or null")); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["show".to_string()])); + // Assigning the binding the object already has runs no command. + let steps = undo_steps(&s); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn an_embedded_image_cannot_take_an_image_variable() { + let dir = Folder::new("script-vars-embedded"); + let path = dir.file("red.png"); + write(&path, &png(10, 10, RED)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = place(&mut s, &path); + s.execute("variable.define", &json!({"name": "photo", "kind": "image"})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables[0]; vc.log(d.pageItems[0].contentVariable.name);"); + assert_eq!(out, vec![json!("photo")]); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("variable.unbind", &json!({"ids": [id.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); + assert!(e.contains("embedded image"), "{e}"); + assert!(s.active().unwrap().doc.variables.bindings.is_empty()); + // Its visibility still takes a visibility variable. + s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);", + ); + assert_eq!(out, vec![json!("shown")]); +} + +#[test] +fn data_sets_capture_display_update_and_remove() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, sets = d.dataSets; + vc.log(sets.length + ',' + (d.activeDataset === null)); + var one = sets.add(); + vc.run('text.setText', {id: TEXT_ID, text: 'World'}); + var two = sets.add(); + vc.log([one.name, two.name, sets.length, d.activeDataset.name].join()); + one.display(); vc.log(d.activeDataset.name); + vc.run('text.setText', {id: TEXT_ID, text: 'Again'}); + two.update(); vc.log(d.activeDataset.name); + two.name = 'Second'; vc.log(sets.getByName('Second').name + ',' + sets.index(1).name); + d.activeDataset = two; vc.log(d.activeDataset.name); + one.remove(); vc.log(sets.length);"# + .replace("TEXT_ID", &t.0.to_string()) + .as_str(), + ); + assert_eq!( + out, + vec![ + json!("0,true"), + json!("Data Set 1,Data Set 2,2,Data Set 2"), + json!("Data Set 1"), + json!("Data Set 1"), + json!("Second,Second"), + json!("Second"), + json!(1) + ] + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.datasets.len(), 1); + assert_eq!(vars.datasets[0].values.get("title"), Some(&vectorcraft_doc::DataValue::Text("Again".into()))); + assert_eq!(vars.active_dataset.as_deref(), Some("Second")); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; x.remove(); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); + log(&mut s, "app.activeDocument.dataSets.removeAll(); app.activeDocument.dataSets.removeAll();"); + assert!(s.active().unwrap().doc.variables.datasets.is_empty()); + assert!(failure(&mut s, "app.activeDocument.activeDataset = 'Data Set 1';").contains("must be a Dataset")); +} + +#[test] +fn update_of_a_data_set_that_holds_the_art_runs_no_command() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = run(&mut s, "var x = app.activeDocument.dataSets[0]; x.update(); x.display(); app.activeDocument.activeDataset = x;").unwrap(); + assert_eq!(undo_steps(&s), before); + assert_eq!(r["slowestCommands"], json!([]), "{r}"); +} + +#[test] +fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap(); + let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);"); + assert_eq!(out.len(), 1, "{out:?}"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn variables_locked_refuses_new_variables_but_not_bindings() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "show", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.variablesLocked); d.variablesLocked = true; d.variablesLocked = true;\ + d.pageItems[1].visibilityVariable = d.variables[0]; vc.log(d.variablesLocked);", + ); + assert_eq!(out, vec![json!(false), json!(true)]); + assert!(s.active().unwrap().doc.variables.locked); + let e = failure(&mut s, "app.activeDocument.variables.add();"); + assert!(e.contains("locked"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.variablesLocked = 1;").contains("true or false")); + assert_eq!(variables(&s).len(), 1); +} + +/// A variable library of two variables and two data sets, written for these tests from the elements +/// and attributes `variable.loadLibrary` reads: `variableSets`, `variableSet`, `variables` of +/// `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements +/// with `dataSetName`. +const LIBRARY: &str = r#" + + + + + + + + <p>Hello</p>true + <p>World</p>false + + + +"#; + +/// A fresh folder with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-vars-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// Runs `main/main.jsx` in `base` with `text`, on `s`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +#[test] +fn import_variables_replaces_the_variables_and_keeps_compatible_bindings() { + let base = folder("import"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "gone", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let r = run_file( + &mut s, + &base, + "var d = app.activeDocument; d.importVariables(new File('lib.xml'));\ + vc.log(d.variables.length + ',' + d.dataSets.length + ',' + d.dataSets[1].name);\ + d.dataSets.getByName('Two').display(); vc.log(d.pageItems[0].contentVariable.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!(["2,2,Two", "title"])); + assert_eq!(variables(&s), vec![("title".to_string(), "text"), ("badge".to_string(), "visibility")]); + assert_eq!(s.active().unwrap().doc.story_text(t), "World"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn import_variables_takes_only_a_file_the_script_may_read() { + let base = folder("import-refused"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + std::fs::write(base.join("outside.xml"), LIBRARY).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let fail = |s: &mut Session, text: &str| run_file(s, &base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string(); + assert!(fail(&mut s, "app.activeDocument.importVariables('lib.xml');").contains("needs a File")); + assert!(fail(&mut s, "app.activeDocument.importVariables(new Folder('.'));").contains("needs a File")); + let outside = base.join("outside.xml").to_string_lossy().replace('\\', "/"); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{outside}'));")); + assert!(e.contains("access denied"), "{e}"); + // The open document's own file is refused, though the script's commands may open it. + let saved = base.join("doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{}'));", saved.replace('\\', "/"))); + assert!(e.contains("access denied"), "{e}"); + // A plain object cannot pass for a File. + let e = fail(&mut s, "var o = {}; o['\\u0000fileRef'] = new File('lib.xml').fsName; app.activeDocument.importVariables(o);"); + assert!(e.contains("not plain data"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn import_variables_refuses_hostile_libraries_before_any_edit() { + let base = folder("import-hostile"); + let external = r#"]>"#; + std::fs::write(base.join("main/external.xml"), external).unwrap(); + let deep = format!("{}{}", "".repeat(300), "".repeat(300)); + std::fs::write(base.join("main/deep.xml"), deep).unwrap(); + let mut big = LIBRARY.as_bytes().to_vec(); + big.resize((8 << 20) + 1, b' '); + std::fs::write(base.join("main/big.xml"), big).unwrap(); + let twice = LIBRARY.replace("varName=\"badge\"", "varName=\"title\""); + std::fs::write(base.join("main/twice.xml"), twice).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + for (file, says) in [("external.xml", "document type declaration"), ("deep.xml", "deep"), ("big.xml", "larger than"), ("twice.xml", "twice")] { + let e = run_file(&mut s, &base, &format!("app.activeDocument.importVariables(new File('{file}'));")).unwrap_err().to_string(); + assert!(e.contains(says), "{file}: {e}"); + } + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); + assert_eq!(undo_steps(&s), before); + // Locked variables refuse a library that would delete or define one. + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let e = run_file(&mut s, &base, "app.activeDocument.importVariables(new File('lib.xml'));").unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn export_variables_writes_a_library_that_import_reads_back() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, f = new File(Folder.temp + '/out.xml');\ + d.exportVariables(f); f.open('r'); var x = f.read(); f.close(); vc.log(x);\ + d.variables.removeAll(); d.importVariables(f); vc.log(d.variables[0].name + ',' + d.dataSets[0].name);", + ); + let xml = out[0].as_str().unwrap(); + for part in ["varName=\"title\"", "trait=\"textcontent\"", "dataSetName=\"Row\"", "

Hello

"] { + assert!(xml.contains(part), "{part} in {xml}"); + } + assert_eq!(out[1], json!("title,Row")); +} + +#[test] +fn export_variables_writes_only_where_the_script_may_write() { + let base = folder("export-refused"); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + // The open document's own file is refused, though the script's commands may save it. + let saved = base.join("main/doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let before = std::fs::read(&saved).unwrap(); + let path = saved.replace('\\', "/"); + let e = run_file(&mut s, &base, &format!("app.activeDocument.exportVariables(new File('{path}'));")).unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert_eq!(std::fs::read(&saved).unwrap(), before); + // The script's own folder is only read. + let e = run_file(&mut s, &base, "app.activeDocument.exportVariables(new File('out.xml'));").unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert!(!base.join("main/out.xml").exists()); + assert!(run_file(&mut s, &base, "app.activeDocument.exportVariables('out.xml');").unwrap_err().to_string().contains("needs a File")); + // A library that cannot be written leaves no file. + s.execute("variable.rename", &json!({"name": "title", "newName": "has space"})).unwrap(); + let e = failure(&mut s, "app.activeDocument.exportVariables(new File(Folder.temp + '/bad.xml'));"); + assert!(e.contains("can't be saved"), "{e}"); + let out = + log(&mut s, "var f = new File(Folder.temp + '/bad.xml'); try { app.activeDocument.exportVariables(f); } catch (e) {} vc.log(f.exists);"); + assert_eq!(out, vec![json!(false)]); +} diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 41ed696c08..a02e5aad53 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -292,6 +292,24 @@ fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() { assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]); } +/// Pasted again, art whose filter was renamed takes the name the first paste gave it, so the +/// same filter does not come in under a new name each time. +#[test] +fn pasting_a_renamed_filter_again_reuses_its_name() { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 2); + assert_eq!(pasted[0], pasted[1], "{pasted:?}"); + assert_ne!(pasted[0].0, "Shift", "{pasted:?}"); +} + /// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own /// definition under a free name no longer than its own (a free letter for a one-letter name), and /// its id is that name. diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 2d29d98a23..20144d4411 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -262,6 +262,22 @@ fn document_color_mode_converts_effect_colors() { assert_eq!((object(&s), style(&s)), before); } +/// Document Color Mode converts the fill of a character style, so type set in the style after the +/// switch paints in the new mode. +#[test] +fn document_color_mode_converts_character_style_colors() { + let mut s = session(); + let id = run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "Ink", "color": "#ff0000"}))["id"].clone(); + run(&mut s, "charStyle.new", json!({"name": "Red", "id": id})); + let fill = |s: &Session| { + let def = doc(s).char_styles.iter().find(|c| c.name == "Red").expect("the style"); + serde_json::from_value::(def.attrs["fill"].clone()).expect("a fill") + }; + assert!(matches!(fill(&s).color(), Some(Color::Rgb { .. })), "{:?}", fill(&s)); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + assert!(matches!(fill(&s).color(), Some(Color::Cmyk { .. })), "{:?}", fill(&s)); +} + /// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a /// graph drawn again after the switch paints its series, labels and lines in the new mode. #[test] diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 980682f57e..891e7a6ba0 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -995,25 +995,32 @@ fn doc_styles_are_worked_out_once_however_many_paragraphs_use_them() { styles.push(Some((stk, if i == first { 0x0FFF } else { i - 1 }, vec![], chpx))); } } - // 20,000 hidden paragraphs in the last paragraph style with the last character style, then one - // shown. - let text: &'static str = format!("{}x\r", "\r".repeat(20_000)).leak(); - let doc = Word97 { - pieces: vec![(text, true)], - chpx: vec![(0, 20_000, prls(&[(0x4A30, &[63, 0]), (0x083C, &[1])])), (20_000, 20_002, prls(&[(0x4A30, &[63, 0])]))], - papx: vec![(20_001, 31, vec![])], - styles, - ..Word97::default() - } - .build(); + // `hidden` hidden paragraphs in the last paragraph style with the last character style, then + // one shown; the Prls read placing it. let mut s = session(); - let started = std::time::Instant::now(); - let r = s.execute("file.place", &json!({"name": "a.doc", "dataBase64": vectorcraft_format::base64_encode(&doc)})).unwrap(); - let took = started.elapsed(); - let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); - let NodeKind::Text(t) = &n.kind else { panic!("not type") }; - assert_eq!((t.runs.len(), t.runs[0].text.as_str(), t.runs[0].style.font_style.as_str(), t.runs[0].style.size), (1, "x", "Italic", 12.0)); - assert!(took < std::time::Duration::from_secs(10), "placing took {took:?}"); + let mut place_hidden = |hidden: u32| { + let text: &'static str = format!("{}x\r", "\r".repeat(hidden as usize)).leak(); + let doc = Word97 { + pieces: vec![(text, true)], + chpx: vec![(0, hidden, prls(&[(0x4A30, &[63, 0]), (0x083C, &[1])])), (hidden, hidden + 2, prls(&[(0x4A30, &[63, 0])]))], + papx: vec![(hidden + 1, 31, vec![])], + styles: styles.clone(), + ..Word97::default() + } + .build(); + crate::cmd::place::PRLS_READ.set(0); + let r = s.execute("file.place", &json!({"name": "a.doc", "dataBase64": vectorcraft_format::base64_encode(&doc)})).unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + assert_eq!((t.runs.len(), t.runs[0].text.as_str(), t.runs[0].style.font_style.as_str(), t.runs[0].style.size), (1, "x", "Italic", 12.0)); + crate::cmd::place::PRLS_READ.get() + }; + let one = place_hidden(1); + let many = place_hidden(20_000); + // The styles' own Prls: 21,000 in each of the 64, and the two first ones' sizes. + let sheet = 64 * 21_000 + 2; + assert!(one >= sheet && one < 2 * sheet, "each style's properties are read once: {one} Prls read, {sheet} in the styles"); + assert!(many <= one + 20_000, "20,000 more paragraphs read {} more Prls", many - one); // A chain of 34 paragraph styles, each based on the next; the last is 12 pt. Styles 31 and 0 // both take its size. let mut styles: Vec<_> = (0..33u16).map(|i| Some((1, i + 1, vec![], vec![]))).collect(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f417bcaf03..bc9e2aa0c6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1918,7 +1918,12 @@ impl Session { // The place cursor's file, placed by the frontend that asked for it. Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)), // The place cursor's file, read within the roots of whoever loaded the cursor. - Action::Exec(cmd, p) if cmd == "file.place" => { + Action::Exec(cmd, mut p) if cmd == "file.place" => { + if let Some(params) = p.as_object_mut() { + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + params.remove(key); + } + } let roots = self.place_queue_roots.clone(); if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) { ui.push(UiRequest::Status(w.to_string())); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index b655ed0eb5..906f26771a 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -966,7 +966,9 @@ fn pdf_of(objs: &[Vec]) -> Vec { /// A file filling thousands of paths with function-based shadings, each a long PostScript /// calculator function of fine stripes, opens in bounded time: each shading is read once, and all -/// of them within one budget of function evaluations per import (#3621 review). +/// of them within one budget of function evaluations per import (#3621 review). One shading +/// filling 5,000 paths takes no more evaluations than filling one, and twenty no more than the +/// budget. #[test] fn pdf_many_paths_filled_with_long_function_shadings_open_in_bounded_time() { let shadings = 20; @@ -981,13 +983,21 @@ fn pdf_many_paths_filled_with_long_function_shadings_open_in_bounded_time() { .into_bytes() }) .collect(); - let content: String = (0..5000).map(|i| format!("/Pattern cs /P{} scn {} {} 2 2 re f\n", i % shadings, i % 100 * 2, i / 100 * 2)).collect(); - let pdf = handmade_pdf_with(&content, &format!("<< /Pattern << {patterns}>> >>"), "[0 0 200 100]", &functions); - let start = std::time::Instant::now(); - let d = vectorcraft_pdf::import(&pdf).unwrap(); - let took = start.elapsed(); - assert!(!d.layers.is_empty()); - assert!(took < std::time::Duration::from_secs(30), "took {took:?}"); + // The evaluations an import of a file filling `paths` paths with the first `used` shadings takes. + let evaluations = |used: usize, paths: usize| { + let content: String = (0..paths).map(|i| format!("/Pattern cs /P{} scn {} {} 2 2 re f\n", i % used, i % 100 * 2, i / 100 * 2)).collect(); + let pdf = handmade_pdf_with(&content, &format!("<< /Pattern << {patterns}>> >>"), "[0 0 200 100]", &functions); + let before = vectorcraft_pdf::function_evaluations_of(&pdf); + let d = vectorcraft_pdf::import(&pdf).unwrap(); + assert!(!d.layers.is_empty()); + vectorcraft_pdf::function_evaluations_of(&pdf) - before + }; + let limit = vectorcraft_pdf::function_evaluation_limit(); + let (one, one_many) = (evaluations(1, 1), evaluations(1, 5000)); + assert!(one > 0 && one < limit, "one path: {one} evaluations, the budget {limit}"); + assert!(one_many <= one, "one shading: 5,000 paths took {one_many} evaluations, one path {one}"); + let all = evaluations(shadings, 5000); + assert!(all <= limit, "{shadings} shadings: {all} evaluations, the budget {limit}"); } /// One content-stream operation with junk operands. @@ -7716,7 +7726,8 @@ fn pdf_streams_the_reader_would_fail_on_are_refused() { /// A page drawing a thousand times one form that decodes to 64 MiB (of spaces, then a square): /// each drawing reads the form again, so the import stops at the page's form content instead of -/// decoding 64 GB (#3569, which hung). +/// decoding 64 GB (#3569, which hung). The scan walks no more than the page's limit and the form +/// that passes it. #[test] fn pdf_a_huge_form_drawn_over_and_over_is_refused_in_bounded_time() { use std::io::Write as _; @@ -7724,14 +7735,17 @@ fn pdf_a_huge_form_drawn_over_and_over_is_refused_in_bounded_time() { for _ in 0..64 { e.write_all(&[b' '; 1 << 20]).unwrap(); } - e.write_all(b"0 0 5 5 re f").unwrap(); + let square = b"0 0 5 5 re f"; + e.write_all(square).unwrap(); let form = packed_as_is(FORM, &e.finish().unwrap()); let bytes = pdf_with(&"/F Do ".repeat(1000), "<< /XObject << /F 5 0 R >> >>", &[form]); - let start = std::time::Instant::now(); + let before = vectorcraft_pdf::form_content_of(&bytes); let e = vectorcraft_engine::cmd::fileio::load("repeated.pdf", &bytes).err().map(|e| e.to_string()); - let took = start.elapsed(); + let walked = vectorcraft_pdf::form_content_of(&bytes) - before; + let one_form = (64 << 20) + square.len(); + assert!(walked > 0, "the page's scan reads the form"); + assert!(walked <= vectorcraft_pdf::form_content_limit() + one_form, "{walked} bytes of form content walked"); assert!(e.as_deref().is_some_and(|e| e.contains("no document was imported")), "{e:?}"); - assert!(took < std::time::Duration::from_secs(60), "took {took:?}"); } // A large file the reader would fail on says which stream (#4366): an image with its size in @@ -8357,21 +8371,30 @@ fn ai_private(layer_art: &str) -> Vec { } /// A blend of many steps doesn't stall the import: one within the limits (a thousand steps between -/// two keys) is checked and made live quickly, one past them keeps its drawn steps without being -/// laid out. +/// two keys) is checked and made live with no more measuring per object than a blend of three +/// steps, one past them keeps its drawn steps without being laid out. #[test] fn large_ai_blends_import_in_bounded_time() { - for (steps, live) in [(3, true), (998, true), (1_500, false)] { + // The objects laid out and the laid objects measured against drawn steps, reading `steps`. + let work = |steps: usize, live: bool| { let private = ai_private(&blend_text(steps)); - let started = std::time::Instant::now(); + let before = vectorcraft_eps::blend_work(); let (doc, notes, read) = vectorcraft_eps::layered_ai(&private, Document::new(4000.0, 200.0), vec![], false, true, 1.0); + let after = vectorcraft_eps::blend_work(); assert!(read, "{steps} steps: read from the layers ({notes:?})"); - let took = started.elapsed(); - assert!(took < std::time::Duration::from_secs(30), "{steps} steps took {took:?}"); let mut blends = 0; doc.walk(|n| blends += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Blend { .. }))); assert_eq!(blends == 1, live, "{steps} steps: live {live}"); - } + (after.0 - before.0, after.1 - before.1) + }; + let (small_laid, small_measured) = work(3, true); + let (laid, measured) = work(998, true); + assert!(small_laid > 0 && laid > small_laid, "laid out: {small_laid} for 3 steps, {laid} for 998"); + assert!( + measured * small_laid <= 2 * small_measured * laid, + "998 steps: {measured} measured for {laid} laid out; 3 steps: {small_measured} for {small_laid}" + ); + assert_eq!(work(1_500, false), (0, 0), "a blend past the limits isn't laid out"); } proptest! { diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1bef3c82be..af3c04eb3c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ]; @@ -138,6 +139,23 @@ const INSIDE: &[(&str, &str)] = &[ ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + // Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s + // `visibilityVariable` is in its row above. + ("", "Dataset Datasets Variable VariableKind Variables"), + ("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"), + ("Variables.", "prototype"), + ("Variables.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Variable.", "prototype"), + ("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"), + ("Datasets.", "prototype"), + ("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Dataset.", "prototype"), + ("Dataset.prototype.", "constructor display name name= parent remove typename update"), + ("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="), + ("GraphItem.prototype.", "contentVariable contentVariable="), + ("PlacedItem.prototype.", "contentVariable contentVariable="), + ("RasterItem.prototype.", "contentVariable contentVariable="), + ("TextFrame.prototype.", "contentVariable contentVariable="), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types. diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 911b39de34..1987b8adba 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -481,6 +481,44 @@ fn arb_object() -> impl Strategy, Value)> { }) } +/// The keys a piece or a fill or stroke of an effect that declares `appearanceOutput` may carry: +/// opacity, a blending mode (known, wrongly spelled or junk) and effect records (built-in ones +/// with random parameters, plug-in effects including the effect itself, junk), up to past the cap. +fn arb_look() -> impl Strategy> { + let id = prop_oneof![ + Just(json!("path.offsetPath")), + Just(json!("stylize.dropShadow")), + Just(json!("distort.twist")), + Just(json!("blur.gaussianBlur")), + Just(json!("threeD.extrude")), + Just(json!("plugin.fuzz.looks")), + arb_junk(), + ]; + let params = prop_oneof![Just(Value::Null), arb_num().prop_map(|n| json!({"offset": n, "angle": n, "radius": n, "opacity": n})), arb_junk()]; + let record = (id, params, prop::option::of(prop_oneof![any::().prop_map(Value::from), arb_junk()])).prop_map(|(id, params, visible)| { + let mut r = Map::new(); + r.insert("id".into(), id); + if !params.is_null() { + r.insert("params".into(), params); + } + if let Some(v) = visible { + r.insert("visible".into(), v); + } + Value::Object(r) + }); + let blend = prop_oneof![Just(json!("Multiply")), Just(json!("Screen")), Just(json!("multiply")), arb_junk()]; + let effects = prop_oneof![prop::collection::vec(record, 0..20).prop_map(Value::from), arb_junk()]; + (prop::option::of(arb_num()), prop::option::of(blend), prop::option::of(effects)).prop_map(|(opacity, blend, effects)| { + let mut m = Map::new(); + for (k, v) in [("opacity", opacity), ("blend", blend), ("effects", effects)] { + if let Some(v) = v { + m.insert(k.into(), v); + } + } + m + }) +} + /// The output document: objects (ids resolved against `inputs`; out-of-range indices become /// unknown ids), or junk. fn output(objects: &[(Option, Value)], inputs: &[u64], junk: Option) -> String { @@ -559,6 +597,50 @@ proptest! { renders(&s, &out)?; } + /// A live effect that declares `appearanceOutput` returning pieces whose own looks, and their + /// first fill's, are hostile, on objects or on a fill: drawing, export and Expand Appearance + /// never crash. + #[test] + fn hostile_piece_looks_never_crash( + objects in prop::collection::vec((arb_object(), arb_look(), prop::option::of(arb_look())), 0..4), + on_fill in any::(), + ) { + let mut s = rich_session(); + s.execute("select.all", &json!({})).unwrap(); + let pieces: Vec<(Option, Value)> = objects + .into_iter() + .map(|((_, mut o), look, fill_look)| { + if let Some(m) = o.as_object_mut() { + m.remove("name"); + m.extend(look); + if let (Some(fl), Some(Value::Array(fills))) = (fill_look, m.get_mut("fills")) + && let Some(first) = fills.first_mut() + { + let mut row = Map::new(); + row.insert("paint".into(), first.take()); + row.extend(fl); + *first = Value::Object(row); + } + } + (None, o) + }) + .collect(); + let out = output(&pieces, &[], None); + let manifest = r#"{"id":"fuzz.looks","name":"Fuzz","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{}}"#; + install(&mut s, &wat::parse_str(tpl::returning(manifest, &out)).unwrap()).unwrap(); + let item = if on_fill { json!(0) } else { Value::Null }; + let r = catch_quiet(|| s.execute("effect.apply", &json!({"effect": "plugin.fuzz.looks", "item": item})).map(|_| ())); + if let Err(msg) = r { + return Err(TestCaseError::fail(format!("panicked on {out}: {msg}"))); + } + renders(&s, &out)?; + let r = catch_quiet(|| s.execute("effect.expandAppearance", &json!({})).map(|_| ())); + if let Err(msg) = r { + return Err(TestCaseError::fail(format!("expanding panicked on {out}: {msg}"))); + } + renders(&s, &out)?; + } + /// An importer's hostile output (`document.open`) either opens a document that renders and /// exports, or is an error that opens nothing. #[test] diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 8a0b71c679..52413b8c28 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -8,6 +8,10 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P [lints] workspace = true +[features] +# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only). +work-count = [] + [dependencies] craft-eps = { workspace = true } craft-ps = { workspace = true } @@ -48,3 +52,6 @@ vectorcraft-testkit = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # Tests: a Group 4 encoder and the T.4 run codes, to write CCITT test images. fax = "0.2" +# The counters vectorcraft-engine's tests turn on, also when this crate is tested without +# vectorcraft-engine (`cargo xtask ci shard`). +vectorcraft-eps = { path = ".", features = ["work-count"] } diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 1a15939c8a..364f3a1646 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -12633,6 +12633,36 @@ fn an_envelope_mapping_from_its_contents_strokes_is_read_back() { assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin); } +/// A stroked straight line, with no height without its stroke, saves the size of its box with its +/// stroke, and opens mapping from that box. +#[test] +fn a_stroked_straight_line_mapping_from_its_stroke_is_read_back() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut envelope = envelope_node( + &mut doc, + EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, + 50.0, + false, + EnvelopeOptions::NEW, + ); + let line = shapes::line(kurbo::Point::new(40.0, 50.0), kurbo::Point::new(160.0, 50.0)); + let line = Node::path(doc.alloc_id(), line, Appearance::basic(Paint::None, solid(Color::BLACK), 10.0)); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + *content = vec![Arc::new(line)]; + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + assert!(plain.height() < 1e-9 && stroked.height() > 9.0, "{plain:?} {stroked:?}"); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let margin = options.bounds_margin; + assert!(margin[0] > 0.0 && margin[1] > 0.0, "{margin:?}"); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin); +} + /// A test's stand-in for a node that must be an envelope. fn unreachable_envelope() -> ! { panic!("not an envelope") diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 16822afbc7..4458f29d2b 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -90,6 +90,8 @@ use interp::{Fault, Interp}; use obj::PsError; pub use ai::NameEncoding; +#[cfg(any(test, feature = "work-count"))] +pub use ai::blend_work; #[cfg(test)] pub(crate) use ai::objects_read; #[cfg(test)] diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index e7a5430e62..149728decf 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -35,6 +35,8 @@ use std::io::Read as _; use super::lex::find; use crate::ps; +#[cfg(any(test, feature = "work-count"))] +pub use blend::blend_work; pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads}; pub(crate) use brush::{ BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over, diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index c1d80a1d63..da2797fa14 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -52,6 +52,20 @@ const COLOR_TOLERANCE: f32 = 0.02; /// The note for a blend that keeps its drawn steps. pub(super) const DRAWN: &str = "a blend VectorCraft couldn't read as a live blend comes in as its drawn steps"; +#[cfg(any(test, feature = "work-count"))] +thread_local! { + /// The work blends took on this thread (tests): the objects laid out to be checked, and the laid + /// objects the check measured against a drawn step. + static BLEND_WORK: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; +} + +/// The objects blends laid out to be checked and made live on this thread, and the laid objects +/// the check measured against a drawn step (tests). +#[cfg(any(test, feature = "work-count"))] +pub fn blend_work() -> (usize, usize) { + BLEND_WORK.get() +} + /// A blend part an object's dictionary names: its type (`K`, `S`) and its id. pub(super) type Roles = HashMap)>; @@ -214,6 +228,8 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol .filter_map(|orientation| { let spec = BlendSpec { orientation, ..spec.clone() }; let laid = blend_expand(&keys, &spec); + #[cfg(any(test, feature = "work-count"))] + BLEND_WORK.with(|w| w.set((w.get().0.saturating_add(laid.len()), w.get().1))); let off = how_far(&laid, &drawn, false)?; Some((off, spec, laid)) }) @@ -505,7 +521,11 @@ fn how_far(laid: &[Node], drawn: &[Drawn], turned: bool) -> Option { .flatten() .filter(|&&i| !used.get(i).copied().unwrap_or(true)) .filter_map(|&i| laid.get(i).map(|l| (i, l))) - .filter(|(_, l)| (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f)); + .filter(|(_, l)| { + #[cfg(any(test, feature = "work-count"))] + BLEND_WORK.with(|w| w.set((w.get().0, w.get().1.saturating_add(1)))); + (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f) + }); let (i, near) = if turned && compare { // Outlines are tried nearest first, so that steps crowded in one place don't spend the // outline comparisons on candidates farther off. diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index e9e588e738..d9a14a0239 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -32,7 +32,7 @@ use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; use vectorcraft_doc::live::{ EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity, envelope_content_boxes, - envelope_content_boxes_with, envelope_stroke_margin, + envelope_content_boxes_with, envelope_margin_lengths, envelope_stroke_margin, }; use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef}; use vectorcraft_geom::PathData; @@ -133,7 +133,7 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { /// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies /// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the /// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for -/// contents with no width or no height. +/// contents with neither a width nor a height. fn saved_margin(o: &Obj, content: &[Arc], scale: f64) -> Option<[f32; 4]> { let saved = |key: &str| match o.nums(key).as_slice() { [v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()), @@ -305,7 +305,7 @@ fn painted_margin(painted: Rect, plain: Rect) -> Option<[f32; 4]> { /// Do bounds margins `a` and `b` give contents with geometric box `plain` the same box, each side /// within [`PAINTED_SLACK`]? fn same_box(a: [f32; 4], b: [f32; 4], plain: Rect) -> bool { - let sizes = [plain.height(), plain.height(), plain.width(), plain.width()]; + let Some(sizes) = envelope_margin_lengths(plain) else { return a == b }; a.iter().zip(b).zip(sizes).all(|((a, b), size)| (f64::from(*a) - f64::from(b)).abs() * size <= PAINTED_SLACK) } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 1e53f2fa57..fcdffd4580 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1658,7 +1658,7 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo } // The object's outline reshaped as it is drawn: its effects from its own bounds. for path in &mut ours { - let bounds = kurbo::Shape::bounding_box(&path.to_bezpath()); + let bounds = path.bounds().unwrap_or_default(); *path = vectorcraft_effects::apply_geometry(&appearance.effects, path, bounds); } let max = MAX_OUTLINE_PAIRS.isqrt(); @@ -2041,6 +2041,29 @@ mod tests { assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); } + /// The outline check reshapes the object as it is drawn, its effects working from its bounds + /// with its lone anchors: a 10 pt line with a lone anchor at (100, 50), scaled 200% about + /// (50, 25), matches a look of that line drawn from (-50, -25), and not one of the line scaled + /// about its own center. + #[test] + fn the_outline_check_reshapes_from_bounds_with_lone_anchors() { + use vectorcraft_geom::{Point, SubPath}; + let scale = + vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"scaleH": 200, "scaleV": 200}), visible: true }; + let path = PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false), + SubPath::polyline(&[Point::new(100.0, 50.0)], false), + ]); + let appearance = Appearance { effects: vec![scale], ..Appearance::basic(Paint::None, Paint::None, 0.0) }; + let object = Node::path(NodeId(1), path, appearance.clone()); + let look = |from: Point, to: Point| { + let drawn = PathData::single(SubPath::polyline(&[from, to], false)); + Node::group(NodeId(2), vec![Arc::new(Node::path(NodeId(3), drawn, Appearance::default()))]) + }; + assert!(draws_look_outline(&object, &appearance, &look(Point::new(-50.0, -25.0), Point::new(-30.0, -25.0)))); + assert!(!draws_look_outline(&object, &appearance, &look(Point::new(-5.0, 0.0), Point::new(15.0, 0.0)))); + } + /// The outline check holds for every point of the outlines, not only the points it checks: a /// 0.25 pt line whose look has only short pieces over its ends, 0.24 pt away, leaves the /// line's middle about 0.27 pt from the look, so the drawn look stays. The line drawn 0.1 pt diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 787c0d268c..242d433b7b 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -9042,7 +9042,7 @@ fn an_envelope_without_distort_appearance_maps_from_the_geometric_box() { /// An envelope maps from the geometric box when its file saves that box's size, saves no size, /// saves a size that isn't a number or saves a size far from both boxes; contents without a stroke -/// have one box, and contents with no height have no margins. +/// have one box. #[test] fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() { use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap}; @@ -9083,13 +9083,52 @@ fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() { let thin = format!("{RED}0 1 1 0 1 0 0 XA\n0.2 w\n{}b\n", rect_path(40.0, 20.0, 160.0, 80.0)); let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &thin, 2, &plain))); assert_eq!(live_envelope(&art(&r.doc)[0]).4.bounds_margin, [0.0; 4]); - // A stroked straight line: 120 × 0 without its stroke, and 120 × 10 as saved. - let keys = format!("{ENVELOPE_KEYS}10 /Real (AIDeformArtHeightKey) ,\n120 /Real (AIDeformArtWidthKey) ,\n"); - let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n40 20 m\n160 20 L\nS\n"); - let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &line, 2, &plain))); - for n in art(&r.doc) { - if let NodeKind::Envelope { options, .. } = &n.kind { - assert_eq!(options.bounds_margin, [0.0; 4]); +} + +/// A stroked straight line, 120 × 0 without its stroke, whose file saves its size with the stroke +/// (120 × 10) maps from that box: the margins across the line are shares of its length. Lines +/// along either axis, in a mesh envelope and in a top object envelope. +#[test] +fn a_stroked_straight_line_saved_with_its_stroke_maps_from_the_stroked_box() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap}; + for vertical in [false, true] { + let (w, h) = if vertical { (10.0, 120.0) } else { (120.0, 10.0) }; + let outer = Rect::from_center_size((100.0, 50.0), (w, h)); + let at = move |(i, j): (usize, usize)| (outer.x0 + i as f64 * w, outer.y0 + j as f64 * h); + let third = move |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + let mesh = mesh_text(1, 1, &at, &third, None); + let flat = EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![ + Point::new(outer.x0, outer.y0), + Point::new(outer.x1, outer.y0), + Point::new(outer.x0, outer.y1), + Point::new(outer.x1, outer.y1), + ], + handles: vec![], + }; + let drawn = drawn_box(&flat, outer, outer); + let keys = format!("{ENVELOPE_KEYS}{h} /Real (AIDeformArtHeightKey) ,\n{w} /Real (AIDeformArtWidthKey) ,\n"); + let line = if vertical { "100 -10 m\n100 110 L\n" } else { "40 50 m\n160 50 L\n" }; + let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n{line}S\n"); + for kind in [2, 3] { + let r = read_ok(&layer(&envelope_of(&mesh, &keys, &line, kind, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{vertical} {kind}: {a:#?}"); + assert!(r.warnings.is_empty(), "{vertical} {kind}: {:?}", r.warnings); + let (.., options) = live_envelope(&a[0]); + let across = 5.0_f32 / 120.0; + let want = if vertical { [0.0, 0.0, across, across] } else { [across, across, 0.0, 0.0] }; + assert!(options.bounds_margin.iter().zip(want).all(|(m, w)| (m - w).abs() < 1e-6), "{vertical} {kind}: {:?}", options.bounds_margin); + let src = EnvelopeMap::of(&a[0]).unwrap().src(); + assert!( + (src.x0 - outer.x0).abs() + (src.y0 - outer.y0).abs() + (src.x1 - outer.x1).abs() + (src.y1 - outer.y1).abs() < 1e-3, + "{vertical} {kind}: {src:?}" + ); } } } diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index ade850a21e..09f7531ff1 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -21,3 +21,5 @@ mod ops; mod pixels; pub(crate) use filters::Stream; +#[cfg(test)] +pub(crate) use ops::measured; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index f5d45449f2..e9bf596eb3 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -8,6 +8,23 @@ use super::{ /// Most bytes one filter or image reads. pub(super) const MAX_DATA: usize = 1 << 28; +/// Decoded bytes the measuring of an image's data left out charges one operation for. A program's +/// budget grows by 64 operations for each byte of it, so the data of one image compressed up to +/// 1024 to 1 is measured within what its own compressed bytes add. +const MEASURED_PER_OP: usize = 16; + +#[cfg(test)] +thread_local! { + /// How many decoded bytes the measuring of images' data left out on this thread decoded. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`MEASURED`] of this thread. +#[cfg(test)] +pub(crate) fn measured() -> u64 { + MEASURED.get() +} + /// Most data sources one image may name (a DeviceN space has up to 32 components). const MAX_SOURCES: usize = 32; /// The longest chain of filters over one pending file (real programs stack two or three). @@ -538,10 +555,10 @@ impl Interp<'_> { // it was; the import goes on without the image either way. let Some(first) = chain.first() else { return }; // Measuring decompresses the data, which is charged by the bytes decoded (one operation - // per 256, as `spend_bytes` charges) and stops at what the budget still pays for: - // data measured again and again (a reusable stream reset in a loop) runs out of the - // budget instead of being decoded in full on every pass. - let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX); + // per [`MEASURED_PER_OP`]) and stops at what the budget still pays for: data measured + // again and again (a reusable stream reset in a loop) runs out of the budget after a + // few passes instead of being decoded in full on every pass. + let most = usize::try_from(self.ops_left().saturating_mul(MEASURED_PER_OP as u64)).unwrap_or(usize::MAX); let (used, decoded) = match &from { Some(r) => match &*r.borrow() { Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most), @@ -549,7 +566,9 @@ impl Interp<'_> { }, None => encoded_len(first, self.lex.data(), most), }; - let paid = self.spend_bytes(decoded).is_ok(); + #[cfg(test)] + MEASURED.set(MEASURED.get().saturating_add(decoded as u64)); + let paid = self.spend((decoded / MEASURED_PER_OP) as u64).is_ok(); let Some(used) = used.filter(|_| paid) else { *f.borrow_mut() = Stream::Pending { chain, from }; return; diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 0ba6c600d5..011cb86ce3 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -7,6 +7,7 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; +use crate::import::data::measured; use crate::import::graphics::{GState, Out, tilings_compared}; use crate::import::interp::Interp; use crate::import::obj::Obj; @@ -1230,16 +1231,19 @@ fn read_within(body: &str, secs: u64) -> crate::Imported { /// [`read_soon`], with how many patterns the tiling pattern lookups compared while reading. fn read_counting_tilings(body: &str) -> (crate::Imported, u64) { - read_counting(body, NEVER_ENDS) + let (read, compared, _) = read_counting(body, NEVER_ENDS); + (read, compared) } -/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading. -fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64) { +/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and +/// how many decoded bytes the measuring of images' data left out decoded. +fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) { let (tx, rx) = std::sync::mpsc::channel(); let ps = eps(body); - std::thread::spawn(move || tx.send((import(&ps), tilings_compared())).ok()); - let (read, compared) = rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); - (read.unwrap(), compared) + std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok()); + let (read, compared, measured) = + rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); + (read.unwrap(), compared, measured) } /// Runs the program of `body` in an interpreter of its own on the 100 × 100 page of [`eps`]'s @@ -1264,9 +1268,15 @@ fn run_looking(body: &str, look: fn(&Interp) -> T) -> T { /// (`search_in_a_loop_runs_out_of_the_budget` searches about 3 GB, 14 s on a fast desktop), so the /// limit here only catches a program that never stops. pub(super) fn runs_out_of_budget(body: &str) { - let r = read_within(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); + runs_out_of_budget_measuring(body); +} + +/// [`runs_out_of_budget`] → how many decoded bytes the measuring of images' data left out decoded. +pub(super) fn runs_out_of_budget_measuring(body: &str) -> u64 { + let (r, _, measured) = read_counting(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); assert_eq!(objects(&r.document).len(), 1, "{body}: {:?}", r.warnings); assert!(r.warnings.iter().any(|w| w.contains("the program runs too long")), "{body}: {:?}", r.warnings); + measured } /// A large file that runs far more operations than a small one may, but only a few hundred for diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index a9385f8eff..6830fb5b41 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -670,14 +670,16 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { /// Measuring the data of an image too large to hold decompresses it, and that is charged to the /// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed /// zeros is left out and measured again each time a loop runs the stream from its start, runs out -/// of the budget. +/// of the budget after it measured the data in full more than once and at most five times. #[test] fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { let mut program = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); - super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); + let measured = + super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); + assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured"); } /// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 4311a54209..6f5ff3d7a2 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -49,6 +49,8 @@ mod scene; mod tiff; pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_ai_editing, private_data as ai_private_data}; +#[cfg(any(test, feature = "work-count"))] +pub use import::blend_work; pub use import::{ AiLayers, Imported, NameEncoding, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, family_style, import, import_ai, import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page, diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 95c4348be8..49cc392f80 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -861,6 +861,58 @@ pub fn curve_bounds(path: &BezPath) -> Rect { path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)).unwrap_or_default() } +/// The box of what a stroke along `path` draws before the stroke's own reach, as +/// [`PathData::drawn_bounds`] measures the path it stands for: the box of its segments, as in +/// [`curve_bounds`], and with `dots` the point of each closed subpath that has no segment, which a +/// round or projecting cap draws as a dot. `None` when the path draws nothing. +pub fn drawn_curve_bounds(path: &BezPath, dots: bool) -> Option { + let mut bbox = path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)); + if !dots { + return bbox; + } + let els = path.elements(); + for (r, closed) in crate::bez::subpaths(path) { + if closed + && kurbo::segments(els[r.clone()].iter().copied()).next().is_none() + && let Some(p) = els[r.start].end_point() + { + let dot = Rect::from_points(p, p); + bbox = Some(bbox.map_or(dot, |bb| bb.union(dot))); + } + } + bbox +} + +/// The box [`PathData::bounds`] measures for the path `path` stands for: its segments, as in +/// [`curve_bounds`], and the point of each subpath that has no segment, a lone anchor, open or +/// closed. `None` for a path with no elements. +pub fn anchored_curve_bounds(path: &BezPath) -> Option { + let mut bbox = path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)); + let mut add = |p: Point| { + let lone = Rect::from_points(p, p); + bbox = Some(bbox.map_or(lone, |bb| bb.union(lone))); + }; + // The start of the current subpath while it has no segment. A `ClosePath` straight after the + // `MoveTo` adds no segment, unless the point is NaN (kurbo then closes with a line of its own, + // which `segments` measured). + let mut lone = None; + for el in path.elements() { + match el { + PathEl::MoveTo(p) => { + if let Some(q) = lone.replace(*p) { + add(q); + } + } + PathEl::ClosePath => {} + _ => lone = None, + } + } + if let Some(q) = lone { + add(q); + } + bbox +} + /// The box of `seg` as kurbo's `bounding_box` measures it (its start, end and extrema), except /// that a segment with a control point whose x or y is not finite or is larger in size than /// `f64::MAX / 16` is measured by its control points. The box then holds every point the segment @@ -916,6 +968,11 @@ mod tests { let path = proptest::collection::vec(sub, 0..4).prop_map(PathData::new); proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + // The kurbo path the anchors stand for draws and measures the same boxes. + for dots in [false, true] { + prop_assert_eq!(bits(drawn_curve_bounds(&pd.to_bezpath(), dots)), bits(pd.drawn_bounds(dots))); + } + prop_assert_eq!(bits(anchored_curve_bounds(&pd.to_bezpath())), bits(pd.bounds())); }); // Two lone anchors: the path has no segment, and the box spans the two points. let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); @@ -942,7 +999,14 @@ mod tests { PathData::new(vec![closed(&[nan, Point::new(3.0, 4.0), Point::new(6.0, 1.0)])]), ] { assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + assert_eq!(bits(anchored_curve_bounds(&pd.to_bezpath())), bits(pd.bounds())); } + // kurbo's own box leaves out the lone anchor, and measures a path of one anchor at the origin. + assert_eq!(anchored_curve_bounds(&beside.to_bezpath()), beside.bounds()); + assert_ne!(Some(beside.to_bezpath().bounding_box()), beside.bounds()); + let one = PathData::single(SubPath::polyline(&[Point::new(7.0, 8.0)], false)); + assert_eq!(anchored_curve_bounds(&one.to_bezpath()), Some(Rect::new(7.0, 8.0, 7.0, 8.0))); + assert_eq!(anchored_curve_bounds(&BezPath::new()), None); } fn square() -> PathData { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 3baad7b7bd..6e6a6edccc 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -4,14 +4,17 @@ //! 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`), -//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator -//! objects' prototypes with `GeneratorFunction` (in `generator`). +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`), `Map`, `Set`, `WeakMap` and +//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can //! run past [`crate::Limits`]. mod array; +pub(crate) mod binary; +pub(crate) mod collections; pub(crate) mod extensions; mod generator; mod global; @@ -270,6 +273,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { } if interp.options.es2015 { promise::install(interp)?; + collections::install(interp)?; + binary::install(interp)?; } Ok(()) } @@ -291,8 +296,16 @@ fn key_of(n: f64) -> Key { number_to_str(n).flat() } -/// ToUint32 of an object's `length`. +/// ToUint32 of an object's `length`. While a `%TypedArray%.prototype` method runs the array +/// method it shares, the typed array's length is its element count, whatever its `length` +/// property says (ECMA-262 6.0 section 22.2.3). fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + if interp.typed_length == Some(o) { + interp.typed_length = None; + if let Some(Class::TypedArray(view)) = interp.heap.object(o).map(|obj| &obj.class) { + return Ok(u32::try_from(view.length).unwrap_or(u32::MAX)); + } + } let len = interp.get_from(o, &key("length"), &Value::Object(o))?; Ok(to_uint32(interp.to_number(&len)?)) } diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..9b7ca4bfa5 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -96,15 +96,23 @@ fn numeric_index(k: &[u16]) -> Option { Some(n) } -/// The objects of the prototype chain from `obj`, with how many properties (and String object -/// indices) each holds. +/// The indices a String object or a typed array holds without properties for them. +fn index_count(class: &Class) -> usize { + match class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + } +} + +/// The objects of the prototype chain from `obj`, with how many properties (and String object or +/// typed array indices) each holds. fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { let mut out = Vec::new(); let mut cur = Some(obj); while let Some(id) = cur { let Some(o) = interp.heap.object(id) else { break }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - out.push((id, o.props.len().saturating_add(string_len))); + out.push((id, o.props.len().saturating_add(index_count(&o.class)))); cur = o.proto; } out @@ -141,8 +149,7 @@ impl Indices { } interp.reserve_heap(n.saturating_mul(8).saturating_mul(self.maps.len() + 1))?; let Some(o) = interp.heap.object(id) else { continue }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - let present = (0..string_len as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); + let present = (0..index_count(&o.class) as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); for p in present { for map in &self.maps { let p = p as i64; @@ -324,18 +331,32 @@ fn join_item(interp: &mut Interp, v: Value) -> JsResult> { /// An element as `toLocaleString` writes it (section 15.4.4.3). fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, false) +} + +/// An element as `%TypedArray%.prototype.toLocaleString` writes it (ECMA-262 6.0 section +/// 22.2.3.27): the method is called on the element's value, not on its object. +fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, true) +} + +/// Calls the element's `toLocaleString`, looked up on its object. With `on_value`, the value +/// itself is `this` for the lookup's getter and for the call (Invoke, section 7.3.18); otherwise +/// the object is. +fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult> { if v.is_nullish() { return Ok(None); } let e = interp.to_object(&v)?; - let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?; + let this = if on_value { v } else { Value::Object(e) }; + let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &this)?; require_callable(interp, &f, "an element's toLocaleString")?; - let s = interp.call(&f, &Value::Object(e), &[])?; + let s = interp.call(&f, &this, &[])?; interp.to_str(&s).map(Some) } /// `Array.prototype.join` (section 15.4.4.5). -fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let separator = arg(args, 0); with_this(interp, &this, |interp, o| join_with(interp, o, &separator, join_item)) } @@ -345,6 +366,12 @@ fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } +/// `%TypedArray%.prototype.toLocaleString` (ECMA-262 6.0 section 22.2.3.27), the array method +/// with each element's method called on the element's value. +pub(super) fn typed_to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, typed_locale_item)) +} + // ---- methods that change the object ---- /// `Array.prototype.concat` (section 15.4.4.4). @@ -413,7 +440,7 @@ fn push(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { +pub(super) fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let middle = len / 2; @@ -692,7 +719,7 @@ fn sort_elements(interp: &mut Interp, o: ObjId, len: u64, compare: &Value) -> Js // ---- searching ---- /// `Array.prototype.indexOf` (section 15.4.4.14). -fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -717,7 +744,7 @@ fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu } /// `Array.prototype.lastIndexOf` (section 15.4.4.15). -fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -794,15 +821,15 @@ fn iterate(interp: &mut Interp, this: Value, args: &[Value], kind: Each) -> JsRe }) } -fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Every) } -fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Some) } -fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Visit) } @@ -852,10 +879,10 @@ fn fold(interp: &mut Interp, this: Value, args: &[Value], right: bool) -> JsResu }) } -fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, false) } -fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, true) } diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs new file mode 100644 index 0000000000..39734bb088 --- /dev/null +++ b/crates/js/src/builtins/binary.rs @@ -0,0 +1,1174 @@ +//! `ArrayBuffer`, `DataView` and the typed arrays (ECMA-262 6.0 sections 24.1, 24.2 and 22.2): +//! `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, +//! `Uint32Array`, `Float32Array` and `Float64Array`, with `%TypedArray%` and its prototype's +//! methods. A realm has them with [`crate::Options::es2015`]. +//! +//! A buffer's bytes are zero when it is made and never change length; no operation detaches +//! one. Views share their buffer's bytes. Typed arrays store their elements little-endian on +//! every platform, and a `DataView` reads and writes big-endian unless `littleEndian` is true. +//! A typed array's numeric property names are its elements or nothing (section 9.4.5, with the +//! element descriptors of later editions: writable, enumerable and configurable, and an element +//! that cannot be deleted); [`crate::interp::Interp`] calls [`element`], [`set_element`] and +//! [`define_element`] for them. +//! +//! A buffer longer than the realm's heap limit, or than 2^32 - 1 bytes, is a `RangeError`, and +//! every buffer's bytes are checked against the heap before they are allocated. Every element +//! a method visits takes a unit of fuel, and a sort's comparisons take one each. +//! +//! The language has no iterators yet, so constructing from an object reads an array or an object +//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A +//! constructor given a primitive string reads it as a length. + +use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, require_callable, to_integer}; +use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; +use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; +use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; + +/// The longest buffer, in bytes. +const MAX_BUFFER: u64 = u32::MAX as u64; + +/// The bytes each item a method gathers before it writes them is charged. +const ITEM_BYTES: usize = 16; + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + install_array_buffer(interp)?; + install_data_view(interp)?; + install_typed_arrays(interp) +} + +fn install_array_buffer(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.array_buffer_proto = proto; + let ctor = native(interp, "ArrayBuffer", array_buffer_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "ArrayBuffer", ctor, proto)?; + method(interp, ctor, "isView", is_view, 1)?; + getter(interp, proto, "get byteLength", buffer_byte_length)?; + method(interp, proto, "slice", buffer_slice, 2) +} + +fn install_data_view(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.data_view_proto = proto; + let ctor = native(interp, "DataView", data_view_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "DataView", ctor, proto)?; + getter(interp, proto, "get buffer", view_buffer)?; + getter(interp, proto, "get byteLength", view_byte_length)?; + getter(interp, proto, "get byteOffset", view_byte_offset)?; + let methods: [(&'static str, NativeFn, u32); 16] = [ + ("getInt8", get_int8, 1), + ("getUint8", get_uint8, 1), + ("getInt16", get_int16, 1), + ("getUint16", get_uint16, 1), + ("getInt32", get_int32, 1), + ("getUint32", get_uint32, 1), + ("getFloat32", get_float32, 1), + ("getFloat64", get_float64, 1), + ("setInt8", set_int8, 2), + ("setUint8", set_uint8, 2), + ("setInt16", set_int16, 2), + ("setUint16", set_uint16, 2), + ("setInt32", set_int32, 2), + ("setUint32", set_uint32, 2), + ("setFloat32", set_float32, 2), + ("setFloat64", set_float64, 2), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + Ok(()) +} + +fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.typed_array_proto = proto; + let ctor = native(interp, "TypedArray", abstract_ctor, 0, NativeKind::Plain, true)?; + interp.intrinsics.es2015.typed_array_ctor = ctor; + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + data(interp, proto, "constructor", Value::Object(ctor), HIDDEN)?; + method(interp, ctor, "from", typed_from, 1)?; + method(interp, ctor, "of", typed_of, 0)?; + for (name, f) in + [("get buffer", ta_buffer as NativeFn), ("get byteLength", ta_byte_length), ("get byteOffset", ta_byte_offset), ("get length", ta_length)] + { + getter(interp, proto, name, f)?; + } + let methods: [(&'static str, NativeFn, u32); 23] = [ + ("copyWithin", copy_within, 2), + ("entries", ta_entries, 0), + ("every", ta_every, 1), + ("fill", fill, 1), + ("filter", filter, 1), + ("find", find, 1), + ("findIndex", find_index, 1), + ("forEach", ta_for_each, 1), + ("indexOf", ta_index_of, 1), + ("join", ta_join, 1), + ("keys", ta_keys, 0), + ("lastIndexOf", ta_last_index_of, 1), + ("map", map, 1), + ("reduce", ta_reduce, 1), + ("reduceRight", ta_reduce_right, 1), + ("reverse", ta_reverse, 0), + ("set", set, 1), + ("slice", slice, 2), + ("some", ta_some, 1), + ("sort", sort, 1), + ("subarray", subarray, 2), + ("toLocaleString", ta_to_locale_string, 0), + ("values", ta_values, 0), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). + let array_proto = interp.intrinsics.array_proto; + let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; + interp.define(proto, key("toString"), crate::heap::Prop::Data { value: to_string, flags: HIDDEN })?; + + let ctors: [NativeFn; 9] = + [int8_ctor, uint8_ctor, uint8_clamped_ctor, int16_ctor, uint16_ctor, int32_ctor, uint32_ctor, float32_ctor, float64_ctor]; + for (elem, f) in Elem::ALL.into_iter().zip(ctors) { + let sub_proto = new_proto(interp, proto); + let sub = native(interp, elem.name(), f, 3, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(sub) { + o.proto = Some(ctor); + } + super::constructor(interp, elem.name(), sub, sub_proto)?; + #[allow(clippy::cast_precision_loss)] + let size = Value::Number(elem.size() as f64); + data(interp, sub, "BYTES_PER_ELEMENT", size.clone(), 0)?; + data(interp, sub_proto, "BYTES_PER_ELEMENT", size, 0)?; + if let Some(slot) = interp.intrinsics.es2015.typed_ctors.get_mut(elem.index()) { + *slot = sub; + } + if let Some(slot) = interp.intrinsics.es2015.typed_protos.get_mut(elem.index()) { + *slot = sub_proto; + } + } + Ok(()) +} + +// ---- elements ---- + +/// CanonicalNumericIndexString (section 7.1.16): the number a property name stands for when it +/// is the canonical text of that number, `-0` included. +pub(crate) fn canonical_index(k: &[u16]) -> Option { + if let Some(i) = array_index(k) { + return Some(f64::from(i)); + } + let first = *k.first()?; + if !(u16::from(b'0')..=u16::from(b'9')).contains(&first) && !b"-IN".iter().any(|c| u16::from(*c) == first) { + return None; + } + if k == [u16::from(b'-'), u16::from(b'0')] { + return Some(-0.0); + } + let n = string_to_number(k, true); + (*number_to_str(n).flat() == *k).then_some(n) +} + +/// The position of the element `n` names in a typed array of `length` elements, if it names one. +fn valid_index(n: f64, length: usize) -> Option { + if n.fract() != 0.0 || (n == 0.0 && n.is_sign_negative()) || n < 0.0 || !n.is_finite() { + return None; + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = n as usize; + (i < length).then_some(i) +} + +/// The buffer's bytes. +fn bytes(interp: &Interp, buffer: ObjId) -> Option<&[u8]> { + match &interp.heap.object(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +fn bytes_mut(interp: &mut Interp, buffer: ObjId) -> Option<&mut [u8]> { + match &mut interp.heap.object_mut(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +/// Reads a value of `elem` from the start of `b` (GetValueFromBuffer, section 24.1.1.5). +fn decode(b: &[u8], elem: Elem, little: bool) -> Option { + let size = elem.size(); + let raw = b.get(..size)?; + let mut bits = 0u64; + for j in 0..size { + let byte = if little { raw.get(j) } else { raw.get(size - 1 - j) }; + bits |= u64::from(*byte?) << (8 * j); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + Some(match elem { + Elem::Int8 => f64::from(bits as u8 as i8), + Elem::Uint8 | Elem::Uint8Clamped => f64::from(bits as u8), + Elem::Int16 => f64::from(bits as u16 as i16), + Elem::Uint16 => f64::from(bits as u16), + Elem::Int32 => f64::from(bits as u32 as i32), + Elem::Uint32 => f64::from(bits as u32), + Elem::Float32 => f64::from(f32::from_bits(bits as u32)), + Elem::Float64 => f64::from_bits(bits), + }) +} + +/// ToUint8Clamp (section 7.1.11): rounds to the nearest integer in 0 to 255, ties to even. +pub(crate) fn to_uint8_clamp(n: f64) -> u8 { + if n.is_nan() || n <= 0.0 { + return 0; + } + if n >= 255.0 { + return 255; + } + let f = n.floor(); + let r = if f + 0.5 < n { + f + 1.0 + } else if n < f + 0.5 || f % 2.0 == 0.0 { + f + } else { + f + 1.0 + }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = r as u8; + byte +} + +/// Writes `n` as a value of `elem` at the start of `b` (SetValueInBuffer, section 24.1.1.6). +/// The integer types keep the low bits of ToUint32, which equal those of ToInt8, ToInt16 and +/// ToInt32. +fn encode(b: &mut [u8], elem: Elem, n: f64, little: bool) { + let size = elem.size(); + let bits = match elem { + Elem::Uint8Clamped => u64::from(to_uint8_clamp(n)), + #[allow(clippy::cast_possible_truncation)] + Elem::Float32 => u64::from((n as f32).to_bits()), + Elem::Float64 => n.to_bits(), + _ => u64::from(to_uint32(n)), + }; + for j in 0..size { + let slot = if little { b.get_mut(j) } else { b.get_mut(size - 1 - j) }; + if let Some(slot) = slot { + #[allow(clippy::cast_possible_truncation)] + let byte = (bits >> (8 * j)) as u8; + *slot = byte; + } + } +} + +/// The element of `view` at the index `n`, or `None` when `n` names no element. +pub(crate) fn element(interp: &Interp, view: &View, n: f64) -> Option { + let i = valid_index(n, view.length)?; + let at = view.offset.checked_add(i.checked_mul(view.elem.size())?)?; + decode(bytes(interp, view.buffer)?.get(at..)?, view.elem, true) +} + +/// The view of the typed array `id`. +fn view_of(interp: &Interp, id: ObjId) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(view) => Some(**view), + _ => None, + } +} + +/// Writes `n` to the element at position `i` of `view`, when there is one. +fn write(interp: &mut Interp, view: &View, i: usize, n: f64) { + let Some(at) = i.checked_mul(view.elem.size()).and_then(|o| o.checked_add(view.offset)) else { return }; + if i < view.length + && let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) + { + encode(b, view.elem, n, true); + } +} + +/// Copies `count` elements of `src` from position `from` to `dst` at position `to` byte for byte, as +/// a typed array is copied to one of the same element type (sections 22.2.3.22.2, 22.2.3.23 and +/// 22.2.4.3), so every bit pattern, a NaN's included, is kept. Overlapping ranges of one buffer copy +/// correctly. Each element takes a unit of fuel. +fn copy_elements(interp: &mut Interp, src: &View, from: usize, dst: &View, to: usize, count: usize) -> JsResult<()> { + for _ in 0..count { + interp.use_fuel()?; + } + let size = src.elem.size(); + let (s, d, n) = (src.offset + from * size, dst.offset + to * size, count * size); + if src.buffer == dst.buffer { + if let Some(b) = bytes_mut(interp, src.buffer) + && s + n <= b.len() + && d + n <= b.len() + { + b.copy_within(s..s + n, d); + } + return Ok(()); + } + // The destination's bytes are moved out while the source's are read, so no third copy is made. + let mut out = match &mut interp.object_mut(dst.buffer)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(from_bytes), Some(to_bytes)) = (bytes(interp, src.buffer).and_then(|b| b.get(s..s + n)), out.get_mut(d..d + n)) { + to_bytes.copy_from_slice(from_bytes); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(dst.buffer)?.class { + *b = out; + } + Ok(()) +} + +/// The number a typed array `id`'s numeric property name `k` stands for. +pub(crate) fn typed_key(interp: &Interp, id: ObjId, k: &[u16]) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(_) => canonical_index(k), + _ => None, + } +} + +/// `[[Set]]` of a numeric name of a typed array: the value is converted with ToNumber, then +/// written when the index names an element and ignored otherwise. +pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> JsResult<()> { + let num = interp.to_number(v)?; + if let Some(view) = view_of(interp, id) + && let Some(i) = valid_index(n, view.length) + { + write(interp, &view, i, num); + } + Ok(()) +} + +/// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the +/// configurable elements of later editions). +pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let view = view_of(interp, id); + let index = canonical_index(k).zip(view).and_then(|(n, view)| valid_index(n, view.length)); + let refused = + index.is_none() || desc.configurable == Some(false) || desc.enumerable == Some(false) || desc.is_accessor() || desc.writable == Some(false); + if refused { + if throw { + let name = String::from_utf16_lossy(k); + return Err(interp.type_error(&format!("cannot define property '{name}' of a typed array"))); + } + return Ok(false); + } + if let (Some(v), Some(view), Some(i)) = (&desc.value, view, index) { + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(true) +} + +// ---- making buffers and views ---- + +/// ToIndex (section 7.1.17 of later editions): `undefined` is 0, and a negative or too large +/// integer is a `RangeError`. +fn to_index(interp: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(0); + } + let n = to_integer(interp, v)?; + if !(0.0..=9_007_199_254_740_991.0).contains(&n) { + return Err(interp.throw(ErrorType::Range, &format!("{what} must be an integer from 0 to 2^53 - 1"))); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(n as u64) +} + +/// A new zeroed buffer of `len` bytes. A length past [`MAX_BUFFER`] or the heap limit is a +/// `RangeError`; otherwise the bytes and `extra` more are reserved before the buffer is +/// allocated. +fn new_buffer(interp: &mut Interp, len: u64, extra: usize) -> JsResult { + if len > MAX_BUFFER || len > interp.limits.heap_bytes as u64 { + return Err(interp.throw(ErrorType::Range, &format!("an array buffer of {len} bytes is larger than the heap limit allows"))); + } + let len = usize::try_from(len).map_err(|_| interp.throw(ErrorType::Range, "the array buffer is too large"))?; + interp.reserve_heap(OBJECT_BYTES.saturating_add(len).saturating_add(extra))?; + let mut b = Vec::new(); + if b.try_reserve_exact(len).is_err() { + return Err(interp.throw(ErrorType::Range, "the memory for the array buffer could not be allocated")); + } + b.resize(len, 0); + let proto = interp.intrinsics.es2015.array_buffer_proto; + let o = interp.heap.alloc_object(Object::new(Class::ArrayBuffer(b.into_boxed_slice()), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(len); + Ok(o) +} + +/// A new view object of `class` on a buffer that is reachable. Its heap was reserved before. +fn new_view(interp: &mut Interp, class: Class, proto: ObjId) -> ObjId { + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + o +} + +fn typed_proto(interp: &Interp, elem: Elem) -> ObjId { + interp.intrinsics.es2015.typed_protos.get(elem.index()).copied().unwrap_or(interp.intrinsics.es2015.typed_array_proto) +} + +/// A new typed array of `len` zero elements of `elem`, with a new buffer. +fn new_typed(interp: &mut Interp, elem: Elem, len: u64) -> JsResult { + let byte_len = len.saturating_mul(elem.size() as u64); + let buffer = new_buffer(interp, byte_len, OBJECT_BYTES + VIEW_BYTES)?; + let length = usize::try_from(len).unwrap_or(0); + let proto = typed_proto(interp, elem); + Ok(new_view(interp, Class::TypedArray(Box::new(View { buffer, offset: 0, length, elem })), proto)) +} + +/// `new ArrayBuffer(length)` (section 24.1.2.1). +fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("ArrayBuffer must be called with new")); + } + let len = to_index(interp, &arg(args, 0), "the length")?; + new_buffer(interp, len, 0).map(Value::Object) +} + +/// `ArrayBuffer.isView` (section 24.1.3.1). +fn is_view(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let view = + arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::DataView(_) | Class::TypedArray(_))); + Ok(Value::Bool(view)) +} + +fn this_buffer(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if bytes(interp, o).is_some() => Ok(o), + _ => Err(interp.type_error(&format!("ArrayBuffer.prototype.{name} was called on a value that is not an ArrayBuffer"))), + } +} + +fn buffer_len(interp: &Interp, o: ObjId) -> usize { + bytes(interp, o).map_or(0, <[u8]>::len) +} + +fn buffer_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "byteLength")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(buffer_len(interp, o) as f64)) +} + +/// A relative index (as `slice` reads its arguments): negative counts from `len`, and the result +/// is clamped to 0 to `len`. `undefined` gives `default`. +fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(default); + } + let n = to_integer(interp, v)?; + #[allow(clippy::cast_precision_loss)] + let len_f = len as f64; + let r = if n < 0.0 { (len_f + n).max(0.0) } else { n.min(len_f) }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(r as usize) +} + +/// The `constructor` steps of SpeciesConstructor (section 7.3.20): reads `o.constructor` and +/// throws a `TypeError` when it is neither `undefined` nor an object. The language has no +/// `@@species`, so the result is always made with the intrinsic constructor. +fn species_check(interp: &mut Interp, o: ObjId, name: &str) -> JsResult<()> { + let c = interp.get_from(o, &key("constructor"), &Value::Object(o))?; + if matches!(c, Value::Undefined | Value::Object(_)) { + return Ok(()); + } + Err(interp.type_error(&format!("{name}: the constructor property is not an object"))) +} + +/// `ArrayBuffer.prototype.slice` (section 24.1.4.3). +fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "slice")?; + let len = buffer_len(interp, o); + let first = relative(interp, &arg(args, 0), len, 0)?; + let last = relative(interp, &arg(args, 1), len, len)?; + species_check(interp, o, "ArrayBuffer.prototype.slice")?; + let count = last.saturating_sub(first); + // Each copied byte takes a unit of fuel, charged before the copy is made. + for _ in 0..count { + interp.use_fuel()?; + } + let new = interp.rooted(std::slice::from_ref(&this), |i| new_buffer(i, count as u64, 0))?; + // The new buffer's bytes are moved out while the source's are read, so no third copy is made. + let mut dst = match &mut interp.object_mut(new)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(src), Some(to)) = (bytes(interp, o).and_then(|b| b.get(first..first + count)), dst.get_mut(..count)) { + to.copy_from_slice(src); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(new)?.class { + *b = dst; + } + Ok(Value::Object(new)) +} + +// ---- DataView ---- + +/// `new DataView(buffer, byteOffset, byteLength)` (section 24.2.2.1). +fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("DataView must be called with new")); + } + let buffer = match arg(args, 0).as_object() { + Some(o) if bytes(interp, o).is_some() => o, + _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), + }; + let offset = to_index(interp, &arg(args, 1), "the byte offset")?; + let len = buffer_len(interp, buffer) as u64; + if offset > len { + return Err(interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer")); + } + let view_len = match arg(args, 2) { + Value::Undefined => len - offset, + v => to_index(interp, &v, "the byte length")?, + }; + if offset.saturating_add(view_len) > len { + return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = interp.intrinsics.es2015.data_view_proto; + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; + Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) +} + +fn this_data_view(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + if let Some(Class::DataView(view)) = this.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + return Ok(**view); + } + Err(interp.type_error(&format!("DataView.prototype.{name} was called on a value that is not a DataView"))) +} + +fn view_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_data_view(interp, &this, "buffer")?.buffer)) +} + +fn view_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteLength")?.length as f64)) +} + +fn view_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteOffset")?.offset as f64)) +} + +/// The byte position in the buffer of a `DataView` access of `elem` at `index`, or a +/// `RangeError` when it does not fit in the view (sections 24.2.1.1 and 24.2.1.2). +fn view_position(interp: &mut Interp, view: &View, index: u64, elem: Elem) -> JsResult { + let end = index.saturating_add(elem.size() as u64); + if end > view.length as u64 { + return Err(interp.throw(ErrorType::Range, "the offset is outside the bounds of the DataView")); + } + Ok(view.offset + usize::try_from(index).unwrap_or(0)) +} + +/// GetViewValue (section 24.2.1.1). +fn view_get(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let little = arg(args, 1).truthy(); + let at = view_position(interp, &view, index, elem)?; + let n = bytes(interp, view.buffer).and_then(|b| b.get(at..)).and_then(|b| decode(b, elem, little)).unwrap_or(0.0); + Ok(Value::Number(n)) +} + +/// SetViewValue (section 24.2.1.2): the offset, then the value, then `littleEndian` are read +/// before the bounds are checked. +fn view_set(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let n = interp.to_number(&arg(args, 1))?; + let little = arg(args, 2).truthy(); + let at = view_position(interp, &view, index, elem)?; + if let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) { + encode(b, elem, n, little); + } + Ok(Value::Undefined) +} + +macro_rules! view_methods { + ($($get:ident, $set:ident, $elem:ident, $getname:literal, $setname:literal;)*) => { + $( + fn $get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_get(interp, &this, args, Elem::$elem, $getname) + } + + fn $set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_set(interp, &this, args, Elem::$elem, $setname) + } + )* + }; +} + +view_methods! { + get_int8, set_int8, Int8, "getInt8", "setInt8"; + get_uint8, set_uint8, Uint8, "getUint8", "setUint8"; + get_int16, set_int16, Int16, "getInt16", "setInt16"; + get_uint16, set_uint16, Uint16, "getUint16", "setUint16"; + get_int32, set_int32, Int32, "getInt32", "setInt32"; + get_uint32, set_uint32, Uint32, "getUint32", "setUint32"; + get_float32, set_float32, Float32, "getFloat32", "setFloat32"; + get_float64, set_float64, Float64, "getFloat64", "setFloat64"; +} + +// ---- typed array constructors ---- + +/// `%TypedArray%` itself (section 22.2.1.1) cannot be called or constructed. +fn abstract_ctor(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(interp.type_error("TypedArray cannot be called or constructed; use a typed array constructor such as Uint8Array")) +} + +/// `new Int8Array(…)` and the other typed array constructors (section 22.2.4). +fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Elem) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{} must be called with new", elem.name()))); + } + let first = arg(args, 0); + let Value::Object(o) = first else { + let len = to_index(interp, &first, "the length")?; + return new_typed(interp, elem, len).map(Value::Object); + }; + if bytes(interp, o).is_some() { + return typed_on_buffer(interp, o, &arg(args, 1), &arg(args, 2), elem).map(Value::Object); + } + if let Some(src) = view_of(interp, o) { + let ta = new_typed(interp, elem, src.length as u64)?; + let dst = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if src.elem == elem { + copy_elements(interp, &src, 0, &dst, 0, src.length)?; + return Ok(Value::Object(ta)); + } + for i in 0..src.length { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let n = element(interp, &src, i as f64).unwrap_or(0.0); + write(interp, &dst, i, n); + } + return Ok(Value::Object(ta)); + } + let len = length_of(interp, o)?; + let ta = new_typed(interp, elem, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; + Ok(Value::Object(ta)) +} + +/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, +/// each converted with ToNumber. +fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { + let Value::Object(o) = src else { return Ok(()) }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(()) +} + +/// A typed array on part of `buffer` (section 22.2.4.5). +fn typed_on_buffer(interp: &mut Interp, buffer: ObjId, offset: &Value, length: &Value, elem: Elem) -> JsResult { + let size = elem.size() as u64; + let offset = to_index(interp, offset, "the byte offset")?; + if !offset.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the byte offset of a {} must be a multiple of {size}", elem.name()))); + } + let new_length = match length { + Value::Undefined => None, + v => Some(to_index(interp, v, "the length")?), + }; + let buf_len = buffer_len(interp, buffer) as u64; + let byte_len = match new_length { + None => { + if !buf_len.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the buffer's length must be a multiple of {size}"))); + } + buf_len.checked_sub(offset).ok_or_else(|| interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer"))? + } + Some(n) => n.saturating_mul(size), + }; + if offset.saturating_add(byte_len) > buf_len { + return Err(interp.throw(ErrorType::Range, "the typed array does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = typed_proto(interp, elem); + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(byte_len / size).unwrap_or(0), elem }; + Ok(new_view(interp, Class::TypedArray(Box::new(view)), proto)) +} + +macro_rules! typed_ctors { + ($($f:ident, $elem:ident;)*) => { + $( + fn $f(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + typed_ctor(interp, args, constructing, Elem::$elem) + } + )* + }; +} + +typed_ctors! { + int8_ctor, Int8; + uint8_ctor, Uint8; + uint8_clamped_ctor, Uint8Clamped; + int16_ctor, Int16; + uint16_ctor, Uint16; + int32_ctor, Int32; + uint32_ctor, Uint32; + float32_ctor, Float32; + float64_ctor, Float64; +} + +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let ctors = interp.intrinsics.es2015.typed_ctors; + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) +} + +/// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). +fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); + } + let map_fn = arg(args, 1); + let mapping = !matches!(map_fn, Value::Undefined); + if mapping { + require_callable(interp, &map_fn, "the map function")?; + } + let this_arg = arg(args, 2); + let source = arg(args, 0); + if !matches!(source, Value::String(_)) { + // An array-like source: each element is read, mapped and written before the next is read. + let src = interp.to_object(&source)?; + let src_value = Value::Object(src); + let len = length_of(interp, src)?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(Value::Object(ta)) + }); + } + // A string is read by code point first, as an iterable source is, and then mapped. + let mark = interp.temp_roots.len(); + let mut held = crate::interp::HeldBytes::new(interp); + let gathered = for_each_item(interp, &source, false, |interp, item| { + held.add(interp, ITEM_BYTES)?; + interp.temp_roots.push(item); + Ok(()) + }); + let result = gathered.and_then(|()| { + let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; + interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, item) in items.into_iter().enumerate() { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }); + interp.temp_roots.truncate(mark); + drop(held); + result +} + +/// `%TypedArray%.of(...items)` (section 22.2.2.2). +fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(ta)], |interp| { + for (i, v) in args.iter().enumerate() { + interp.use_fuel()?; + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }) +} + +// ---- %TypedArray%.prototype ---- + +/// The typed array a method was called on (ValidateTypedArray, section 22.2.3.5.1). +fn this_typed(interp: &mut Interp, this: &Value, name: &str) -> JsResult<(ObjId, View)> { + if let Some(o) = this.as_object() + && let Some(view) = view_of(interp, o) + { + return Ok((o, view)); + } + Err(interp.type_error(&format!("TypedArray.prototype.{name} was called on a value that is not a typed array"))) +} + +fn ta_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_typed(interp, &this, "buffer")?.1.buffer)) +} + +fn ta_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let view = this_typed(interp, &this, "byteLength")?.1; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number((view.length * view.elem.size()) as f64)) +} + +fn ta_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "byteOffset")?.1.offset as f64)) +} + +fn ta_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "length")?.1.length as f64)) +} + +/// The element at position `i`, 0 past the end. +fn at(interp: &Interp, view: &View, i: usize) -> f64 { + #[allow(clippy::cast_precision_loss)] + element(interp, view, i as f64).unwrap_or(0.0) +} + +/// Runs the array prototype's generic method `f` on a typed array, after checking `this`. +/// The array method reads the typed array's element count as its length, not its `length` +/// property. +fn generic(interp: &mut Interp, this: Value, args: &[Value], name: &str, f: NativeFn) -> JsResult { + let (o, _) = this_typed(interp, &this, name)?; + let saved = interp.typed_length.replace(o); + let result = f(interp, this, args, false); + interp.typed_length = saved; + result +} + +macro_rules! generic_methods { + ($($f:ident, $name:literal, $array:path;)*) => { + $( + fn $f(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + generic(interp, this, args, $name, $array) + } + )* + }; +} + +generic_methods! { + ta_every, "every", array::every; + ta_some, "some", array::some; + ta_for_each, "forEach", array::for_each; + ta_index_of, "indexOf", array::index_of; + ta_last_index_of, "lastIndexOf", array::last_index_of; + ta_join, "join", array::join; + ta_reduce, "reduce", array::reduce; + ta_reduce_right, "reduceRight", array::reduce_right; + ta_reverse, "reverse", array::reverse; + ta_to_locale_string, "toLocaleString", array::typed_to_locale_string; +} + +fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { + let (o, _) = this_typed(interp, this, name)?; + new_iter(interp, o, IterSource::Array, kind, None).map(Value::Object) +} + +fn ta_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Keys, "keys") +} + +fn ta_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Values, "values") +} + +fn ta_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Entries, "entries") +} + +/// `fill(value, start, end)` (section 22.2.3.8): the value is converted once, before the range. +fn fill(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "fill")?; + let n = interp.to_number(&arg(args, 0))?; + let start = relative(interp, &arg(args, 1), view.length, 0)?; + let end = relative(interp, &arg(args, 2), view.length, view.length)?; + for i in start..end { + interp.use_fuel()?; + write(interp, &view, i, n); + } + Ok(this) +} + +/// Calls `f(element, index, array)` for each element in order until `stop` says the result is +/// found; returns the index and the element. +fn search(interp: &mut Interp, this: &Value, args: &[Value], name: &str) -> JsResult> { + let (_, view) = this_typed(interp, this, name)?; + let f = arg(args, 0); + require_callable(interp, &f, "the predicate")?; + let this_arg = arg(args, 1); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + return Ok(Some((i, v))); + } + } + Ok(None) +} + +/// `find` (section 22.2.3.10). +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + Ok(search(interp, &this, args, "find")?.map_or(Value::Undefined, |(_, v)| Value::Number(v))) +} + +/// `findIndex` (section 22.2.3.11). +fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(search(interp, &this, args, "findIndex")?.map_or(-1.0, |(i, _)| i as f64))) +} + +/// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. +fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "map")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.map")?; + let out = new_typed(interp, view.elem, view.length as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(out)], |interp| { + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + let n = interp.to_number(&r)?; + write(interp, &dst, i, n); + } + Ok(Value::Object(out)) + }) +} + +/// A new typed array of `elem` holding `values`. +fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResult { + let out = new_typed(interp, elem, values.len() as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, n) in values.iter().enumerate() { + write(interp, &dst, i, *n); + } + Ok(out) +} + +/// `filter` (section 22.2.3.9). +fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "filter")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.filter")?; + let mut held = crate::interp::HeldBytes::new(interp); + let mut kept = Vec::new(); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + held.add(interp, 8)?; + kept.push(v); + } + } + let out = typed_from_values(interp, view.elem, &kept)?; + drop(held); + Ok(Value::Object(out)) +} + +/// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. +fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "slice")?; + let start = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + let count = end.saturating_sub(start); + species_check(interp, o, "TypedArray.prototype.slice")?; + let out = new_typed(interp, view.elem, count as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + copy_elements(interp, &view, start, &dst, 0, count)?; + Ok(Value::Object(out)) +} + +/// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. +fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "subarray")?; + let begin = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + species_check(interp, o, "TypedArray.prototype.subarray")?; + interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; + let proto = typed_proto(interp, view.elem); + Ok(Value::Object(new_view(interp, Class::TypedArray(Box::new(sub)), proto))) +} + +/// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like +/// object's elements converted with ToNumber, starting at `offset`. A source that does not fit +/// is a `RangeError`. A typed array source on the same buffer is read in full before anything is +/// written, so it copies correctly. +fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "set")?; + let offset = to_integer(interp, &arg(args, 1))?; + if offset < 0.0 { + return Err(interp.throw(ErrorType::Range, "the offset must not be negative")); + } + let source = arg(args, 0); + let src_view = source.as_object().and_then(|o| view_of(interp, o)); + let src_len = match (&source, src_view) { + (_, Some(v)) => v.length as u64, + (Value::Object(o), None) => length_of(interp, *o)?, + _ => { + let o = interp.to_object(&source)?; + length_of(interp, o)? + } + }; + #[allow(clippy::cast_precision_loss)] + if offset + src_len as f64 > view.length as f64 { + return Err(interp.throw(ErrorType::Range, "the source does not fit in the typed array at that offset")); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let offset = offset as usize; + let count = usize::try_from(src_len).unwrap_or(0); + if let Some(src) = src_view.filter(|src| src.elem == view.elem) { + copy_elements(interp, &src, 0, &view, offset, count)?; + return Ok(Value::Undefined); + } + if let Some(src) = src_view.filter(|src| src.buffer != view.buffer) { + // On another buffer, the writes do not change the source, so each element is written as + // it is read. + for i in 0..count { + interp.use_fuel()?; + let n = at(interp, &src, i); + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + if let Some(src) = src_view { + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, count.saturating_mul(8))?; + let mut values = Vec::with_capacity(count); + for i in 0..count { + interp.use_fuel()?; + values.push(at(interp, &src, i)); + } + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + let src = interp.to_object(&source)?; + interp.rooted(&[Value::Object(src)], |interp| { + for i in 0..count { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(src, &super::key_of(i as f64), &Value::Object(src))?; + let n = interp.to_number(&v)?; + write(interp, &view, offset + i, n); + } + Ok(Value::Undefined) + }) +} + +/// `copyWithin(target, start, end)` (section 22.2.3.5): moves the bytes of the range within the +/// buffer, overlapping ranges included. +fn copy_within(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "copyWithin")?; + let len = view.length; + let to = relative(interp, &arg(args, 0), len, 0)?; + let from = relative(interp, &arg(args, 1), len, 0)?; + let end = relative(interp, &arg(args, 2), len, len)?; + let count = end.saturating_sub(from).min(len - to); + copy_elements(interp, &view, from, &view, to, count)?; + Ok(this) +} + +/// The default order of `sort` (section 22.2.3.25): numeric, with `-0` before `+0` and `NaN` +/// last. +fn default_order(a: f64, b: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (a.is_nan(), b.is_nan()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + _ if a == 0.0 && b == 0.0 => b.is_sign_negative().cmp(&a.is_sign_negative()), + _ => a.partial_cmp(&b).unwrap_or(Ordering::Equal), + } +} + +/// Whether `b` goes before `a`: by `compare` when it is a function, the default order otherwise. +/// Each comparison takes a unit of fuel. +fn goes_before(interp: &mut Interp, compare: &Value, a: f64, b: f64) -> JsResult { + interp.use_fuel()?; + if matches!(compare, Value::Undefined) { + return Ok(default_order(b, a) == std::cmp::Ordering::Less); + } + let r = interp.call(compare, &Value::Undefined, &[Value::Number(a), Value::Number(b)])?; + let n = interp.to_number(&r)?; + Ok(n > 0.0) +} + +/// Sorts `values` stably with a merge sort whose comparisons may fail. +fn merge_sort(interp: &mut Interp, values: &mut Vec, compare: &Value) -> JsResult<()> { + let n = values.len(); + let mut buf = values.clone(); + let mut width = 1; + while width < n { + let mut lo = 0; + while lo < n { + let mid = (lo + width).min(n); + let hi = (lo + 2 * width).min(n); + let (mut i, mut j) = (lo, mid); + for slot in buf.iter_mut().take(hi).skip(lo) { + let take_right = match (values.get(i), values.get(j)) { + (Some(&a), Some(&b)) if i < mid && j < hi => goes_before(interp, compare, a, b)?, + _ => i >= mid, + }; + let pick = if take_right { &mut j } else { &mut i }; + *slot = values.get(*pick).copied().unwrap_or(0.0); + *pick += 1; + } + lo = hi; + } + std::mem::swap(values, &mut buf); + width *= 2; + } + Ok(()) +} + +/// `sort(comparefn)` (section 22.2.3.25). +fn sort(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let compare = arg(args, 0); + if !matches!(compare, Value::Undefined) { + require_callable(interp, &compare, "the comparison function")?; + } + let (_, view) = this_typed(interp, &this, "sort")?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, view.length.saturating_mul(16))?; + // Each element is read and written back: two units of fuel, charged before the sort starts. + for _ in 0..view.length.saturating_mul(2) { + interp.use_fuel()?; + } + let mut values: Vec = (0..view.length).map(|i| at(interp, &view, i)).collect(); + merge_sort(interp, &mut values, &compare)?; + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, i, n); + } + Ok(this) +} diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs new file mode 100644 index 0000000000..70da37c39c --- /dev/null +++ b/crates/js/src/builtins/collections.rs @@ -0,0 +1,697 @@ +//! `Map`, `Set`, `WeakMap` and `WeakSet` (ECMA-262 6.0 sections 23.1 to 23.4), and the iterator +//! objects that `keys`, `values` and `entries` give for Maps, Sets and typed arrays (sections +//! 23.1.5, 23.2.5 and 22.1.5). A realm has them with [`crate::Options::es2015`]. +//! +//! Keys compare with SameValueZero, and a key of `-0` is stored as `+0`. Entries keep the order +//! they were added in; deleting one leaves a hole, so `forEach` and an iterator visit the entries +//! added while they run and skip the ones deleted before they reach them. WeakMap and WeakSet +//! entries hold their key weakly: the collector removes an entry once its key is reachable only +//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. +//! +//! The language has no iterators yet, so the constructors read their argument by index: an +//! array or an object with a `length`, or a string by code point. Every entry added is checked +//! against the heap limit before it is added, and every entry visited takes a unit of fuel. + +use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use crate::heap::{ + COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, + PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, +}; +use crate::interp::{Abrupt, Interp, JsResult}; +use crate::string_builtins::flat_charged; +use crate::value::{Str, Value}; + +/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does +/// to the globals. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Es2015 { + pub(crate) map_proto: ObjId, + pub(crate) set_proto: ObjId, + pub(crate) weak_map_proto: ObjId, + pub(crate) weak_set_proto: ObjId, + pub(crate) map_iter_proto: ObjId, + pub(crate) set_iter_proto: ObjId, + pub(crate) array_iter_proto: ObjId, + pub(crate) array_buffer_proto: ObjId, + pub(crate) data_view_proto: ObjId, + /// `%TypedArray%` and its prototype (section 22.2.1). + pub(crate) typed_array_ctor: ObjId, + pub(crate) typed_array_proto: ObjId, + /// The typed array constructors and prototypes, in the order of [`crate::heap::Elem::ALL`]. + pub(crate) typed_ctors: [ObjId; 9], + pub(crate) typed_protos: [ObjId; 9], +} + +impl Es2015 { + pub(crate) fn placeholder() -> Self { + let o = ObjId(0); + Self { + map_proto: o, + set_proto: o, + weak_map_proto: o, + weak_set_proto: o, + map_iter_proto: o, + set_iter_proto: o, + array_iter_proto: o, + array_buffer_proto: o, + data_view_proto: o, + typed_array_ctor: o, + typed_array_proto: o, + typed_ctors: [o; 9], + typed_protos: [o; 9], + } + } + + pub(crate) fn all(&self) -> Vec { + let mut v = vec![ + self.map_proto, + self.set_proto, + self.weak_map_proto, + self.weak_set_proto, + self.map_iter_proto, + self.set_iter_proto, + self.array_iter_proto, + self.array_buffer_proto, + self.data_view_proto, + self.typed_array_ctor, + self.typed_array_proto, + ]; + v.extend(self.typed_ctors); + v.extend(self.typed_protos); + v + } +} + +/// A new ordinary object with `proto`, for a prototype. +pub(crate) fn new_proto(interp: &mut Interp, proto: ObjId) -> ObjId { + interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))) +} + +/// Defines a getter `name` on `on`, configurable and not enumerable, as the prototype accessors +/// of ECMAScript 2015 are. +pub(crate) fn getter(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn) -> JsResult<()> { + let g = native(interp, name, f, 0, NativeKind::Plain, false)?; + let prop_name = name.strip_prefix("get ").unwrap_or(name); + interp.define(on, key(prop_name), Prop::Accessor { get: Some(g), set: None, flags: CONFIGURABLE }) +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + + let map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.map_proto = map_proto; + let map = native(interp, "Map", map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Map", map, map_proto)?; + let map_methods: [(&'static str, NativeFn, u32); 9] = [ + ("get", map_get, 1), + ("set", map_set, 2), + ("has", map_has, 1), + ("delete", map_delete, 1), + ("clear", map_clear, 0), + ("forEach", map_for_each, 1), + ("keys", map_keys, 0), + ("values", map_values, 0), + ("entries", map_entries, 0), + ]; + for (name, f, length) in map_methods { + method(interp, map_proto, name, f, length)?; + } + getter(interp, map_proto, "get size", map_size)?; + + let set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.set_proto = set_proto; + let set = native(interp, "Set", set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Set", set, set_proto)?; + let set_methods: [(&'static str, NativeFn, u32); 7] = [ + ("has", set_has, 1), + ("add", set_add, 1), + ("delete", set_delete, 1), + ("clear", set_clear, 0), + ("entries", set_entries, 0), + ("forEach", set_for_each, 1), + ("values", set_values, 0), + ]; + for (name, f, length) in set_methods { + method(interp, set_proto, name, f, length)?; + } + getter(interp, set_proto, "get size", set_size)?; + // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). + let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; + interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + + let weak_map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_map_proto = weak_map_proto; + let weak_map = native(interp, "WeakMap", weak_map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakMap", weak_map, weak_map_proto)?; + let weak_map_methods: [(&'static str, NativeFn, u32); 4] = + [("delete", weak_map_delete, 1), ("get", weak_map_get, 1), ("has", weak_map_has, 1), ("set", weak_map_set, 2)]; + for (name, f, length) in weak_map_methods { + method(interp, weak_map_proto, name, f, length)?; + } + + let weak_set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_set_proto = weak_set_proto; + let weak_set = native(interp, "WeakSet", weak_set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakSet", weak_set, weak_set_proto)?; + let weak_set_methods: [(&'static str, NativeFn, u32); 3] = [("add", weak_set_add, 1), ("delete", weak_set_delete, 1), ("has", weak_set_has, 1)]; + for (name, f, length) in weak_set_methods { + method(interp, weak_set_proto, name, f, length)?; + } + + for source in [IterSource::Map, IterSource::Set, IterSource::Array] { + let proto = new_proto(interp, object_proto); + let next: NativeFn = match source { + IterSource::Map => map_iterator_next, + IterSource::Set => set_iterator_next, + IterSource::Array => array_iterator_next, + }; + method(interp, proto, "next", next, 0)?; + match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto = proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto = proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto = proto, + } + } + Ok(()) +} + +// ---- keys ---- + +/// The SameValueZero key of `v`. A string is flattened, its copy charged to the heap. +fn coll_key(interp: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => CollKey::Undefined, + Value::Null => CollKey::Null, + Value::Bool(b) => CollKey::Bool(*b), + Value::Number(n) => CollKey::number(*n), + Value::String(s) => CollKey::String(flat_charged(interp, s)?), + Value::Symbol(s) => CollKey::Symbol(s.clone()), + Value::Object(o) => CollKey::Object(o.0), + }) +} + +/// `v`, with `-0` made `+0`, as Map and Set store a key (sections 23.1.3.9 and 23.2.3.1). +fn stored_key(v: Value) -> Value { + match v { + // `-0 + 0` is `+0`, and every other number is unchanged by adding `+0`. + Value::Number(n) => Value::Number(n + 0.0), + v => v, + } +} + +// ---- reading a list ---- + +/// ToLength (section 7.1.15) of an object's `length`. +pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + let len = interp.get_from(o, &key("length"), &Value::Object(o))?; + let n = super::to_integer(interp, &len)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) +} + +/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, +/// or a string's code points. Any other value is a `TypeError`, and so is an object without a +/// `length` when `need_length` is true. Each item takes a unit of fuel. +pub(crate) fn for_each_item( + interp: &mut Interp, + list: &Value, + need_length: bool, + mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, +) -> JsResult<()> { + match list { + Value::Object(o) => { + if need_length && !interp.has_property(*o, &key("length"))? { + return Err(interp.type_error("the value is not an array, a string or an object with a length")); + } + let len = length_of(interp, *o)?; + let mut i = 0u64; + while i < len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(*o, &key_of(i as f64), list)?; + f(interp, item)?; + i += 1; + } + Ok(()) + } + Value::String(s) => { + let units = flat_charged(interp, s)?; + let mut i = 0; + while i < units.len() { + interp.use_fuel()?; + let width = match (units.get(i), units.get(i + 1)) { + (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, + _ => 1, + }; + let piece = units.get(i..i + width).unwrap_or_default().to_vec(); + let bytes = string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + f(interp, Value::String(Str::from_units(piece)))?; + i += width; + } + Ok(()) + } + _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), + } +} + +/// Adds the items of `list` to the new collection `target` with its `adder` method, as the +/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item +/// as a `[key, value]` entry. +fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { + if list.is_nullish() { + return Ok(()); + } + let this = Value::Object(target); + interp.rooted(&[this.clone(), list.clone()], |interp| { + let add = interp.get_from(target, &key(adder), &this)?; + require_callable(interp, &add, adder)?; + interp.rooted(std::slice::from_ref(&add), |interp| { + for_each_item(interp, list, true, |interp, item| { + if !pairs { + return interp.call(&add, &this, &[item]).map(drop); + } + let Value::Object(entry) = item else { return Err(interp.type_error("an entry is not an object")) }; + let k = interp.get_from(entry, &key("0"), &item)?; + let v = interp.rooted(std::slice::from_ref(&k), |interp| interp.get_from(entry, &key("1"), &item))?; + interp.call(&add, &this, &[k, v]).map(drop) + }) + }) + }) +} + +/// A new collection object of `class` with `proto`, filled from `args[0]`. +fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{name} must be called with new"))); + } + interp.reserve_heap(OBJECT_BYTES)?; + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + let (adder, pairs) = match name { + "Map" | "WeakMap" => ("set", true), + _ => ("add", false), + }; + fill(interp, o, &arg(args, 0), adder, pairs)?; + Ok(Value::Object(o)) +} + +fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.map_proto; + construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto) +} + +fn set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.set_proto; + construct(interp, args, constructing, "Set", Class::Set(Box::default()), proto) +} + +fn weak_map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_map_proto; + construct(interp, args, constructing, "WeakMap", Class::WeakMap(Box::default()), proto) +} + +fn weak_set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_set_proto; + construct(interp, args, constructing, "WeakSet", Class::WeakSet(Box::default()), proto) +} + +// ---- Map and Set ---- + +/// The Map (or with `set`, the Set) a method was called on. +fn this_coll(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::Map(_), false) | (Class::Set(_), true)) + { + return Ok(*o); + } + let name = if set { "Set" } else { "Map" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn coll(interp: &Interp, o: ObjId) -> JsResult<&Coll> { + match &interp.object(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +fn coll_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut Coll> { + match &mut interp.object_mut(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +/// Adds or replaces the entry of `k`, reserving the heap for a new one first. +fn coll_put(interp: &mut Interp, o: ObjId, k: Value, v: Value) -> JsResult<()> { + let ck = coll_key(interp, &k)?; + if !coll(interp, o)?.has(&ck) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(COLL_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(COLL_ENTRY_BYTES); + } + coll_mut(interp, o)?.set(ck, stored_key(k), v); + Ok(()) +} + +fn map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "get")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(coll(interp, o)?.get(&k).cloned().unwrap_or(Value::Undefined)) +} + +fn map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "set")?; + coll_put(interp, o, arg(args, 0), arg(args, 1))?; + Ok(this) +} + +fn has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "has")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll(interp, o)?.has(&k))) +} + +fn delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "delete")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll_mut(interp, o)?.delete(&k))) +} + +fn clear(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "clear")?; + let slots = coll(interp, o)?.slots(); + // Clearing visits every position, and each takes a unit of fuel. + for _ in 0..slots { + interp.use_fuel()?; + } + coll_mut(interp, o)?.clear(); + Ok(Value::Undefined) +} + +fn size(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "size")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(coll(interp, o)?.len() as f64)) +} + +fn map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, false) +} + +fn map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, false) +} + +fn map_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, false) +} + +fn map_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, false) +} + +fn set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, true, "add")?; + coll_put(interp, o, arg(args, 0), Value::Undefined)?; + Ok(this) +} + +fn set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, true) +} + +fn set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, true) +} + +fn set_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, true) +} + +fn set_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, true) +} + +/// `forEach` (sections 23.1.3.5 and 23.2.3.6): calls `f` with each entry's value, its key (for a +/// Set, the value again) and the collection, in order, visiting entries added while it runs. The +/// position is kept in an iterator object, so a collection that removes holes moves it. +fn for_each(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "forEach")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let source = if set { IterSource::Set } else { IterSource::Map }; + let it = new_iter(interp, o, source, IterKind::Entries, None)?; + interp.rooted(&[Value::Object(it), f.clone(), this_arg.clone()], |interp| { + while let Some((k, v)) = advance(interp, it)? { + let v = if set { k.clone() } else { v }; + interp.call(&f, &this_arg, &[v, k, Value::Object(o)])?; + } + Ok(Value::Undefined) + }) +} + +fn map_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, false) +} + +fn set_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, true) +} + +// ---- iterators ---- + +/// A new iterator over `target`, with `proto` (by default the prototype for `source`). +pub(crate) fn new_iter(interp: &mut Interp, target: ObjId, source: IterSource, kind: IterKind, proto: Option) -> JsResult { + interp.rooted(&[Value::Object(target)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = proto.unwrap_or(match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto, + }); + let state = IterState { source, kind, target: Some(target), pos: 0 }; + let it = interp.heap.alloc_object(Object::new(Class::Iter(Box::new(state)), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + Ok(it) +} + +/// The next entry of a Map or Set iterator, or `None` when it has finished. Each position +/// passed takes a unit of fuel. +fn advance(interp: &mut Interp, it: ObjId) -> JsResult> { + loop { + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (Some(target), pos) = (state.target, state.pos) else { return Ok(None) }; + let c = coll(interp, target)?; + let found = (pos < c.slots()).then(|| c.entry(pos).cloned()); + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + match found { + None => { + state.target = None; + return Ok(None); + } + Some(entry) => { + state.pos = pos + 1; + if let Some(entry) = entry { + return Ok(Some(entry)); + } + } + } + } +} + +/// An iterator result object `{ value, done }` (section 7.4.7). +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * (PROP_BYTES + string_bytes(5))))?; + let o = interp.new_object(); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new array `[a, b]`. +pub(crate) fn pair(interp: &mut Interp, a: Value, b: Value) -> JsResult { + interp.rooted(&[a.clone(), b.clone()], |interp| { + let arr = new_array(interp, 0)?; + interp.rooted(&[Value::Object(arr)], |interp| { + create_at(interp, arr, 0.0, a.clone())?; + create_at(interp, arr, 1.0, b.clone())?; + Ok(Value::Object(arr)) + }) + }) +} + +/// The iterator a `next` method was called on, when it goes through `source`. +fn this_iter(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<(ObjId, IterKind)> { + if let Value::Object(o) = this + && let Some(Class::Iter(state)) = interp.heap.object(*o).map(|o| &o.class) + && state.source == source + { + return Ok((*o, state.kind)); + } + Err(interp.type_error(&format!("{name} Iterator.prototype.next was called on a value that is not a {name} Iterator"))) +} + +fn coll_next(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult { + let (it, kind) = this_iter(interp, this, source, name)?; + let Some((k, v)) = advance(interp, it)? else { return iter_result(interp, Value::Undefined, true) }; + let value = match (kind, source) { + (IterKind::Keys, _) | (IterKind::Values, IterSource::Set) => k, + (IterKind::Values, _) => v, + (IterKind::Entries, IterSource::Set) => pair(interp, k.clone(), k)?, + (IterKind::Entries, _) => pair(interp, k, v)?, + }; + iter_result(interp, value, false) +} + +fn map_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Map, "Map") +} + +fn set_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Set, "Set") +} + +/// `%ArrayIteratorPrototype%.next` (section 22.1.5.2.1) for the iterators of typed arrays. +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (it, kind) = this_iter(interp, &this, IterSource::Array, "Array")?; + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (target, pos) = (state.target, state.pos); + let element = match target { + Some(t) => match &interp.object(t)?.class { + Class::TypedArray(view) => super::binary::element(interp, view, pos as f64), + _ => None, + }, + None => None, + }; + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let Some(element) = element else { + state.target = None; + return iter_result(interp, Value::Undefined, true); + }; + state.pos = pos + 1; + #[allow(clippy::cast_precision_loss)] + let index = Value::Number(pos as f64); + let value = match kind { + IterKind::Keys => index, + IterKind::Values => Value::Number(element), + IterKind::Entries => pair(interp, index, Value::Number(element))?, + }; + iter_result(interp, value, false) +} + +fn iter_method(interp: &mut Interp, this: &Value, set: bool, kind: IterKind, name: &str) -> JsResult { + let o = this_coll(interp, this, set, name)?; + let source = if set { IterSource::Set } else { IterSource::Map }; + new_iter(interp, o, source, kind, None).map(Value::Object) +} + +fn map_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Keys, "keys") +} + +fn map_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Values, "values") +} + +fn map_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Entries, "entries") +} + +fn set_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Values, "values") +} + +fn set_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Entries, "entries") +} + +// ---- WeakMap and WeakSet ---- + +fn this_weak(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::WeakMap(_), false) | (Class::WeakSet(_), true)) + { + return Ok(*o); + } + let name = if set { "WeakSet" } else { "WeakMap" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn weak(interp: &Interp, o: ObjId) -> JsResult<&WeakColl> { + match &interp.object(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +fn weak_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut WeakColl> { + match &mut interp.object_mut(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +/// Adds or replaces the entry of the object `k`; a key that is not an object is a `TypeError`. +fn weak_put(interp: &mut Interp, o: ObjId, k: &Value, v: Value, set: bool) -> JsResult<()> { + let Value::Object(key_obj) = k else { + let what = if set { "a WeakSet value" } else { "a WeakMap key" }; + return Err(interp.type_error(&format!("{what} must be an object"))); + }; + if !weak(interp, o)?.entries.contains_key(&key_obj.0) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(WEAK_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(WEAK_ENTRY_BYTES); + } + weak_mut(interp, o)?.entries.insert(key_obj.0, v); + Ok(()) +} + +fn weak_map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "get")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Undefined) }; + Ok(weak(interp, o)?.entries.get(&k.0).cloned().unwrap_or(Value::Undefined)) +} + +fn weak_map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "set")?; + weak_put(interp, o, &arg(args, 0), arg(args, 1), false)?; + Ok(this) +} + +fn weak_has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "has")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak(interp, o)?.entries.contains_key(&k.0))) +} + +fn weak_delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "delete")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak_mut(interp, o)?.entries.remove(&k.0).is_some())) +} + +fn weak_map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, false) +} + +fn weak_map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, false) +} + +fn weak_set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, true, "add")?; + weak_put(interp, o, &arg(args, 0), Value::Undefined, true)?; + Ok(this) +} + +fn weak_set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, true) +} + +fn weak_set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, true) +} diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs new file mode 100644 index 0000000000..cbc35d3929 --- /dev/null +++ b/crates/js/src/collections_tests.rs @@ -0,0 +1,510 @@ +use crate::heap::{Class, key}; +use crate::value::Value; +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015() -> Options { + Options { es2015: true, ..Options::default() } +} + +fn realm() -> Realm { + Realm::with_options(es2015(), Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match realm().run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +fn limit(limits: &Limits, src: &str) -> LimitKind { + match Realm::with_options(es2015(), limits.clone()).run(src) { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => k, + other => panic!("{src}: {other:?}"), + } +} + +/// The object a global variable holds. +fn global_object(realm: &mut Realm, name: &str) -> crate::heap::ObjId { + let interp = realm.interp(); + let global = interp.global; + match interp.heap.object(global).and_then(|g| g.props.get(&key(name))) { + Some(crate::heap::Prop::Data { value: Value::Object(o), .. }) => *o, + _ => panic!("{name} is not an object"), + } +} + +// ---- realms ---- + +#[test] +fn realms_without_the_option_keep_the_es5_globals() { + for options in [Options::default(), Options { e4x: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let names = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array \ + Uint32Array Float32Array Float64Array"; + for name in names.split_whitespace() { + assert_eq!(realm.run(&format!("typeof {name}")).unwrap(), JsValue::String("undefined".into()), "{name}"); + } + } + truth("typeof Map === 'function' && typeof Float64Array === 'function' && typeof TypedArray === 'undefined'"); +} + +// ---- Map and Set ---- + +#[test] +fn keys_compare_with_same_value_zero() { + truth("var m = new Map(); m.set(NaN, 1); m.get(NaN) === 1 && m.has(0 / 0) && m.size === 1"); + truth("var m = new Map(); m.set(-0, 'a'); m.get(0) === 'a' && m.has(-0) && 1 / m.keys().next().value === Infinity"); + truth("var s = new Set([0, -0, NaN, NaN]); s.size === 2 && 1 / s.values().next().value === Infinity"); + truth("var m = new Map(); m.set('1', 'string').set(1, 'number'); m.size === 2 && m.get('1') === 'string' && m.get(1) === 'number'"); + truth("var a = {}, b = {}; var m = new Map([[a, 1], [b, 2]]); m.get(a) === 1 && m.get(b) === 2 && m.get({}) === undefined"); + truth("var m = new Map(); m.set('ab' + 'c', 1); m.get('abc') === 1"); +} + +#[test] +fn symbol_keys_compare_by_identity() { + truth( + "var a = Symbol('k'), b = Symbol('k'); var m = new Map([[a, 1], [b, 2]]); \ + m.size === 2 && m.get(a) === 1 && m.get(b) === 2 && m.get(Symbol('k')) === undefined && m.keys().next().value === a", + ); + truth("var r = Symbol.for('k'); var s = new Set([r, Symbol.for('k')]); s.size === 1 && s.has(r) && s.delete(r) && s.size === 0"); +} + +#[test] +fn entries_keep_the_order_they_were_added_in() { + assert_eq!( + string( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); m.set('a', 9); m.delete('b'); m.set('b', 4); \ + var out = []; m.forEach(function (v, k, map) { out.push(k + v + (map === m)); }); out.join()" + ), + "a9true,c3true,b4true" + ); + assert_eq!(string("var s = new Set(['x', 'y']); var out = []; s.forEach(function (v, k) { out.push(v + k); }); out.join()"), "xx,yy"); +} + +#[test] +fn for_each_skips_deleted_entries_and_visits_added_ones() { + assert_eq!( + string( + "var m = new Map([[1, 'a'], [2, 'b'], [3, 'c']]); var out = []; \ + m.forEach(function (v, k) { out.push(v); if (k === 1) { m.delete(2); m.set(4, 'd'); } }); out.join()" + ), + "a,c,d" + ); + assert_eq!( + string("var s = new Set([1, 2]); var out = []; s.forEach(function (v) { out.push(v); if (v < 4) s.add(v + 2); }); out.join()"), + "1,2,3,4,5" + ); + assert_eq!(string("var s = new Set([1, 2, 3]); var out = []; s.forEach(function (v) { out.push(v); s.clear(); }); out.join()"), "1"); +} + +#[test] +fn iterators_step_through_live_entries() { + truth( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); var it = m.entries(); var first = it.next(); m.delete('b'); m.set('d', 4); \ + var second = it.next(), third = it.next(), last = it.next(); \ + first.value.join() === 'a,1' && !first.done && second.value.join() === 'c,3' && third.value.join() === 'd,4' && \ + last.done && last.value === undefined && it.next().done", + ); + truth("var s = new Set(['p']); var e = s.entries().next().value; e[0] === 'p' && e[1] === 'p' && s.keys === s.values"); + truth("Object.prototype.toString.call(new Map().keys()) === '[object Map Iterator]'"); + throws("var it = new Map().keys(); it.next.call(new Set().values());", "TypeError"); +} + +#[test] +fn constructors_read_arrays_strings_and_array_likes() { + truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); + truth("new Set('ab\u{1F600}b').size === 3"); + truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + truth("new Map(null).size === 0 && new Set(undefined).size === 0"); + truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); + throws("Map()", "TypeError"); + throws("Set([])", "TypeError"); + throws("new Map([1])", "TypeError"); + throws("new Set(5)", "TypeError"); + throws("new Map({})", "TypeError"); + throws("new WeakSet({})", "TypeError"); + truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); + // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). + truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); + throws("Map.prototype.get.call({}, 1)", "TypeError"); + throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); + // The constructor adds through the prototype's method, as section 23.1.1.1 says. + truth( + "var calls = 0; var set = Map.prototype.set; Map.prototype.set = function (k, v) { calls++; return set.call(this, k, v); }; \ + new Map([[1, 1], [2, 2]]); Map.prototype.set = set; calls === 2", + ); + truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); +} + +// ---- WeakMap and WeakSet ---- + +#[test] +fn weak_collections_take_object_keys_only() { + truth("var k = {}; var w = new WeakMap([[k, 1]]); w.get(k) === 1 && w.has(k) && w.delete(k) && !w.has(k)"); + truth("var w = new WeakMap(); w.get(1) === undefined && !w.has('a') && !w.delete(null)"); + truth("var s = new WeakSet(); var o = {}; s.add(o) === s && s.has(o) && !s.has(1) && !s.delete(1)"); + throws("new WeakMap().set(1, 2)", "TypeError"); + throws("new WeakSet().add('x')", "TypeError"); + throws("new WeakMap([[1, 2]])", "TypeError"); + truth("new WeakMap().size === undefined && typeof WeakMap.prototype.forEach === 'undefined'"); +} + +#[test] +fn a_weak_map_entry_does_not_keep_its_key_alive() { + let mut realm = realm(); + realm + .run( + "var wm = new WeakMap(), ws = new WeakSet(), kept = {}; + (function () { for (var i = 0; i < 50; i++) { var k = {}; wm.set(k, {back: k}); ws.add(k); } })(); + wm.set(kept, {back: kept}); ws.add(kept);", + ) + .unwrap(); + let wm = global_object(&mut realm, "wm"); + let ws = global_object(&mut realm, "ws"); + let before = realm.interp().heap.live_cells(); + realm.interp().collect_garbage(); + let after = realm.interp().heap.live_cells(); + let count = |realm: &mut Realm, o| match realm.interp().heap.object(o).map(|o| &o.class) { + Some(Class::WeakMap(w) | Class::WeakSet(w)) => w.entries.len(), + _ => panic!("not a weak collection"), + }; + assert_eq!(count(&mut realm, wm), 1); + assert_eq!(count(&mut realm, ws), 1); + // Each dropped key and its value were freed. + assert!(before - after >= 100, "{before} -> {after}"); + assert_eq!(realm.run("wm.get(kept).back === kept && ws.has(kept)").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_weak_map_value_reachable_through_another_key_is_kept() { + let mut realm = realm(); + realm.run("var wm = new WeakMap(), a = {}; (function () { var b = {}; wm.set(a, b); wm.set(b, {n: 7}); })();").unwrap(); + realm.interp().collect_garbage(); + assert_eq!(realm.run("wm.get(wm.get(a)).n").unwrap(), JsValue::Number(7.0)); +} + +#[test] +fn weak_maps_of_dropped_keys_stay_within_the_heap() { + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(es2015(), limits); + let r = realm.run("var wm = new WeakMap(); for (var i = 0; i < 100000; i++) wm.set({}, i); 'done'"); + assert_eq!(r.unwrap(), JsValue::String("done".into())); + assert!(realm.interp().heap.collections > 0); +} + +#[test] +fn collections_of_millions_end_at_the_limits() { + let heap = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); + assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); + let fuel = Limits { fuel: 100_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; + assert_eq!(limit(&fuel, m), LimitKind::Fuel); +} + +#[test] +fn a_collection_removes_holes_and_moves_live_iterators() { + let mut realm = realm(); + realm + .run( + "var m = new Map(); for (var i = 0; i < 100; i++) m.set(i, i * 2); + var it = m.values(); it.next(); it.next(); + for (var j = 0; j < 90; j++) m.delete(j);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => assert_eq!((c.len(), c.slots()), (10, 10)), + _ => panic!("not a Map"), + } + let rest = realm.run("var out = []; for (var r = it.next(); !r.done; r = it.next()) out.push(r.value); out.join()").unwrap(); + assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); +} + +#[test] +fn a_collection_releases_the_storage_of_removed_entries() { + let mut realm = realm(); + realm + .run( + "var m = new Map(), wm = new WeakMap(), kept = {}; + for (var i = 0; i < 1000; i++) m.set(i, i); + m.clear(); m.set('a', 1); + (function () { for (var i = 0; i < 1000; i++) wm.set({}, i); })(); + wm.set(kept, 1);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + let wm = global_object(&mut realm, "wm"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => { + let (entries, index) = c.capacity(); + assert_eq!(c.slots(), 1); + assert!(entries < 64 && index < 64, "{entries} {index}"); + } + _ => panic!("not a Map"), + } + match realm.interp().heap.object(wm).map(|o| &o.class) { + Some(Class::WeakMap(w)) => assert!(w.entries.len() == 1 && w.entries.capacity() < 64, "{}", w.entries.capacity()), + _ => panic!("not a WeakMap"), + } + assert_eq!(realm.run("m.get('a') + wm.get(kept)").unwrap(), JsValue::Number(2.0)); +} + +// ---- ArrayBuffer ---- + +#[test] +fn array_buffers_are_zeroed_and_sliced() { + truth("var b = new ArrayBuffer(8); b.byteLength === 8 && new Uint8Array(b)[7] === 0"); + truth("var u = new Uint8Array([1, 2, 3, 4]); var s = u.buffer.slice(1, -1); s.byteLength === 2 && new Uint8Array(s).join() === '2,3'"); + truth("ArrayBuffer.isView(new DataView(new ArrayBuffer(1))) && ArrayBuffer.isView(new Int8Array(1)) && !ArrayBuffer.isView(new ArrayBuffer(1))"); + truth("new ArrayBuffer().byteLength === 0 && new ArrayBuffer(2.9).byteLength === 2"); + throws("ArrayBuffer(1)", "TypeError"); + throws("new ArrayBuffer(-1)", "RangeError"); +} + +#[test] +fn a_huge_array_buffer_is_refused_before_it_is_allocated() { + throws("new ArrayBuffer(1e15)", "RangeError"); + throws("new ArrayBuffer(Math.pow(2, 53))", "RangeError"); + throws("new Float64Array(Math.pow(2, 40))", "RangeError"); + truth("var caught; try { new Uint8Array(1e12); } catch (e) { caught = e instanceof RangeError; } caught"); + // Larger than the realm's heap limit: a catchable RangeError, not an allocation. + let mut small = Realm::with_options(es2015(), Limits { heap_bytes: 8 << 20, ..Limits::default() }); + assert_eq!(small.run("try { new ArrayBuffer(16 << 20); 'made' } catch (e) { e.name }").unwrap(), JsValue::String("RangeError".into())); + // Within the limit but not within what is left of it: the heap limit. + assert_eq!( + limit(&Limits { heap_bytes: 8 << 20, ..Limits::default() }, "var keep = []; for (;;) keep.push(new ArrayBuffer(1 << 20));"), + LimitKind::Heap + ); +} + +// ---- DataView ---- + +#[test] +fn data_views_read_and_write_both_byte_orders() { + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234); v.getUint8(0) === 0x12 && v.getUint8(1) === 0x34"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234, true); v.getUint8(0) === 0x34 && v.getUint16(0, true) === 0x1234"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt32(0, -2); v.getInt32(0) === -2 && v.getUint32(0) === 4294967294"); + truth("var v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, Math.PI); v.getFloat64(0) === Math.PI && v.getUint8(0) === 0x40"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setFloat32(0, 1.5, true); v.getFloat32(0, true) === 1.5 && v.getUint8(3) === 0x3f"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt8(0, 200); v.getInt8(0) === -56 && v.getUint8(0) === 200"); + truth("var b = new ArrayBuffer(8); var v = new DataView(b, 2, 4); v.byteOffset === 2 && v.byteLength === 4 && v.buffer === b"); + throws("new DataView(new ArrayBuffer(4)).getUint32(1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4)).getInt8(-1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 5)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 2, 3)", "RangeError"); + throws("new DataView({})", "TypeError"); + throws("DataView(new ArrayBuffer(1))", "TypeError"); +} + +// ---- typed arrays ---- + +#[test] +fn uint8_clamped_rounds_half_to_even() { + assert_eq!(string("new Uint8ClampedArray([300, -5, 1.5, 2.5, 0.5, NaN, 254.5, 254.6, Infinity]).join()"), "255,0,2,2,0,0,254,255,255"); + assert_eq!(string("var u = new Uint8ClampedArray(1); u[0] = 3.5; u[0] + ',' + new Uint8Array([300])[0]"), "4,44"); +} + +#[test] +fn element_types_convert_their_values() { + assert_eq!(string("new Int8Array([127, 128, -129, 1.9]).join()"), "127,-128,127,1"); + assert_eq!(string("new Uint16Array([-1, 65536]).join()"), "65535,0"); + assert_eq!(string("new Int32Array([4294967295]).join()"), "-1"); + assert_eq!(string("new Uint32Array([-1]).join()"), "4294967295"); + assert_eq!(string("new Float32Array([0.1])[0].toFixed(8)"), "0.10000000"); + assert_eq!(string("new Float64Array([0.1, NaN]).join()"), "0.1,NaN"); + truth("Int16Array.BYTES_PER_ELEMENT === 2 && new Float64Array(1).BYTES_PER_ELEMENT === 8"); + truth("Object.prototype.toString.call(new Uint8Array(1)) === '[object Uint8Array]'"); +} + +#[test] +fn views_share_their_buffer_little_endian() { + truth("var b = new ArrayBuffer(8); var u8 = new Uint8Array(b), u32 = new Uint32Array(b); u32[0] = 0x01020304; u8[0] === 4 && u8[3] === 1"); + truth("var a = new Uint8Array([1, 2, 3, 4]); var s = a.subarray(1, 3); s[0] = 9; a[1] === 9 && s.length === 2 && s.byteOffset === 1"); + truth("var b = new ArrayBuffer(8); var a = new Int16Array(b, 2, 2); a.length === 2 && a.byteOffset === 2 && a.byteLength === 4"); + throws("new Int32Array(new ArrayBuffer(8), 2)", "RangeError"); + throws("new Int32Array(new ArrayBuffer(6))", "RangeError"); + throws("new Int16Array(new ArrayBuffer(8), 4, 4)", "RangeError"); +} + +#[test] +fn numeric_names_are_elements_or_nothing() { + truth("var a = new Int8Array(2); a[5] = 1; a[5] === undefined && !('5' in a) && Object.keys(a).join() === '0,1'"); + truth( + "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", + ); + truth("Int8Array.prototype[3] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[3]; r"); + truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); + // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. + truth( + "var n = 0; var a = new Int8Array(1); a[5] = {valueOf: function () { n++; return 1; }}; a['-0'] = {valueOf: function () { n++; }}; n === 2", + ); + truth("var a = new Int8Array([200]); a[0] === -56 && delete a[1] && !delete a[0]"); + throws("'use strict'; var a = new Int8Array(1); delete a[0];", "TypeError"); + // An out-of-range write is ignored without an error in strict mode too, as later editions define [[Set]]. + truth("'use strict'; var a = new Uint8Array(1); a[2] = 7; a['-1'] = 7; a[0.5] = 7; a.length === 1 && a[2] === undefined"); + truth("var d = Object.getOwnPropertyDescriptor(new Uint8Array([7]), '0'); d.value === 7 && d.writable && d.enumerable && d.configurable"); + truth("var a = new Uint8Array(1); Object.defineProperty(a, '0', {value: 5}); a[0] === 5"); + throws("Object.defineProperty(new Uint8Array(1), '0', {value: 5, configurable: false})", "TypeError"); + throws("Object.defineProperty(new Uint8Array(1), '3', {value: 5})", "TypeError"); + throws("Object.freeze(new Uint8Array(1))", "TypeError"); + truth("var keys = []; for (var k in new Uint8Array(3)) keys.push(k); keys.join() === '0,1,2'"); + truth("JSON.stringify(new Uint8Array([1, 2])) === '{\"0\":1,\"1\":2}'"); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_typed_array() { + truth("Array.prototype.join.call(new Uint8Array(5000)).length === 9999"); + truth("var a = new Uint8Array(10000); a[9999] = 1; Array.prototype.indexOf.call(a, 1) === 9999"); + // The element count, not a `length` property defined on the array, bounds the methods. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 0}); var n = 0; \ + a.forEach(function () { n++; }); n === 3 && a.join() === '1,2,3' && a.every(function (v) { return v > 0; }) && !a.every(function (v) { return v > 1; })", + ); + // A generic array method called on the typed array reads its `length` property. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 1}); \ + Array.prototype.join.call(a) === '1' && a.join() === '1,2,3' && Array.prototype.join.call(new Uint8Array([4, 5])) === '4,5'", + ); +} + +#[test] +fn typed_array_methods() { + assert_eq!(string("new Float64Array([3, NaN, -0, 0, -1, 2]).sort().join()"), "-1,0,0,2,3,NaN"); + truth("var a = new Float64Array([0, -0]).sort(); 1 / a[0] === -Infinity && 1 / a[1] === Infinity"); + assert_eq!(string("new Int8Array([1, 2, 3]).sort(function (a, b) { return b - a; }).join()"), "3,2,1"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).map(function (v) { return v * 100; }).join()"), "100,-56,44,-112"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).filter(function (v) { return v % 2; }).join()"), "1,3"); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(0, 3), 2); a.join()"), "1,2,1,2,3"); + assert_eq!(string("var a = new Uint8Array(4); a.set([7, '8'], 1); a.join()"), "0,7,8,0"); + throws("new Uint8Array(2).set([1, 2, 3])", "RangeError"); + throws("new Uint8Array(2).set([1], -1)", "RangeError"); + assert_eq!(string("new Uint8Array([1, 2, 3, 4, 5]).copyWithin(0, 3).join()"), "4,5,3,4,5"); + assert_eq!(string("new Uint8Array(4).fill(7, 1, -1).join()"), "0,7,7,0"); + assert_eq!(string("new Int8Array([5, 6, 7]).slice(-2).join()"), "6,7"); + truth("var a = new Int8Array([5, 6, 7]); a.find(function (v) { return v > 5; }) === 6 && a.findIndex(function (v) { return v > 9; }) === -1"); + truth("new Int8Array([1, 2, 1]).indexOf(1, 1) === 2 && new Int8Array([1, 2, 1]).lastIndexOf(2) === 1"); + truth("new Int8Array([1, 2, 3]).reduce(function (s, v) { return s + v; }) === 6 && new Int8Array([1, 2]).reverse().join() === '2,1'"); + truth( + "var it = new Int8Array([4, 5]).entries(); var e = it.next().value; e[0] === 0 && e[1] === 4 && it.next().value[1] === 5 && it.next().done", + ); + truth("new Int8Array([9]).keys().next().value === 0 && new Int8Array([9]).values().next().value === 9"); + truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); + truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); + truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + // A typed array calls each element's toLocaleString on the number (section 22.2.3.27); an array + // calls it on the element's object (section 15.4.4.3). + assert_eq!( + string( + "Number.prototype.toLocaleString = function () { 'use strict'; return typeof this; }; new Uint8Array([7, 8]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number,number;object" + ); + // A getter for the method gets the number as `this` too (Invoke, section 7.3.18). + assert_eq!( + string( + "Object.defineProperty(Number.prototype, 'toLocaleString', {get: function () { 'use strict'; var t = typeof this; \ + return function () { return t; }; }}); new Uint8Array([7]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number;object" + ); + truth( + "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", + ); + throws("Object.getPrototypeOf(Int8Array)()", "TypeError"); + throws("Int8Array(1)", "TypeError"); + throws("Object.getPrototypeOf(Int8Array.prototype).fill.call([1], 0)", "TypeError"); + throws("Int8Array.from.call(Object, [1])", "TypeError"); + throws("Int8Array.from.call({}, [1])", "TypeError"); + // The source's length is read before the constructor is checked to be a typed array's. + throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + // A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2). + throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError"); + // A constructor that is not a typed array's is refused (AllocateTypedArray, section 22.2.1.2.1), + // a function that returns a typed array and a bound typed array constructor included. + throws("Int8Array.from.call(function () { return new Int8Array(2); }, [1, 2])", "TypeError"); + throws("Int8Array.of.call(Int8Array.bind(null), 1)", "TypeError"); + truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); + // A copy to the same element type keeps every bit, a signaling NaN's included. + truth( + "var f = new Float32Array(2); new DataView(f.buffer).setUint32(4, 0x7f800001, true); \ + function bits(t) { return new DataView(t.buffer, t.byteOffset).getUint32(4, true); } \ + var g = new Float32Array(3); g.set(f, 1); var h = new Float32Array(2); h.set(f); \ + bits(f.slice()) === 0x7f800001 && bits(new Float32Array(f)) === 0x7f800001 && bits(h) === 0x7f800001 && \ + new DataView(g.buffer).getUint32(8, true) === 0x7f800001", + ); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); + assert_eq!( + string("var b = new ArrayBuffer(4); var a = new Int8Array(b); a.set([1, 2]); new Uint16Array(b).set(a.subarray(0, 2)); a.join()"), + "1,0,2,0" + ); + assert_eq!(string("var a = new Int8Array(3); a.set(new Uint8Array([200, 1]), 1); a.join()"), "0,-56,1"); +} + +#[test] +fn derived_buffers_and_typed_arrays_read_the_constructor_first() { + // SpeciesConstructor (section 7.3.20) reads `constructor` before the result is made, and + // before filter's callback runs. + for call in ["a.slice()", "a.subarray(0)", "a.map(function (v) { return v; })", "a.filter(function () { n++; })", "a.buffer.slice(0)"] { + let getter = format!( + "var n = 0; var a = new Int8Array([1, 2]); var g = {{get: function () {{ throw new RangeError('c'); }}}}; \ + Object.defineProperty(a, 'constructor', g); Object.defineProperty(a.buffer, 'constructor', g); {call}" + ); + throws(&getter, "RangeError"); + throws(&format!("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; a.buffer.constructor = null; {call}"), "TypeError"); + } + truth("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; try { a.filter(function () { n++; }); } catch (e) {} n === 0"); + truth( + "var a = new Int8Array([1, 2]); a.constructor = undefined; a.buffer.constructor = undefined; a.slice().join() === '1,2' && a.subarray(1)[0] === 2 && a.buffer.slice(1).byteLength === 1", + ); + truth("var a = new Int8Array([1, 2]); a.constructor = Array; a.map(function (v) { return v; }) instanceof Int8Array"); +} + +#[test] +fn typed_array_work_takes_fuel() { + let fuel = Limits { fuel: 50_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).fill(1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).copyWithin(0, 1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).slice()"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); + // A sort of 2^16 equal elements makes 2^19 comparisons, and reading and writing back its + // elements takes 2^17 units more. + let sort = "new Uint8Array(1 << 16).sort(); 'sorted'"; + assert_eq!(limit(&Limits { fuel: 600_000, ..Limits::default() }, sort), LimitKind::Fuel); + let mut enough = Realm::with_options(es2015(), Limits { fuel: 700_000, ..Limits::default() }); + assert_eq!(enough.run(sort).unwrap(), JsValue::String("sorted".into())); +} + +#[test] +fn a_copy_between_buffers_holds_no_snapshot() { + let mut realm = Realm::with_options(es2015(), Limits { heap_bytes: 6 << 20, ..Limits::default() }); + let r = realm.run("var a = new Uint8Array(1 << 20), b = new Int8Array(1 << 20); a[5] = 200; b.set(a); b[5]"); + assert_eq!(r.unwrap(), JsValue::Number(-56.0)); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c4327572f9..fd32b00549 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -92,6 +92,19 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose +/// path is in its own slot. `None` for anything else, a `Folder` included. +pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { + let Some(c) = &i.files else { return Ok(None) }; + if i.object(id)?.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match slot(i, id, PATH)? { + Value::String(s) => Some(s.to_rust_string()), + _ => None, + }) +} + fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { if let Value::String(s) = &value { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index abfbb6c6ac..3ca55dcd0b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -280,6 +280,241 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. + Map(Box), + /// A `Set` (section 23.2): its values in the order they were added, each with `undefined`. + Set(Box), + /// A `WeakMap` (section 23.3): values keyed by object. An entry does not keep its key + /// reachable, and its value is reachable only while its key is. + WeakMap(Box), + /// A `WeakSet` (section 23.4): objects that it does not keep reachable. + WeakSet(Box), + /// An iterator over a Map, a Set or a typed array (sections 23.1.5, 23.2.5 and 22.1.5). + Iter(Box), + /// An `ArrayBuffer` (section 24.1) and its bytes, which never change length. + ArrayBuffer(Box<[u8]>), + /// A `DataView` (section 24.2): a range of a buffer's bytes. + DataView(Box), + /// A typed array (section 22.2): elements of one type in a range of a buffer's bytes. + TypedArray(Box), +} + +/// A Map or Set key compared with SameValueZero (section 7.2.10): `NaN` equals `NaN`, `-0` +/// equals `+0`, strings compare by their code units, and Symbols and objects by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) enum CollKey { + Undefined, + Null, + Bool(bool), + /// The bits of the number, with every `NaN` as one value and `-0` as `+0`. + Number(u64), + String(Rc<[u16]>), + Symbol(crate::symbol::Sym), + Object(u32), +} + +impl CollKey { + /// The key of a number. + pub(crate) fn number(n: f64) -> Self { + CollKey::Number(if n.is_nan() { + f64::NAN.to_bits() + } else if n == 0.0 { + 0 + } else { + n.to_bits() + }) + } +} + +/// The entries of a Map or a Set in the order they were added. Deleting an entry leaves a hole, +/// so the position an iterator or a `forEach` loop has reached stays valid; a collection removes +/// the holes of a collection with more holes than entries and moves its live iterators with them. +#[derive(Clone, Default)] +pub(crate) struct Coll { + entries: Vec>, + index: HashMap, +} + +impl Coll { + /// The number of entries. + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + /// The number of positions, holes included. + pub(crate) fn slots(&self) -> usize { + self.entries.len() + } + + pub(crate) fn get(&self, k: &CollKey) -> Option<&Value> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, v)| v) + } + + pub(crate) fn has(&self, k: &CollKey) -> bool { + self.index.contains_key(k) + } + + /// Sets the value under `k`, keeping its position when it is there already. Returns whether + /// a new entry was added. + pub(crate) fn set(&mut self, k: CollKey, key: Value, value: Value) -> bool { + if let Some(&i) = self.index.get(&k) + && let Some(Some((_, v))) = self.entries.get_mut(i) + { + *v = value; + return false; + } + self.index.insert(k, self.entries.len()); + self.entries.push(Some((key, value))); + true + } + + /// Deletes the entry under `k`; returns whether there was one. + pub(crate) fn delete(&mut self, k: &CollKey) -> bool { + let Some(i) = self.index.remove(k) else { return false }; + if let Some(slot) = self.entries.get_mut(i) { + *slot = None; + } + true + } + + /// Deletes every entry, leaving the positions in place. + pub(crate) fn clear(&mut self) { + self.index.clear(); + self.entries.iter_mut().for_each(|e| *e = None); + } + + /// The entry at position `i`, or `None` for a hole or a position past the end. + pub(crate) fn entry(&self, i: usize) -> Option<&(Value, Value)> { + self.entries.get(i)?.as_ref() + } + + fn values(&self) -> impl Iterator { + self.entries.iter().flatten().flat_map(|(k, v)| [k, v]) + } + + fn should_compact(&self) -> bool { + let holes = self.entries.len() - self.index.len(); + holes > 16 && holes > self.index.len() + } + + /// Removes the holes. Returns, for each old position and the position past the end, the new + /// position of the first entry at or after it. + fn compact(&mut self) -> Vec { + let mut moved = Vec::with_capacity(self.entries.len() + 1); + let mut live = 0usize; + for e in &self.entries { + moved.push(live); + live += usize::from(e.is_some()); + } + moved.push(live); + self.entries.retain(Option::is_some); + // The storage the holes held is released along with their charge. + self.entries.shrink_to_fit(); + self.index.shrink_to_fit(); + for slot in self.index.values_mut() { + *slot = moved.get(*slot).copied().unwrap_or(*slot); + } + moved + } + + /// The positions the entries and the index have room for, for tests. + #[cfg(test)] + pub(crate) fn capacity(&self) -> (usize, usize) { + (self.entries.capacity(), self.index.capacity()) + } +} + +/// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are +/// `undefined`. +#[derive(Clone, Default)] +pub(crate) struct WeakColl { + pub(crate) entries: HashMap, +} + +/// What an iterator object goes through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterSource { + Map, + Set, + /// A typed array, by index. + Array, +} + +/// What each step of an iterator gives: the key, the value or a `[key, value]` array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. `target` is `None` once the iterator has finished. +#[derive(Clone, Debug)] +pub(crate) struct IterState { + pub(crate) source: IterSource, + pub(crate) kind: IterKind, + pub(crate) target: Option, + pub(crate) pos: usize, +} + +/// The element type of a typed array (section 22.2, table 50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Elem { + Int8, + Uint8, + Uint8Clamped, + Int16, + Uint16, + Int32, + Uint32, + Float32, + Float64, +} + +impl Elem { + pub(crate) const ALL: [Elem; 9] = + [Elem::Int8, Elem::Uint8, Elem::Uint8Clamped, Elem::Int16, Elem::Uint16, Elem::Int32, Elem::Uint32, Elem::Float32, Elem::Float64]; + + /// The bytes of one element. + pub(crate) fn size(self) -> usize { + match self { + Elem::Int8 | Elem::Uint8 | Elem::Uint8Clamped => 1, + Elem::Int16 | Elem::Uint16 => 2, + Elem::Int32 | Elem::Uint32 | Elem::Float32 => 4, + Elem::Float64 => 8, + } + } + + /// The name of the constructor. + pub(crate) fn name(self) -> &'static str { + match self { + Elem::Int8 => "Int8Array", + Elem::Uint8 => "Uint8Array", + Elem::Uint8Clamped => "Uint8ClampedArray", + Elem::Int16 => "Int16Array", + Elem::Uint16 => "Uint16Array", + Elem::Int32 => "Int32Array", + Elem::Uint32 => "Uint32Array", + Elem::Float32 => "Float32Array", + Elem::Float64 => "Float64Array", + } + } + + /// The position of the type in [`Elem::ALL`]. + pub(crate) fn index(self) -> usize { + Elem::ALL.iter().position(|e| *e == self).unwrap_or(0) + } +} + +/// A typed array or a `DataView`: `length` elements of `elem` (bytes, for a `DataView`) starting +/// `offset` bytes into `buffer`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct View { + pub(crate) buffer: ObjId, + pub(crate) offset: usize, + pub(crate) length: usize, + pub(crate) elem: Elem, } /// What an XML value is. @@ -364,6 +599,18 @@ impl Class { Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", Class::UnitValue(_) => "UnitValue", + Class::Map(_) => "Map", + Class::Set(_) => "Set", + Class::WeakMap(_) => "WeakMap", + Class::WeakSet(_) => "WeakSet", + Class::Iter(state) => match state.source { + IterSource::Map => "Map Iterator", + IterSource::Set => "Set Iterator", + IterSource::Array => "Array Iterator", + }, + Class::ArrayBuffer(_) => "ArrayBuffer", + Class::DataView(_) => "DataView", + Class::TypedArray(view) => view.elem.name(), } } } @@ -465,6 +712,12 @@ pub(crate) const SYMBOL_BYTES: usize = 48; pub(crate) const UNIT_VALUE_BYTES: usize = 32; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; +/// The estimated bytes of a Map or Set position, with its entry in the hash index. +pub(crate) const COLL_ENTRY_BYTES: usize = 96; +/// The estimated bytes of a WeakMap or WeakSet entry. +pub(crate) const WEAK_ENTRY_BYTES: usize = 64; +/// The estimated bytes of the state of an iterator, a typed array or a `DataView`. +pub(crate) const VIEW_BYTES: usize = 48; pub(crate) fn string_bytes(len: usize) -> usize { 32 + 2 * len @@ -560,11 +813,18 @@ impl Heap { /// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is /// the estimated size of what is left, strings reachable from it included. + /// + /// A WeakMap's entry marks its value only once its key is marked by another path, and the + /// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so + /// a value that refers back to its own key does not keep it alive. Values waiting for their + /// key are kept by key, so the marking stays linear in the number of entries. pub(crate) fn collect(&mut self, roots: &Roots<'_>) { let mut marks = vec![false; self.cells.len()]; let mut work: Vec = Vec::new(); let mut strings = StringSizes::default(); let mut live = 0usize; + let mut pending: HashMap> = HashMap::new(); + let mut weak: Vec = Vec::new(); for v in &roots.values { mark_value(v, &mut work, &mut strings); } @@ -579,21 +839,85 @@ impl Heap { continue; } *mark = true; + if let Some(values) = pending.remove(&i) { + for v in &values { + mark_value(v, &mut work, &mut strings); + } + } match self.cells.get(i as usize) { - Some(Cell::Object(o)) => live += trace_object(o, &mut work, &mut strings), + Some(Cell::Object(o)) => { + live += trace_object(o, &mut work, &mut strings); + match &o.class { + Class::WeakMap(w) => { + weak.push(i); + for (k, v) in &w.entries { + if marks.get(*k as usize).copied().unwrap_or(false) { + mark_value(v, &mut work, &mut strings); + } else if matches!(v, Value::Object(_) | Value::String(_)) { + pending.entry(*k).or_default().push(v.clone()); + } + } + } + Class::WeakSet(_) => weak.push(i), + _ => {} + } + } Some(Cell::Env(e)) => live += trace_env(e, &mut work, &mut strings), _ => {} } } + for i in weak { + if let Some(Cell::Object(o)) = self.cells.get_mut(i as usize) + && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class + { + w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + // Only the entries left are charged, and a table with far more room than entries + // releases the extra room. + if w.entries.capacity() > 2 * w.entries.len() + 16 { + w.entries.shrink_to_fit(); + } + live += WEAK_ENTRY_BYTES * w.entries.len(); + } + } for (i, (cell, marked)) in self.cells.iter_mut().zip(&marks).enumerate() { if !marked && !matches!(cell, Cell::Free) { *cell = Cell::Free; self.free.push(u32::try_from(i).unwrap_or(u32::MAX)); } } + live = live.saturating_sub(self.compact_collections()); self.bytes = live + strings.bytes; self.collections += 1; } + + /// Removes the holes of the Maps and Sets that have more holes than entries, and moves the + /// positions of their iterators with them. Returns the bytes the holes held. + fn compact_collections(&mut self) -> usize { + let mut moved: HashMap> = HashMap::new(); + let mut freed = 0usize; + for (i, cell) in self.cells.iter_mut().enumerate() { + if let Cell::Object(o) = cell + && let Class::Map(c) | Class::Set(c) = &mut o.class + && c.should_compact() + { + freed += COLL_ENTRY_BYTES * (c.slots() - c.len()); + moved.insert(u32::try_from(i).unwrap_or(u32::MAX), c.compact()); + } + } + if moved.is_empty() { + return 0; + } + for cell in &mut self.cells { + if let Cell::Object(o) = cell + && let Class::Iter(state) = &mut o.class + && state.source != IterSource::Array + && let Some(map) = state.target.and_then(|t| moved.get(&t.0)) + { + state.pos = map.get(state.pos).or(map.last()).copied().unwrap_or(0); + } + } + freed + } } /// What the collector starts from. @@ -830,6 +1154,23 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Map(c) | Class::Set(c) => { + for v in c.values() { + mark_value(v, work, strings); + } + extra = COLL_ENTRY_BYTES * c.slots(); + } + // Their entries are marked and counted by the collector's weak pass. + Class::WeakMap(_) | Class::WeakSet(_) => {} + Class::Iter(state) => { + work.extend(state.target.iter().map(|o| o.0)); + extra = VIEW_BYTES; + } + Class::ArrayBuffer(bytes) => extra = bytes.len(), + Class::DataView(view) | Class::TypedArray(view) => { + work.push(view.buffer.0); + extra = VIEW_BYTES; + } Class::Xmp(meta) => extra = meta.heap_bytes(), Class::XmpFile(fields) => { for (name, value) in fields.iter() { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 81d8411530..ae61b15663 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -200,8 +200,8 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, - /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object - /// that has [`crate::HOST_REF_KEY`] is refused. + /// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under + /// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused. hosted: bool, } @@ -272,6 +272,12 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + if r.hosted + && let Some(path) = crate::file_classes::file_path(self, id)? + { + self.charge_reading(r, path.len().saturating_add(16))?; + return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))])); + } let shape = match &self.object(id)?.class { Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), @@ -338,7 +344,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 9d14718dee..4586c231b8 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -131,6 +131,19 @@ pub fn host_ref(class: &str, handle: &[f64]) -> Data { Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) } +/// The one key of the [`Data`] object that stands for a script's `File` in the arguments of a host +/// class's member ([`file_ref_path`]). A plain object a script made that carries it is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d`, an argument of a host class's member, stands for. +pub fn file_ref_path(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + /// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { let Data::Object(items) = d else { return None }; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index cd1f3e64b5..e3a4f5e411 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -136,6 +136,8 @@ pub(crate) struct Intrinsics { pub(crate) xml_list_proto: ObjId, pub(crate) namespace_proto: ObjId, pub(crate) qname_proto: ObjId, + /// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]). + pub(crate) es2015: crate::builtins::collections::Es2015, } impl Intrinsics { @@ -158,6 +160,7 @@ impl Intrinsics { xml_list_proto: o, namespace_proto: o, qname_proto: o, + es2015: crate::builtins::collections::Es2015::placeholder(), } } @@ -193,6 +196,7 @@ impl Intrinsics { self.qname_proto, ]; v.extend(self.error_protos); + v.extend(self.es2015.all()); v } } @@ -318,6 +322,9 @@ pub(crate) struct Interp { pub(crate) held_bytes: usize, /// Why installing the built-ins failed; a realm with this set runs no script. pub(crate) install_error: Option, + /// The typed array whose element count the next array method reads as its length, set while a + /// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read. + pub(crate) typed_length: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, /// `ExternalObject` and the XMP classes it loads, once a host has added them @@ -645,6 +652,7 @@ impl Interp { join_stack: Vec::new(), held_bytes: 0, install_error: None, + typed_length: None, files: None, xmp: None, host_classes: Vec::new(), @@ -1698,6 +1706,12 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + // A numeric name of a typed array is an element or nothing (section 9.4.5.1). + Class::TypedArray(view) => { + if let Some(n) = crate::builtins::binary::canonical_index(k) { + return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN })); + } + } _ => {} } Ok(o.props.get(k).cloned()) @@ -1711,6 +1725,10 @@ impl Interp { if let Some(p) = self.get_own_property(o, k)? { return Ok(Some(p)); } + // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). + if crate::builtins::binary::typed_key(self, o, k).is_some() { + return Ok(None); + } cur = self.object(o)?.proto; steps += 1; if steps > 1_000_000 { @@ -1831,6 +1849,9 @@ impl Interp { } self.define_ordinary(id, k, desc, throw) } + Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => { + crate::builtins::binary::define_element(self, id, &k, desc, throw) + } Class::Arguments(map) => { let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned(); if !self.define_ordinary(id, k.clone(), desc, false)? { @@ -1983,7 +2004,12 @@ impl Interp { /// list is checked first. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { let o = self.object(id)?; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; + // A typed array's indices come first, as a String object's do (section 9.4.5.6). + let string_len = match &o.class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + }; let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); @@ -2025,6 +2051,9 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) { + return crate::builtins::binary::set_element(self, id, n, &v); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -2109,6 +2138,18 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + // A typed array's element cannot be deleted, and a numeric name it has no element for + // is not a property it can hold (section 9.4.5.6 of later editions). + if crate::builtins::binary::typed_key(self, id, k).is_some() { + if self.get_own_property(id, k)?.is_none() { + return Ok(true); + } + if throw { + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array"))); + } + return Ok(false); + } match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -2855,8 +2896,12 @@ impl Interp { let mut cur = Some(id); while let Some(o) = cur { let obj = self.object(o)?; - let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None }; - let is_array = matches!(obj.class, Class::Array { .. }); + let string_len = match &obj.class { + Class::String(s) => Some(s.len()), + Class::TypedArray(view) => Some(view.length), + _ => None, + }; + let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_)); if let Some(len) = string_len { self.reserve_heap(index_keys_bytes(len))?; for i in 0..len { @@ -2866,7 +2911,6 @@ impl Interp { out.push(k); } } - seen.insert(key("length")); } if is_array { seen.insert(key("length")); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 911c56d5a0..e943552035 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -95,6 +95,18 @@ //! 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. +//! +//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins +//! (): `Map` and `Set` (sections 23.1 and 23.2), whose +//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting +//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the +//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine +//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with +//! a `next` method. Until the language has iterators, the collection constructors and +//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by +//! index. A typed array constructor reads an array or an object with a `length` the same way, and +//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] pub mod ast; @@ -139,7 +151,7 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{ @@ -170,8 +182,9 @@ pub struct Options { /// `??`. 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, 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 + /// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, + /// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` + /// and the typed arrays. 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. @@ -280,6 +293,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod collections_tests; +#[cfg(test)] mod es2015_object_tests; #[cfg(test)] mod es2015_tests; diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index a5047566a0..3558aa5eca 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -33,6 +33,12 @@ //! and from ECMAScript 2020 optional chains and `??`) without and with that option, and //! prints both counts; its failures with the option go to `es2015-failures.txt`. //! +//! A sixth test runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names (`Map`, `Set`, +//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in +//! realms with [`Options::es2015`], each test whose feature tags are all in +//! [`ES2015_COLLECTION_FEATURES`]; its failures go to `es2015-builtins-failures.txt`. It fails when +//! the interpreter panics. +//! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset //! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the @@ -629,6 +635,108 @@ fn run_text_builtins(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The directories under `test/built-ins/` that hold the tests of the ECMAScript 2015 collections +/// and binary data, which run in a realm with [`Options::es2015`]. +const ES2015_COLLECTION_BUILT_INS: &[&str] = &["Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "TypedArray", "TypedArrayConstructors"]; + +/// The names in [`MISSING_BUILTINS`] that a realm with [`Options::es2015`] provides. +const ES2015_BUILTINS: &str = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array"; + +/// The feature tags a test under [`ES2015_COLLECTION_BUILT_INS`] may have and still run: the built-ins +/// themselves and the stable typed array sort. A tag starting `DataView.prototype.` names one of +/// the `DataView` methods. Tests with any other tag (symbols, `Reflect`, classes, resizable or +/// detached buffers, `BigInt` and later additions) are counted as skipped. +const ES2015_COLLECTION_FEATURES: &[&str] = &[ + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "TypedArray", + "Int8Array", + "Uint8Array", + "Float64Array", + "stable-typedarray-sort", +]; + +#[test] +fn es2015_collections_and_binary_data_run() { + let Some(dir) = suite_dir() else { + println!("test262 ECMAScript 2015 built-ins: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names in realms with +/// [`Options::es2015`], prints each folder's counts and writes the failures to +/// `es2015-builtins-failures.txt` beside the suite. +fn run_es2015_built_ins(dir: &Path) { + let missing = missing_builtins(&[TEXT_BUILTINS, ES2015_BUILTINS]); + let mut report = String::new(); + let mut panicked = 0; + for name in ES2015_COLLECTION_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_es2015_tests(dir, &root, &missing); + println!("test262 built-ins/{name} in an ECMAScript 2015 realm: {}.", counts.summary()); + report.push_str(&format!("# built-ins/{name}\n{}\n", counts.failures)); + panicked += counts.panicked; + } + let path = dir.join("es2015-builtins-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 ECMAScript 2015 built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); +} + +/// Runs the tests under `root` whose feature tags are all in [`ES2015_COLLECTION_FEATURES`], as +/// [`run_tests`] runs the ES5 tests, each in a new realm with [`Options::es2015`]. +fn run_es2015_tests(dir: &Path, root: &Path, missing: &HashSet<&str>) -> RunCounts { + // 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 mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) || meta.flags.iter().any(|f| f == "module") { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let known = meta.features.iter().all(|f| ES2015_COLLECTION_FEATURES.contains(&f.as_str()) || f.starts_with("DataView.prototype.")); + if !known || meta.flags.iter().any(|f| f == "async") || 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_one(&script, negative_type.as_deref(), &Options { es2015: true, ..Options::default() })) { + 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")); + } + } + } + } + counts +} + /// Runs the tests under `root` that have no feature tag and are not module, asynchronous or /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f2444bc019..1c9f673200 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -612,6 +612,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -670,7 +682,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "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 column's place in that edge's dock, 0 at the window's edge, while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `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", "", "{}"), ( @@ -1256,7 +1268,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -2006,6 +2018,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), + ( + "ui.failedPlugins", + "Plug-ins That Didn't Load…", + "", + "{} Object › Plug-ins › Plug-ins That Didn't Load…: list the plug-in files that didn't load in this session, each by its file name with why (plugin.list's failed), at most 50 and a count of the others (dialog `pluginsFailed`); Retry All loads them again (plugin.retry) and the status bar says how many loaded, Close changes nothing → {pending: \"pluginsFailed\", failed: n}. Disabled, and an error, while no plug-in failed to load", + ), ( "plugin.cancelRuns", "Cancel Plug-in Run", diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index fc3b92eac2..d4447f3e0c 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -9,7 +9,8 @@ description = "VectorCraft PDF export and import" workspace = true [features] -# `vectorcraft_pdf::reads_of` and `imports_of` for other crates' tests (dev-dependencies only). +# `vectorcraft_pdf::reads_of`, `imports_of`, `function_evaluations_of`, `form_content_of` and their +# limits for other crates' tests (dev-dependencies only). read-count = [] [dependencies] diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index d378da1593..b0d6ac3adf 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -40,12 +40,12 @@ mod state; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; -#[cfg(any(test, feature = "read-count"))] -pub use entry::imports_of; pub use entry::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(test)] pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read}; +#[cfg(any(test, feature = "read-count"))] +pub use entry::{form_content_of, function_evaluations_of, imports_of}; pub(crate) use state::{closed_subpaths, round3}; diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 07197309b2..fbc9e1aef5 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -243,6 +243,34 @@ pub fn imports_of(bytes: &[u8]) -> usize { IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) } +/// The work the imports of each buffer took, by its address (tests): the function evaluations of +/// its function-based shadings, and the bytes of form content its pages' scans walked. +#[cfg(any(test, feature = "read-count"))] +static WORK: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// Adds `evaluations` and `form_content` to the work of the imports of `bytes` (tests). +#[cfg(any(test, feature = "read-count"))] +fn note_work(bytes: &[u8], evaluations: usize, form_content: usize) { + if let Ok(mut work) = WORK.lock() { + let (e, f) = work.entry(bytes.as_ptr() as usize).or_default(); + (*e, *f) = (e.saturating_add(evaluations), f.saturating_add(form_content)); + } +} + +/// How many function evaluations the function-based shadings of `bytes`, at its address, have +/// taken in its imports on any thread (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn function_evaluations_of(bytes: &[u8]) -> usize { + WORK.lock().ok().and_then(|w| w.get(&(bytes.as_ptr() as usize)).map(|w| w.0)).unwrap_or(0) +} + +/// How many bytes of form content the pages of `bytes`, at its address, have walked in its imports +/// on any thread, up to [`crate::import_scan::form_content_limit`] a page (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn form_content_of(bytes: &[u8]) -> usize { + WORK.lock().ok().and_then(|w| w.get(&(bytes.as_ptr() as usize)).map(|w| w.1)).unwrap_or(0) +} + /// The notes on the fonts the file draws with that aren't available: type in a font the file /// carries keeps its look until it is edited; the rest shows in the fallback font. fn warn_missing_fonts(b: &mut Builder, doc: &Document) { @@ -344,7 +372,12 @@ fn read_opened( b.page = ab; // The first id of this page's art. let first_id = b.next; - let mut scan = scan_page(page, &mut ocgs, all_on, &mut b.fonts, pdf.decode_limits().max_decoded_stream())?; + #[cfg(any(test, feature = "read-count"))] + crate::import_scan::FORM_CONTENT_WALKED.set(0); + let scan = scan_page(page, &mut ocgs, all_on, &mut b.fonts, pdf.decode_limits().max_decoded_stream()); + #[cfg(any(test, feature = "read-count"))] + note_work(bytes, 0, crate::import_scan::FORM_CONTENT_WALKED.take()); + let mut scan = scan?; // The walk's ink names pick between spaces of inks that look the same to the interpreter. A // page keeps them only when it uses such an ink and the interpreter draws as many paths // there as the walk counts. @@ -358,7 +391,12 @@ fn read_opened( merge_order(&mut order, &mut known, &marked); } b.begin_page(scan); - craft::pdf::interpret_page(page, &mut ctx, &mut b).map_err(|e| PdfError::Parse(e.to_string()))?; + let drawn = craft::pdf::interpret_page(page, &mut ctx, &mut b); + // The page's shadings take their evaluations while it is drawn: they count even when the + // import stops on this page or a later one. + #[cfg(any(test, feature = "read-count"))] + note_work(bytes, b.function_budget.take_spent(), 0); + drawn.map_err(|e| PdfError::Parse(e.to_string()))?; if incomplete.load(Ordering::Relaxed) { return Err(crate::import_scan::incomplete_content()); } diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 6b812224e2..1f62a7b380 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -1147,10 +1147,25 @@ fn embeds_glyphs(f: &Dict<'_>) -> bool { /// found are noted in `fonts` (their cache key → base font name, and whether the file carries its /// glyphs). pub(crate) fn scan_page(page: &Page<'_>, ocgs: &mut Ocgs, all_on: bool, fonts: &mut FontNames, max_form_bytes: usize) -> Result { - let scan = walk_page(page, ocgs, all_on, fonts, max_form_bytes).out; + let walked = walk_page(page, ocgs, all_on, fonts, max_form_bytes); + #[cfg(any(test, feature = "read-count"))] + FORM_CONTENT_WALKED.with(|n| n.set(n.get().saturating_add(walked.form_content))); + let scan = walked.out; if scan.cut { Err(incomplete_content()) } else { Ok(scan) } } +#[cfg(any(test, feature = "read-count"))] +thread_local! { + /// The bytes of form content [`scan_page`] walked on this thread (tests). + pub(crate) static FORM_CONTENT_WALKED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The bytes of form content a page's scan walks before it refuses the page (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn form_content_limit() -> usize { + MAX_FORM_CONTENT +} + pub(crate) fn walk_page<'w, 'p>( page: &Page<'p>, ocgs: &'w mut Ocgs, diff --git a/crates/pdf/src/import_shading.rs b/crates/pdf/src/import_shading.rs index bf2bbec832..544208ed0b 100644 --- a/crates/pdf/src/import_shading.rs +++ b/crates/pdf/src/import_shading.rs @@ -178,25 +178,48 @@ const AVERAGE_EVALUATIONS: usize = (FUNCTION_GRID + 1) * (FUNCTION_GRID + 1); #[cfg(test)] pub(crate) static EVALUATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// The function evaluations function-based shadings may take in one import (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn function_evaluation_limit() -> usize { + MAX_FUNCTION_EVALUATIONS +} + /// What is left of one import's function evaluations ([`MAX_FUNCTION_EVALUATIONS`]). -pub(crate) struct FunctionBudget(std::cell::Cell); +pub(crate) struct FunctionBudget { + left: std::cell::Cell, + /// The evaluations taken (tests). + #[cfg(any(test, feature = "read-count"))] + taken: std::cell::Cell, +} impl FunctionBudget { pub(crate) fn new() -> Self { - Self(std::cell::Cell::new(MAX_FUNCTION_EVALUATIONS)) + Self { + left: std::cell::Cell::new(MAX_FUNCTION_EVALUATIONS), + #[cfg(any(test, feature = "read-count"))] + taken: std::cell::Cell::new(0), + } } /// Take one evaluation, leaving at least `reserve`: `false` when there isn't one. fn take(&self, reserve: usize) -> bool { - let left = self.0.get(); + let left = self.left.get(); if left <= reserve { return false; } - self.0.set(left - 1); + self.left.set(left - 1); #[cfg(test)] EVALUATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + #[cfg(any(test, feature = "read-count"))] + self.taken.set(self.taken.get().saturating_add(1)); true } + + /// The evaluations taken from it since the last call (tests). + #[cfg(any(test, feature = "read-count"))] + pub(crate) fn take_spent(&self) -> usize { + self.taken.take() + } } /// What a function-based shading comes in as ([`function_paint`]). diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index e3bc2f504a..9b8579885b 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,12 +76,16 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use export::{check_page_sizes, export, export_with_report, page_areas}; pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; -#[cfg(any(test, feature = "read-count"))] -pub use import::imports_of; pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; +#[cfg(any(test, feature = "read-count"))] +pub use import::{form_content_of, function_evaluations_of, imports_of}; +#[cfg(any(test, feature = "read-count"))] +pub use import_scan::form_content_limit; +#[cfg(any(test, feature = "read-count"))] +pub use import_shading::function_evaluation_limit; pub use marks::{leaves_out_bleed, page_bleed, printer_marks}; pub use output::ActiveProfiles; #[cfg(any(test, feature = "read-count"))] diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 596e029e3a..0be8dce82f 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -957,6 +957,29 @@ fn function_based_shadings_share_one_budget_per_import() { assert!(r.warnings.iter().any(|w| w.contains("too many to read")), "{:?}", r.warnings); } +/// An import that stops on a later page still counts the evaluations the shadings of the pages +/// before it took, once each. +#[test] +fn an_import_that_stops_on_a_later_page_counts_its_function_evaluations() { + use std::sync::atomic::Ordering::Relaxed; + let _held = shadings(); + let resources = format!( + "/Pattern << /P0 << /PatternType 2 /Shading << /ShadingType 1 /ColorSpace /DeviceRGB /Domain [0 4 0 1] /Matrix [25 0 0 100 0 0] /Function {} 0 R >> >> >>", + first_extra(2) + ); + let function = stream("/FunctionType 4 /Domain [0 4 0 1] /Range [0 1 0 1 0 1]", STRIPES); + let shaded = PdfPage { resources, ..PdfPage::new(100.0, 100.0, "/Pattern cs /P0 scn 0 0 100 100 re f") }; + // The second page's content ends inside a string, so the import stops there. + let cut = PdfPage::new(100.0, 100.0, "0 0 5 5 re f (unterminated"); + let bytes = pdf_with(&[shaded, cut], &[&function], None); + crate::import_shading::EVALUATIONS.store(0, Relaxed); + let before = function_evaluations_of(&bytes); + assert!(import(&bytes).is_err()); + let used = crate::import_shading::EVALUATIONS.load(Relaxed); + assert!(used > 0, "the first page's shading is read"); + assert_eq!(function_evaluations_of(&bytes) - before, used); +} + /// A page drawing one small form over and over makes objects only up to the import's limit, then /// leaves the rest out with a warning, instead of taking memory for every drawing (#3569). #[test] diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index 1f478353fa..2107b5f7b5 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -503,7 +503,8 @@ fn run( tests::RUNS_STARTED.with(|n| n.set(n.get() + 1)); let output = plugin.run_limited(&input, ¶ms, &limits)?; if plugin.manifest().paint_output { - return Ok(Out::Pieces(Arc::new(painted::decode(&output, scope, rule)?))); + let looks = plugin.manifest().appearance_output.then(painted::effect_check); + return Ok(Out::Pieces(Arc::new(painted::decode_with(&output, scope, rule, looks)?))); } Ok(Out::Path(output_geometry(decode(&output)?))) } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 56b8357cf1..9e68d6b70c 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, WRITES_API}; +use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -512,6 +512,11 @@ pub struct Manifest { /// manifest has `"paintOutput": true`, the only value the key may hold. #[serde(default, rename = "paintOutput", skip_serializing_if = "std::ops::Not::not")] pub paint_output: bool, + /// A live effect at `api` 3 that declares `paintOutput` and whose pieces, and their fills and + /// strokes, may also carry opacity, a blending mode and effects ([`crate::painted`]): `true` + /// when the manifest has `"appearanceOutput": true`, the only value the key may hold. + #[serde(default, rename = "appearanceOutput", skip_serializing_if = "std::ops::Not::not")] + pub appearance_output: bool, /// The menu commands it adds, in menu order (a filter or a live effect only). #[serde(default, deserialize_with = "ordered_commands", skip_serializing_if = "Vec::is_empty")] pub commands: Vec, @@ -539,9 +544,14 @@ impl Manifest { /// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys /// the manifest doesn't declare are ignored, and `params` keep the order the text gives them. pub(crate) fn parse_text(text: &str) -> Result { - if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { + let value = serde_json::from_str::(text).ok(); + let not_true = |key: &str| value.as_ref().is_some_and(|v| v.get(key).is_some_and(|p| *p != Value::Bool(true))); + if not_true("paintOutput") { return Err(Error::Manifest("`paintOutput` may only be true".into())); } + if not_true("appearanceOutput") { + return Err(Error::Manifest("`appearanceOutput` may only be true".into())); + } let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; man.validate()?; man.read_places()?; @@ -567,6 +577,7 @@ impl Manifest { place: false, budget: Budget::Light, paint_output: false, + appearance_output: false, commands: Vec::new(), command_allowlist: Vec::new(), runtime: Runtime::Wasm, @@ -639,6 +650,9 @@ impl Manifest { 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())); } + if self.appearance_output && (!self.paint_output || self.api < APPEARANCE_API) { + return Err(Error::Manifest("`appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3".into())); + } self.validate_extensions()?; if self.place && self.kind != Kind::Importer { return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into())); @@ -1668,6 +1682,35 @@ mod tests { } } + /// A live effect at `api` 3 that declares `paintOutput` may also declare + /// `"appearanceOutput": true`, and only that value, with no permission beyond `doc.read` and `effect.render`; + /// without `paintOutput`, below `api` 3, on another kind, or with `false`, `null` or another + /// type, it is refused naming the key. Without the key, at `api` 3, the effect paints as at 2. + #[test] + fn manifest_accepts_api3_appearance_output_only_for_painted_effects() { + let m = Manifest::parse( + br#"{"id":"org.example.tone","name":"Tone","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"permissions":["doc.read","effect.render"]}"#, + ) + .unwrap(); + assert!(m.paint_output && m.appearance_output); + assert_eq!(serde_json::to_value(&m).unwrap()["appearanceOutput"], json!(true)); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true}"#).unwrap(); + assert!(plain.paint_output && !plain.appearance_output); + assert!(serde_json::to_value(&plain).unwrap().get("appearanceOutput").is_none()); + for bad in [ + r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":false}"#, + r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":null}"#, + r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":1}"#, + r#"{"id":"a","name":"x","kind":"effect","api":3,"appearanceOutput":true}"#, + r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"appearanceOutput":true}"#, + r#"{"id":"a","name":"x","kind":"filter","api":3,"appearanceOutput":true}"#, + r#"{"id":"a","name":"x","kind":"exporter","api":3,"extensions":["plt"],"appearanceOutput":true}"#, + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains("appearanceOutput"), "{bad}: {e}"); + } + } + #[test] fn commands_and_paint_output_may_both_be_declared_on_a_live_effect() { let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"commands":[{"id":"c","label":"C"}]}"#).unwrap(); diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 4b0a528703..1b8396ddb5 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -781,7 +781,7 @@ fn decode_stroke(v: &Value, at: &str) -> Result { /// An effect record from plug-in output: `{id, params?, visible?}`, in form only (the host says /// whether the effect exists and takes the parameters). `params` stays as given, so a record /// handed back unchanged equals the object's own. -fn decode_effect(v: &Value, at: &str) -> Result { +pub(crate) fn decode_effect(v: &Value, at: &str) -> Result { let e = v.as_object().ok_or_else(|| out_err(at, "an effect must be {\"id\", \"params\"?, \"visible\"?}"))?; let id = e.get("id").and_then(Value::as_str).filter(|id| (1..=MAX_EFFECT_ID).contains(&id.len()) && !id.chars().any(char::is_control)); let id = id.ok_or_else(|| out_err(at, format!("`id` must be an effect id of 1-{MAX_EFFECT_ID} bytes")))?; diff --git a/crates/plugins/src/painted.rs b/crates/plugins/src/painted.rs index e7ed51e225..3aab24ef16 100644 --- a/crates/plugins/src/painted.rs +++ b/crates/plugins/src/painted.rs @@ -6,14 +6,21 @@ //! A piece without `fills` (or `strokes`) keeps the ones it was given; an empty list paints none. //! An effect on a fill may return only `fills`, one on a stroke only `strokes`. //! +//! An effect that also declares `"appearanceOutput": true` (at `api` 3) may give a piece, and each +//! fill or stroke it returns, an `opacity` (0–1), a `blend` (a [`BlendMode`] by its identifier) and +//! `effects` ([`Look`]): built-in effects only, which the host checks ([`CheckEffect`]), at most +//! [`MAX_LOOK_EFFECTS`] in one list and [`MAX_RESULT_EFFECTS`] in one result. A fill that carries +//! them is `{"paint", "opacity"?, "blend"?, "effects"?}`. The fills and strokes an effect on a fill +//! or a stroke returns take no `effects`. +//! //! The result is checked whole before any of it is used ([`decode`]): every number finite and in //! range (nothing is clamped), every key known, a gradient stop's `plates` only on a stop linked to //! a spot swatch, and every swatch and pattern a paint names in the document ([`check_references`]). //! One fault refuses the whole result, naming the field. -use serde_json::Value; -use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, LineCap, LineJoin}; +use serde_json::{Map, Value}; +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, LineCap, LineJoin}; use vectorcraft_geom::{FillRule, PathData}; use crate::objects::{MAX_COORD, MAX_ITEMS, MAX_OBJECTS, MAX_STROKE_WIDTH, MITER_LIMIT, OutStroke, check_point, out_err}; @@ -24,15 +31,88 @@ use crate::{Error, Result}; const PIECE_KEYS: [&str; 6] = ["type", "path", "fillRule", "bounds", "fills", "strokes"]; /// The keys a stroke of a piece may have. const STROKE_KEYS: [&str; 5] = ["paint", "width", "join", "cap", "miterLimit"]; +/// The keys a piece, a stroke or a fill also may have when the effect declares `appearanceOutput`. +const LOOK_KEYS: [&str; 3] = ["opacity", "blend", "effects"]; +/// The look keys a fill or stroke has that an effect on a fill or a stroke returns. +const ROW_LOOK_KEYS: [&str; 2] = ["opacity", "blend"]; +/// The keys an effect record has. +const EFFECT_KEYS: [&str; 3] = ["id", "params", "visible"]; + +/// Most effect records one piece, fill or stroke may carry. +pub const MAX_LOOK_EFFECTS: usize = 16; +/// Most effect records one result may carry, over all its pieces, fills and strokes. +pub const MAX_RESULT_EFFECTS: usize = 4_096; + +/// How the host checks an effect record a piece (`false`) or one of its fills or strokes (`true`) +/// carries: `Err` with the reason when the record names no built-in effect that may be there or has +/// parameters that effect does not take. The plug-in crate checks the record's form; which effects +/// exist and what they take is the host's to say. +pub type CheckEffect = fn(&Effect, bool) -> std::result::Result<(), String>; + +/// The [`CheckEffect`] of a host that lets no effect record in. +pub fn no_effects(_: &Effect, _: bool) -> std::result::Result<(), String> { + Err("this host takes no effects here".into()) +} + +/// The host's [`CheckEffect`], set once ([`set_effect_check`]). +static CHECK: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Makes `check` how the effect records of painted results are checked in this process, unless +/// one was set before. Until one is set, every effect record is refused ([`no_effects`]). +pub fn set_effect_check(check: CheckEffect) { + let _ = CHECK.set(check); +} + +/// How the effect records of painted results are checked ([`set_effect_check`]). +pub(crate) fn effect_check() -> CheckEffect { + CHECK.get().copied().unwrap_or(no_effects) +} + +/// The opacity, blending mode and effects a piece, or one of its fills or strokes, is given: each +/// `None` (or empty) keeps what it would have without. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Look { + pub opacity: Option, + pub blend: Option, + /// Drawn after the effects it already has. + pub effects: Vec, +} + +impl Look { + /// Does it keep everything as it is? + pub fn is_empty(&self) -> bool { + self.opacity.is_none() && self.blend.is_none() && self.effects.is_empty() + } + + /// Gives fill or stroke `item` this opacity and blending mode where given, and these effects + /// after its own. + fn dress(&self, item: &mut AppearanceItem) { + let (opacity, blend, effects) = match item { + AppearanceItem::Fill(f) => (&mut f.opacity, &mut f.blend, &mut f.effects), + AppearanceItem::Stroke(s) => (&mut s.opacity, &mut s.blend, &mut s.effects), + }; + if let Some(o) = self.opacity { + *opacity = o; + } + if let Some(b) = self.blend { + *blend = b; + } + effects.extend(self.effects.iter().cloned()); + } +} /// One piece a live effect returned: its geometry and fill rule, and its fills and strokes in paint -/// order (`None`: the ones it was given). +/// order (`None`: the ones it was given), with the look of the piece and of each fill and stroke it +/// gives (`fill_looks[k]` for `fills[k]`; a missing one keeps everything). #[derive(Clone, Debug, PartialEq)] pub struct Piece { pub path: PathData, pub rule: FillRule, pub fills: Option>, pub strokes: Option>, + pub look: Look, + pub fill_looks: Vec, + pub stroke_looks: Vec, } /// Where in an appearance the effect sits, which says what its pieces may paint. @@ -51,6 +131,13 @@ pub enum Scope { /// is ignored. Any other top-level key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of /// range or a paint of the wrong form refuses the whole result, naming the field. pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> { + decode_with(bytes, scope, rule, None) +} + +/// [`decode`] for an effect that declares `appearanceOutput` when `looks` is `Some`: its pieces, +/// fills and strokes may then carry opacity, a blending mode and effects, each effect record +/// checked by it. +pub fn decode_with(bytes: &[u8], scope: Scope, rule: FillRule, looks: Option) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?; if let Some(e) = crate::objects::declined(&v) { return Err(e); @@ -63,13 +150,38 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> if objects.len() > MAX_OBJECTS { return Err(out_err("objects", format!("{} objects (limit {MAX_OBJECTS})", objects.len()))); } - let mut anchors = 0; - objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut anchors)).collect() + let mut counts = Counts { anchors: 0, effects: 0, looks, row_effects: scope == Scope::Object }; + objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut counts)).collect() } -fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) -> Result { +/// What a result holds so far, which its limits count: anchors and effect records, and how its +/// effect records are checked (`None`: the result carries no look), and whether its fills and +/// strokes may carry `effects` (only those of an object's effect: one on a fill or a stroke sits +/// among that fill's or stroke's own effects). +struct Counts { + anchors: usize, + effects: usize, + looks: Option, + row_effects: bool, +} + +impl Counts { + /// The look keys a fill or stroke may have. + fn row_look_keys(&self) -> &'static [&'static str] { + if self.row_effects { &LOOK_KEYS } else { &ROW_LOOK_KEYS } + } +} + +fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, counts: &mut Counts) -> Result { let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; - if let Some(k) = o.keys().find(|k| !PIECE_KEYS.contains(&k.as_str())) { + let known = |k: &str| PIECE_KEYS.contains(&k) || (counts.looks.is_some() && LOOK_KEYS.contains(&k)); + if let Some(k) = o.keys().find(|k| !known(k)) { + if counts.looks.is_some() { + return Err(out_err( + &format!("{at}.{k}"), + "a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects`", + )); + } return Err(out_err(&format!("{at}.{k}"), "a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes`")); } if let Some(t) = o.get("type") @@ -79,7 +191,7 @@ fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) } let path = o.get("path").ok_or_else(|| out_err(&format!("{at}.path"), "each piece needs a `path`"))?; // At most MAX_ANCHORS over all pieces. - let path = crate::objects::decode_path(path, &format!("{at}.path"), anchors)?; + let path = crate::objects::decode_path(path, &format!("{at}.path"), &mut counts.anchors)?; let rule = match o.get("fillRule") { None => rule, Some(r) => match r.as_str() { @@ -101,17 +213,112 @@ fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) Scope::Stroke if fills.is_some() => return Err(out_err(&format!("{at}.fills"), "an effect on a stroke returns only `strokes`")), _ => {} } - let fills = fills.map(|f| f.iter().enumerate().map(|(i, p)| paint(p, &format!("{at}.fills[{i}]"))).collect::>>()).transpose()?; - let strokes = - strokes.map(|s| s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"))).collect::>>()).transpose()?; - Ok(Piece { path, rule, fills, strokes }) + let look = look(o, at, false, counts)?; + let mut fill_looks = vec![]; + let fills = match fills { + None => None, + Some(f) => { + let rows = f.iter().enumerate().map(|(i, p)| fill_row(p, &format!("{at}.fills[{i}]"), counts)).collect::>>()?; + let (paints, looks): (Vec, Vec) = rows.into_iter().unzip(); + fill_looks = looks; + Some(paints) + } + }; + let mut stroke_looks = vec![]; + let strokes = match strokes { + None => None, + Some(s) => { + let rows = s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"), counts)).collect::>>()?; + let (strokes, looks): (Vec, Vec) = rows.into_iter().unzip(); + stroke_looks = looks; + Some(strokes) + } + }; + // A look that keeps everything is left out, so a result without any compares as one. + for looks in [&mut fill_looks, &mut stroke_looks] { + if looks.iter().all(Look::is_empty) { + looks.clear(); + } + } + Ok(Piece { path, rule, fills, strokes, look, fill_looks, stroke_looks }) +} + +/// A fill of a piece: a paint, or with `appearanceOutput` also `{"paint", "opacity"?, "blend"?, +/// "effects"?}` (an object with `paint` and no `type`), with its look. +fn fill_row(v: &Value, at: &str, counts: &mut Counts) -> Result<(Paint, Look)> { + match v.as_object() { + Some(o) if counts.looks.is_some() && o.contains_key("paint") && !o.contains_key("type") => { + let keys: Vec<&str> = std::iter::once("paint").chain(counts.row_look_keys().iter().copied()).collect(); + only_keys(v, at, &keys)?; + let look = look(o, at, true, counts)?; + Ok((paint(o.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?, look)) + } + _ => Ok((paint(v, at)?, Look::default())), + } +} + +/// The identifiers `blend` takes, in Transparency-panel order. +fn blend_names() -> String { + BlendMode::ALL.iter().map(|m| format!("{m:?}")).collect::>().join(", ") +} + +/// The opacity, blending mode and effects object `o` of a piece (`row` off) or of one of its fills +/// or strokes gives, checked: an `opacity` from 0 to 1, a `blend` that is one of [`BlendMode`]'s +/// identifiers exactly, and at most [`MAX_LOOK_EFFECTS`] effect records, each `{id, params?, +/// visible?}` that the host's [`CheckEffect`] lets in, within [`MAX_RESULT_EFFECTS`] for the whole +/// result. Without `appearanceOutput` the keys are refused before this is reached. +fn look(o: &Map, at: &str, row: bool, counts: &mut Counts) -> Result { + let Some(check) = counts.looks else { return Ok(Look::default()) }; + let opacity = match o.get("opacity") { + None => None, + Some(v) => match v.as_f64().filter(|x| within(*x, 0.0, 1.0)) { + Some(x) => Some(x as f32), + None => return Err(out_err(&format!("{at}.opacity"), "`opacity` must be a number from 0 to 1")), + }, + }; + let blend = match o.get("blend") { + None => None, + Some(v) => match v.as_str().and_then(|s| BlendMode::ALL.into_iter().find(|m| format!("{m:?}") == s)) { + Some(b) => Some(b), + None => return Err(out_err(&format!("{at}.blend"), format!("unknown blending mode; `blend` is one of {}", blend_names()))), + }, + }; + let records = match o.get("effects") { + None => &[][..], + Some(Value::Array(a)) if a.len() <= MAX_LOOK_EFFECTS => a.as_slice(), + Some(_) => return Err(out_err(&format!("{at}.effects"), format!("`effects` must be an array of at most {MAX_LOOK_EFFECTS} records"))), + }; + let mut effects = Vec::with_capacity(records.len()); + for (j, r) in records.iter().enumerate() { + let at = format!("{at}.effects[{j}]"); + counts.effects += 1; + if counts.effects > MAX_RESULT_EFFECTS { + return Err(out_err(&at, format!("a result carries at most {MAX_RESULT_EFFECTS} effect records"))); + } + only_keys(r, &at, &EFFECT_KEYS)?; + let e = crate::objects::decode_effect(r, &at)?; + check(&e, row).map_err(|why| out_err(&at, why))?; + effects.push(e); + } + Ok(Look { opacity, blend, effects }) } /// A stroke `{paint, width?, join?, cap?, miterLimit?}`: a width of 0–[`MAX_STROKE_WIDTH`] and a -/// miter limit in [`MITER_LIMIT`]. -fn stroke(v: &Value, at: &str) -> Result { +/// miter limit in [`MITER_LIMIT`]; with `appearanceOutput` also its look. +fn stroke(v: &Value, at: &str, counts: &mut Counts) -> Result<(OutStroke, Look)> { let s = v.as_object().ok_or_else(|| out_err(at, "a stroke must be {\"paint\", \"width\"?, \"join\"?, \"cap\"?, \"miterLimit\"?}"))?; - if let Some(k) = s.keys().find(|k| !STROKE_KEYS.contains(&k.as_str())) { + if counts.looks.is_some() && !counts.row_effects { + let keys: Vec<&str> = STROKE_KEYS.iter().chain(&ROW_LOOK_KEYS).copied().collect(); + only_keys(v, at, &keys)?; + } + let known = |k: &str| STROKE_KEYS.contains(&k) || (counts.looks.is_some() && LOOK_KEYS.contains(&k)); + if let Some(k) = s.keys().find(|k| !known(k)) { + if counts.looks.is_some() { + return Err(out_err( + &format!("{at}.{k}"), + "a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects`", + )); + } return Err(out_err(&format!("{at}.{k}"), "a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit`")); } let number = |key: &str, range: std::ops::RangeInclusive| -> Result> { @@ -136,7 +343,8 @@ fn stroke(v: &Value, at: &str) -> Result { Some(_) => return Err(out_err(&format!("{at}.cap"), "`cap` must be \"butt\", \"round\" or \"square\"")), }; let paint = paint(s.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?; - Ok(OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? }) + let out = OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? }; + Ok((out, look(s, at, true, counts)?)) } /// Is `x` finite and in `lo..=hi`? @@ -407,48 +615,78 @@ pub(crate) fn with_swatch_colors(mut pieces: std::sync::Arc>, doc: &D pieces } -/// How many paints, gradient stops and freeform points `pieces` hold: what a cache counts them as -/// besides their anchors. +/// How many paints, gradient stops and freeform points `pieces` hold, and one for each effect +/// record they carry and for each 50 bytes of its parameters: what a cache counts them as besides +/// their anchors. pub(crate) fn paint_count(pieces: &[Piece]) -> usize { let one = |p: &Paint| match p { Paint::Gradient(g) => 1 + g.gradient.stops.len() + g.freeform.as_ref().map_or(0, |f| f.points.len()), _ => 1, }; - pieces.iter().map(|p| p.fills.iter().flatten().map(one).sum::() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::()).sum() + let effects = |l: &Look| l.effects.iter().map(|e| 1 + e.params.to_string().len() / 50).sum::(); + let looks = |p: &Piece| effects(&p.look) + p.fill_looks.iter().chain(&p.stroke_looks).map(effects).sum::(); + pieces + .iter() + .map(|p| p.fills.iter().flatten().map(one).sum::() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::() + looks(p)) + .sum() } /// The appearance piece `p` of an object-level effect is drawn with: `base` (the object's) with /// its fills, then its strokes, replaced by the piece's where it has them, as a filter's output /// sets them (an existing item keeps everything but what the piece gives; new ones take the -/// defaults). +/// defaults), each given its look ([`Look`]). The piece's own look is not part of it: the art the +/// piece becomes carries it. pub fn appearance(base: &Appearance, p: &Piece) -> Appearance { let mut ap = base.clone(); if let Some(fills) = &p.fills { crate::objects::set_items(&mut ap, true, fills.iter().cloned().map(OutStroke::paint).collect()); + dress_items(&mut ap, true, &p.fill_looks); } if let Some(strokes) = &p.strokes { crate::objects::set_items(&mut ap, false, strokes.clone()); + dress_items(&mut ap, false, &p.stroke_looks); } ap } +/// Gives the fills (`fill`) or strokes of `ap`, in paint order, the looks in `looks`. +fn dress_items(ap: &mut Appearance, fill: bool, looks: &[Look]) { + for (item, look) in ap.items.iter_mut().filter(|i| i.is_fill() == fill).zip(looks) { + look.dress(item); + } +} + /// The items piece `p` of an effect on `item` (a fill or a stroke) is drawn with, in paint order: /// `item` itself when the piece keeps it, else one copy of it for each paint or stroke the piece -/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given). +/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given) and +/// that fill's or stroke's look. pub fn items(item: &AppearanceItem, p: &Piece) -> Vec { + let dressed = |mut it: AppearanceItem, look: Option<&Look>| { + if let Some(look) = look { + look.dress(&mut it); + } + it + }; match item { AppearanceItem::Fill(f) => match &p.fills { None => vec![item.clone()], - Some(fills) => fills.iter().map(|paint| AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() })).collect(), + Some(fills) => fills + .iter() + .enumerate() + .map(|(k, paint)| { + dressed(AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() }), p.fill_looks.get(k)) + }) + .collect(), }, AppearanceItem::Stroke(s) => match &p.strokes { None => vec![item.clone()], Some(strokes) => strokes .iter() - .map(|o| { + .enumerate() + .map(|(k, o)| { let mut s = s.clone(); crate::objects::style(&mut s, o.clone()); - AppearanceItem::Stroke(s) + dressed(AppearanceItem::Stroke(s), p.stroke_looks.get(k)) }) .collect(), }, diff --git a/crates/plugins/src/painted/tests.rs b/crates/plugins/src/painted/tests.rs index 471c12ea48..16135d47c8 100644 --- a/crates/plugins/src/painted/tests.rs +++ b/crates/plugins/src/painted/tests.rs @@ -84,8 +84,15 @@ fn a_piece_s_appearance_inherits_or_replaces() { ..Appearance::default() }; let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); - let piece = - |fills: Option>, strokes: Option>| Piece { path: PathData::default(), rule: FillRule::NonZero, fills, strokes }; + let piece = |fills: Option>, strokes: Option>| Piece { + path: PathData::default(), + rule: FillRule::NonZero, + fills, + strokes, + look: Look::default(), + fill_looks: vec![], + stroke_looks: vec![], + }; assert_eq!(appearance(&base, &piece(None, None)), base, "inherited"); let ap = appearance(&base, &piece(Some(vec![red.clone()]), Some(vec![]))); assert_eq!(ap.items.len(), 1); @@ -348,3 +355,147 @@ fn linked_spot_stop_plates_are_kept() { assert_eq!(plates(&pieces[0].fills.as_ref().unwrap()[0]), [Some([0.0; 4]), Some([0.1, 0.2, 0.3, 0.4])]); assert_eq!(plates(&pieces[0].strokes.as_ref().unwrap()[0].paint), [None, Some([0.1, 0.2, 0.3, 0.4])]); } + +/// A host check for these tests: Drop Shadow anywhere, Roughen on a piece only, nothing else. +fn shadows_only(e: &Effect, row: bool) -> std::result::Result<(), String> { + match e.id.as_str() { + "stylize.dropShadow" => Ok(()), + "distort.roughen" if !row => Ok(()), + id => Err(format!("not taken: {id}")), + } +} + +fn with_looks(pieces: Value) -> Result> { + decode_with(&out(pieces), Scope::Object, FillRule::NonZero, Some(shadows_only)) +} + +/// Without `appearanceOutput`, a piece, a fill and a stroke still have no opacity, blending mode +/// or effects: each refuses the result, naming the field. +#[test] +fn api2_and_undeclared_effects_still_refuse_piece_appearance() { + for (piece, at) in [ + (json!({"path": square(), "opacity": 0.5}), "objects[0].opacity"), + (json!({"path": square(), "blend": "Multiply"}), "objects[0].blend"), + (json!({"path": square(), "effects": []}), "objects[0].effects"), + (json!({"path": square(), "fills": [{"paint": red(), "opacity": 0.5}]}), "objects[0].fills[0]"), + (json!({"path": square(), "strokes": [{"paint": red(), "blend": "Screen"}]}), "objects[0].strokes[0].blend"), + ] { + let e = decode(&out(json!([piece])), Scope::Object, FillRule::NonZero).unwrap_err().to_string(); + assert!(e.contains(&format!("{at}:")), "{at}: {e}"); + } +} + +/// With `appearanceOutput`, a piece and each fill and stroke it returns take an opacity, a blending +/// mode by its identifier and effect records the host lets in; a fill carrying them is +/// `{"paint", …}`. The fills and strokes are dressed with them, with the effects after their own; +/// a piece without any compares as one from an effect that declares nothing. +#[test] +fn piece_and_row_opacity_blend_and_effects_decode_in_order() { + let shadow = json!({"id": "stylize.dropShadow", "params": {"x": 2}}); + let pieces = with_looks(json!([ + {"path": square(), "opacity": 0.5, "blend": "Multiply", "effects": [{"id": "distort.roughen"}, shadow], + "fills": [red(), {"paint": red(), "opacity": 0.25, "blend": "ColorBurn", "effects": [shadow]}], + "strokes": [{"paint": red(), "width": 2, "opacity": 0, "effects": [{"id": "stylize.dropShadow", "visible": false}]}]}, + {"path": square(), "fills": [red()]}, + ])) + .unwrap(); + let look = &pieces[0].look; + assert_eq!((look.opacity, look.blend), (Some(0.5), Some(BlendMode::Multiply))); + assert_eq!(look.effects.iter().map(|e| e.id.as_str()).collect::>(), ["distort.roughen", "stylize.dropShadow"]); + assert_eq!(look.effects[1].params, json!({"x": 2})); + assert_eq!(pieces[0].fill_looks.len(), 2); + assert!(pieces[0].fill_looks[0].is_empty()); + assert_eq!((pieces[0].fill_looks[1].opacity, pieces[0].fill_looks[1].blend), (Some(0.25), Some(BlendMode::ColorBurn))); + assert_eq!(pieces[0].stroke_looks[0].opacity, Some(0.0)); + assert!(!pieces[0].stroke_looks[0].effects[0].visible); + let plain = decode(&out(json!([{"path": square(), "fills": [red()]}])), Scope::Object, FillRule::NonZero).unwrap(); + assert_eq!(pieces[1], plain[0], "no look"); + // Dressed: the second fill and the stroke take their looks, the stroke's effect after its own. + let mut own = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0); + own.effects.push(Effect { id: "stylize.outerGlow".into(), params: Value::Null, visible: true }); + let base = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE))), AppearanceItem::Stroke(own)], + ..Default::default() + }; + let ap = appearance(&base, &pieces[0]); + let fills: Vec<&FillLayer> = ap.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + assert_eq!((fills[0].opacity, fills[0].blend), (1.0, BlendMode::Normal)); + assert_eq!((fills[1].opacity, fills[1].blend, fills[1].effects.len()), (0.25, BlendMode::ColorBurn, 1)); + let Some(AppearanceItem::Stroke(s)) = ap.items.iter().find(|i| !i.is_fill()) else { panic!("a stroke") }; + assert_eq!(s.opacity, 0.0); + assert_eq!(s.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow", "stylize.dropShadow"]); + // On one fill: each copy takes its own fill's look. + let copies = items(&base.items[0], &pieces[0]); + let opacity: Vec = copies.iter().map(|i| if let AppearanceItem::Fill(f) = i { f.opacity } else { -1.0 }).collect(); + assert_eq!(opacity, [1.0, 0.25]); +} + +/// Every bad look refuses the whole result, naming the field: an opacity that is not a number from +/// 0 to 1, a blending mode that is not an identifier exactly, an `effects` that is not a list, a +/// record with another key or an id the host refuses (a plug-in effect, a geometry effect on a +/// fill), and the limits of 16 records in a list and 4,096 in a result. +#[test] +fn invalid_appearance_field_refuses_every_piece_and_names_field() { + let ok = json!({"path": square(), "opacity": 0.5}); + let shadow = json!({"id": "stylize.dropShadow"}); + for (piece, at) in [ + (json!({"path": square(), "opacity": 1.5}), "objects[1].opacity"), + (json!({"path": square(), "opacity": -0.01}), "objects[1].opacity"), + (json!({"path": square(), "opacity": "0.5"}), "objects[1].opacity"), + (json!({"path": square(), "opacity": null}), "objects[1].opacity"), + (json!({"path": square(), "blend": "multiply"}), "objects[1].blend"), + (json!({"path": square(), "blend": "Color Burn"}), "objects[1].blend"), + (json!({"path": square(), "blend": 2}), "objects[1].blend"), + (json!({"path": square(), "effects": shadow}), "objects[1].effects"), + (json!({"path": square(), "effects": [{"id": "stylize.dropShadow", "order": 1}]}), "objects[1].effects[0].order"), + (json!({"path": square(), "effects": [{"id": ""}]}), "objects[1].effects[0]"), + (json!({"path": square(), "effects": [{"id": "plugin.test.self"}]}), "objects[1].effects[0]"), + (json!({"path": square(), "effects": [shadow, {"id": "stylize.nope"}]}), "objects[1].effects[1]"), + (json!({"path": square(), "fills": [{"paint": red(), "effects": [{"id": "distort.roughen"}]}]}), "objects[1].fills[0].effects[0]"), + (json!({"path": square(), "fills": [{"paint": red(), "tint": 1}]}), "objects[1].fills[0].tint"), + (json!({"path": square(), "strokes": [{"paint": red(), "opacity": 2}]}), "objects[1].strokes[0].opacity"), + (json!({"path": square(), "effects": vec![shadow.clone(); MAX_LOOK_EFFECTS + 1]}), "objects[1].effects"), + ] { + let e = with_looks(json!([ok, piece])).unwrap_err().to_string(); + assert!(e.contains(&format!("{at}:")), "{at}: {e}"); + } + let e = with_looks(json!([{"path": square(), "effects": [{"id": "plugin.test.self"}]}])).unwrap_err().to_string(); + assert!(e.contains("not taken: plugin.test.self"), "{e}"); + // 256 pieces of 16 records each fit; one more record does not. + let full = json!({"path": square(), "effects": vec![shadow.clone(); MAX_LOOK_EFFECTS]}); + let mut many = vec![full.clone(); MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS]; + assert_eq!(with_looks(Value::from(many.clone())).unwrap().len(), MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS); + many.push(json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]})); + let e = with_looks(Value::from(many)).unwrap_err().to_string(); + assert!( + e.contains(&format!("objects[{}].fills[0].effects[0]: a result carries at most {MAX_RESULT_EFFECTS}", MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS)), + "{e}" + ); + // A host that has set no check lets no record in. + let e = decode_with(&out(json!([{"path": square(), "effects": [shadow]}])), Scope::Object, FillRule::NonZero, Some(no_effects)).unwrap_err(); + assert!(e.to_string().contains("objects[0].effects[0]:"), "{e}"); +} + +/// An effect on a fill or a stroke sits among that fill's or stroke's own effects, so the fills +/// and strokes it returns take an opacity and a blending mode but no `effects`, even an empty +/// list; its pieces still take effects of their own. +#[test] +fn rows_of_an_effect_on_a_fill_or_stroke_take_no_effects() { + let shadow = json!({"id": "stylize.dropShadow"}); + for (scope, piece, at) in [ + (Scope::Fill, json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]}), "objects[0].fills[0].effects"), + (Scope::Fill, json!({"path": square(), "fills": [{"paint": red(), "effects": []}]}), "objects[0].fills[0].effects"), + (Scope::Stroke, json!({"path": square(), "strokes": [{"paint": red(), "effects": [shadow]}]}), "objects[0].strokes[0].effects"), + ] { + let e = decode_with(&out(json!([piece])), scope, FillRule::NonZero, Some(shadows_only)).unwrap_err().to_string(); + assert!(e.contains(&format!("{at}:")), "{at}: {e}"); + } + for (scope, piece) in [ + (Scope::Fill, json!({"path": square(), "effects": [shadow], "fills": [{"paint": red(), "opacity": 0.5, "blend": "Screen"}]})), + (Scope::Stroke, json!({"path": square(), "effects": [shadow], "strokes": [{"paint": red(), "width": 1, "opacity": 0.5}]})), + (Scope::Object, json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]})), + ] { + let pieces = decode_with(&out(json!([piece])), scope, FillRule::NonZero, Some(shadows_only)); + assert!(pieces.is_ok(), "{scope:?}: {pieces:?}"); + } +} diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 5fda6fb896..538a454f52 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -15,10 +15,14 @@ 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 filter's `writes` ([`WRITES_API`]) and a manifest's -/// `context` ([`CONTEXT_API`]). +/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]), a live effect's +/// `appearanceOutput` ([`APPEARANCE_API`]) and a manifest's `context` ([`CONTEXT_API`]). pub const API_LEVEL: u32 = 3; +/// The API level that adds a painted live effect's `appearanceOutput`: opacity, a blending mode +/// and effects on the pieces it returns and on their fills and strokes ([`crate::painted`]). +pub const APPEARANCE_API: u32 = 3; + /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, /// `settings`, `cache` and `commands` permissions they need. pub const PROGRESS_API: u32 = 2; diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index a79aa72a22..9fc233e51c 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -533,6 +533,15 @@ impl FolderLoad { Self::list_on(dir, allow, None) } + /// [`FolderLoad::list`] for the one file `file` of a folder, without listing the folder: a file + /// that is no longer there is reported as failed. + pub fn list_file( + file: &std::path::Path, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + ) -> Result { + Self::list_found(Ok((vec![file.to_path_buf()], 0)), allow, None) + } + /// Starts the loads, unless they started already. pub fn start(&mut self) { self.changes.start(); @@ -545,6 +554,16 @@ impl FolderLoad { dir: &std::path::Path, allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, workers: Option, + ) -> Result { + Self::list_found(Err(dir), allow, workers) + } + + /// [`FolderLoad::list_on`] for the files of folder `Err(dir)`, or for the files and the count of + /// files left out given as `Ok`. + fn list_found( + found: std::result::Result<(Vec, usize), &std::path::Path>, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + workers: Option, ) -> Result { use crate::loader::{Job, Loads}; use crate::safe_mode::{self, Item}; @@ -552,7 +571,10 @@ impl FolderLoad { // A change made elsewhere once the folder starts being listed is one the load doesn't undo. let mut changes = LoadChanges::default(); changes.start(); - let (found, left_out) = folder_files(dir)?; + let (found, left_out) = match found { + Ok(found) => found, + Err(dir) => folder_files(dir)?, + }; let allow = std::sync::Arc::new(allow); let mut files = Vec::with_capacity(found.len()); let mut jobs = Vec::new(); diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index 9a580a1b11..ef282e5b4d 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -7,6 +7,8 @@ use std::sync::Arc; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, Rect}; +use crate::placed_document::{LayerMode, enter_layer}; + /// What may draw differently in a document than in its version before an edit ([`changed`]). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Changed { @@ -129,6 +131,8 @@ fn changed_with(old: &Document, new: &Document, renderer: Option<&mut crate::Ren return Changed::Everything; } let mut diff = Diff { old: old.symbol_boxes(), new: new.symbol_boxes(), area: None, renderer, opts, sources: (None, None) }; + // Measured as the frames with `opts` draw ([`crate::Renderer::cross_placed`]). + let _mode = LayerMode { options: opts.dim_templates && !opts.skip_templates, outline: opts.outline, images: new.setup.outline_images }.enter(); diff.children(&old.layers, &new.layers); diff.area.map_or(Changed::Nothing, Changed::Area) } @@ -179,11 +183,20 @@ impl Diff<'_, '_> { } } + /// [`Self::node_in`], the members of a layer that draws in the same mode in both versions + /// measured in that mode ([`LayerMode::inside`]). The two versions of a layer that draw in + /// different modes are each measured in their own ([`Self::bounds`]). + fn node(&mut self, old: &Arc, new: &Arc) { + let modes = LayerMode::now().map(|m| (m.inside(old), m.inside(new))); + let _mode = modes.and_then(|(a, b)| if a == b { b } else { None }).map(LayerMode::enter); + self.node_in(old, new); + } + /// A group or layer that only its members changed in, without a clipping mask or effects of /// its own that draw from all of them, changed where they did. A path or compound path that /// only had anchors moved changed around them ([`moved_anchors`]). Any other object that /// changed counts whole, before and after. - fn node(&mut self, old: &Arc, new: &Arc) { + fn node_in(&mut self, old: &Arc, new: &Arc) { if Arc::ptr_eq(old, new) || self.unseen(Side::Old, old) && self.unseen(Side::New, new) { return; } @@ -228,6 +241,8 @@ impl Diff<'_, '_> { if self.unseen(side, n) { return None; } + // A layer is measured in the mode its Layer Options draw it in. + let _mode = enter_layer(n); let Diff { old, new, renderer, .. } = self; let symbols = match side { Side::Old => old, diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2a554a3d92..be4cfb5f77 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -22,11 +22,17 @@ pub(super) fn node_bezpath(n: &Node) -> Option { } } +/// The box geometry effects on `bp` work from: the object's geometric bounds, lone anchors +/// included, as [`vectorcraft_geom::PathData::bounds`] measures them. +fn reference_box(bp: &BezPath) -> Rect { + vectorcraft_geom::path::anchored_curve_bounds(bp).unwrap_or_default() +} + pub(super) fn apply(effects: &[Effect], bp: &BezPath, ctx: &GeomContext) -> BezPath { if !effects::has_geometry(effects) || bp.elements().is_empty() { return bp.clone(); } - effects::apply_geometry_bez(effects, bp, bp.bounding_box(), ctx) + effects::apply_geometry_bez(effects, bp, reference_box(bp), ctx) } /// The object-level effected geometry of `n` (base path `bp`), with the swatches and patterns that @@ -40,7 +46,7 @@ pub(super) fn apply_carrying(effects: &[Effect], bp: &BezPath, ctx: &GeomContext if !effects::has_geometry(effects) || bp.elements().is_empty() { return (bp.clone(), effects::Carry::default()); } - effects::apply_geometry_bez_carrying(effects, bp, bp.bounding_box(), ctx) + effects::apply_geometry_bez_carrying(effects, bp, reference_box(bp), ctx) } /// [`effected_path`], and how `n`'s gradients follow its effects. @@ -124,7 +130,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { if carry.skipped() { carry.hide_skipped(&mut ran.to_mut().appearance.effects); } - let mut r: Option = (!g.elements().is_empty()).then(|| g.bounding_box()); + let mut r: Option = drawn_box(&g, n.appearance.painted_strokes().any(dotted)); for (j, item) in n.appearance.items.iter().enumerate() { let fx = item_effects(item); if effects::has_geometry(fx) { @@ -134,10 +140,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { { c.hide_skipped(it.effects_mut()); } - if !ig.elements().is_empty() { - let b = ig.bounding_box(); - r = Some(r.map_or(b, |r| r.union(b))); - } + r = vectorcraft_geom::union_opt(r, drawn_box(&ig, item_dots(item))); } } let s = n.appearance.outset(); @@ -324,10 +327,29 @@ fn item_bounds(doc: &Document, n: &Node, item: &AppearanceItem) -> Option if effects::has_geometry(fx) { let ig = apply(fx, &g, &GeomContext { doc: Some(doc), ..GeomContext::of(n) }.item(item)); let o = if let AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - return (!ig.elements().is_empty()).then(|| ig.bounding_box().inflate(o, o)); + return drawn_box(&ig, item_dots(item)).map(|b| b.inflate(o, o)); } let one = vectorcraft_doc::Appearance { items: vec![item.clone()], ..Default::default() }; - (!g.elements().is_empty()).then(|| one.stroked_bounds(g.bounding_box(), || g.clone())) + drawn_box(&g, item_dots(item)).map(|b| one.stroked_bounds(b, || g.clone())) +} + +/// The box of what `g` draws before the strokes' reach ([`vectorcraft_geom::path::drawn_curve_bounds`]), +/// with the lone anchors of closed subpaths when `dots`; a path that draws nothing is measured by +/// its anchors, as [`Node::visual_bounds`] measures one. `None` for a path with no elements. +pub(super) fn drawn_box(g: &BezPath, dots: bool) -> Option { + vectorcraft_geom::path::drawn_curve_bounds(g, dots) + .or_else(|| g.elements().iter().filter_map(|e| e.end_point()).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b))) +} + +/// Does `s`, a painted stroke, draw a lone anchor of a closed subpath as a dot (a round or +/// projecting cap)? +pub(super) fn dotted(s: &vectorcraft_doc::StrokeLayer) -> bool { + matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square) +} + +/// Does `item` draw lone anchors as dots: a painted stroke with a round or projecting cap? +fn item_dots(item: &AppearanceItem) -> bool { + matches!(item, AppearanceItem::Stroke(s) if paints(item) && dotted(s)) } /// `b` grown by how far raster effects `fx` paint past it, each spreading what the ones before it @@ -382,12 +404,13 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { let mut plain = n.appearance.clone(); plain.items.retain(|i| !(paints(i) && effects::has_geometry(item_effects(i)))); let on_path = !n.appearance.items.iter().any(paints) || plain.items.iter().any(paints); - let mut r = (on_path && !g.elements().is_empty()).then(|| plain.stroked_bounds(g.bounding_box(), || g.clone())); + let dots = plain.painted_strokes().any(dotted); + let mut r = on_path.then(|| drawn_box(&g, dots)).flatten().map(|b| plain.stroked_bounds(b, || g.clone())); let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) }; for item in n.appearance.items.iter().filter(|i| paints(i) && effects::has_geometry(item_effects(i))) { let ig = apply(item_effects(item), &g, &ctx.item(item)); let o = if let AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - r = vectorcraft_geom::union_opt(r, (!ig.elements().is_empty()).then(|| ig.bounding_box().inflate(o, o))); + r = vectorcraft_geom::union_opt(r, drawn_box(&ig, item_dots(item)).map(|b| b.inflate(o, o))); } r } diff --git a/crates/render/src/fx/predicates.rs b/crates/render/src/fx/predicates.rs index 08bfceb7f2..f46a109aa7 100644 --- a/crates/render/src/fx/predicates.rs +++ b/crates/render/src/fx/predicates.rs @@ -68,11 +68,13 @@ pub(super) fn evaluates_live(n: &Node) -> bool { /// dots sampled from everything it draws), one with a live-effect plug-in that paints its pieces /// (drawn only while the swatches and patterns they name are in the document), or an image with a /// fill or stroke that follows the outline of its pixels ([`effects::follows_image_pixels`]: the -/// document's pixels for it can change), in it or in the opacity masks of the objects in it. +/// document's pixels for it can change), or a placed document (its file read, or in some Outline +/// frames its crossed box, [`vectorcraft_doc::placed_document::Crossed`]), in it or in the opacity +/// masks of the objects in it. pub(super) fn reads_outside(n: &Node) -> bool { let mut reads = false; n.walk(&mut |c| { - reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. }) + reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_)) || effects::follows_image_pixels(c) || effects::has_revolve(c) || effects::has_solid(c) diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 1bc71d4626..67b80e6b41 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1,4 +1,4 @@ -use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage}; +use super::bounds::{cull_bounds, dotted, drawn_box, effected_path_carrying, node_bezpath, rasterize_stage}; use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry}; use super::pixels::FilterReach; use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted}; @@ -453,7 +453,7 @@ impl Renderer { let rfx = effects::raster_effects(&paints.appearance.effects); // Document-space reach of the painted geometry (strokes, arrowheads…). let outset = n.appearance.outset(); - let reach = g.bounding_box().inflate(outset, outset); + let reach = drawn_box(g, paints.appearance.painted_strokes().any(dotted)).unwrap_or_default().inflate(outset, outset); let bounds = rasterize_bounds(f.symbols, n, &rfx); // Under Rasterize the content reaches as far as its fills' and strokes' raster effects paint. let reach = bounds.map_or(reach, |b| reach.union(b)); @@ -488,9 +488,9 @@ impl Renderer { // A placed document whose effects make no art of their own (raster effects and color // adjustments, which Outline mode does not draw) shows its box crossed as without effects // ([`Self::draw_placed`]). Effects that change geometry (plug-in effects among them, - // [`effects::is_geometry`]), 3D and Pathfinder make art from - // the file's art, which is drawn; Crop Marks and Vector Halftone draw the placed document - // itself among their art. + // [`effects::is_geometry`]), 3D and Pathfinder make art from the crossed box, which the + // frame gives as the placed document's art ([`Self::cross_placed`]), and that art is drawn; + // Crop Marks and Vector Halftone draw the placed document itself among their art. if let NodeKind::PlacedDocument(p) = &a.kind && self.crosses_placed(f) && !effects::has_geometry(&a.appearance.effects) diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 39b6e951b8..757290ed1f 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -99,6 +99,88 @@ fn doc_with(r: Rect, fill: Color, effects: Vec<(&str, serde_json::Value)>) -> Do d } +/// A stroked line from (10, 50) to (60, 50) beside a lone anchor at (90, 90), closed or open +/// (`line` false: the lone anchor alone), its stroke 4 pt wide with `cap`, round joins and the +/// object-level `object` and stroke-level `stroke` effects. +fn lone_anchor_doc(line: bool, closed: bool, cap: vectorcraft_doc::LineCap, object: &[Effect], stroke: &[Effect]) -> Document { + use vectorcraft_geom::{PathData, SubPath}; + let mut d = Document::new(100.0, 100.0); + let lone = SubPath::polyline(&[Point::new(90.0, 90.0)], closed); + let subpaths = if line { vec![SubPath::polyline(&[Point::new(10.0, 50.0), Point::new(60.0, 50.0)], false), lone] } else { vec![lone] }; + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + let s = ap.stroke_mut().unwrap(); + (s.cap, s.join) = (cap, vectorcraft_doc::LineJoin::Round); + s.effects = stroke.to_vec(); + ap.effects = object.to_vec(); + let n = Node::path(d.alloc_id(), PathData::new(subpaths), ap); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// The bounds the effects are measured by hold the dot a round or projecting cap draws for a +/// lone anchor of a closed subpath, wherever the effected path is measured: the visual and cull +/// bounds (with the object's or the stroke's own geometry effect) and what Rasterize makes its image +/// over (the path as drawn, and a stroke with a raster effect, with and without a geometry effect +/// of its own). A lone anchor that draws no dot (open, or under a butt cap) leaves them as the line +/// alone has them. +#[test] +fn effect_bounds_hold_a_lone_anchors_dot_only_where_its_cap_draws_one() { + use vectorcraft_doc::LineCap; + let fx = |id: &str, p: serde_json::Value| Effect { id: id.into(), params: p, visible: true }; + // The object's effect moves the dot to (91, 90), the stroke's own effect to (130, 90), and the + // stroke's shadow paints a copy 30 pt below. + let moved = fx("distort.transform", json!({"moveH": 1})); + let far = fx("distort.transform", json!({"moveH": 40})); + let shadow = fx("stylize.dropShadow", json!({"x": 0, "y": 30, "blur": 0})); + // (what, object effects, stroke effects, measure, the center of the lowest dot painted) + type Measure = fn(&Document, &Node) -> Option; + let visual: Measure = |d, n| super::visual_bounds(&d.symbol_boxes(), n); + let cull: Measure = |d, n| super::cull_bounds(&d.symbol_boxes(), n); + let drawn: Measure = |d, n| crate::drawn_bounds(d, n); + type Case = (&'static str, Vec, Vec, Measure, Point); + let cases: [Case; 7] = [ + ("visual, object effect", vec![moved.clone()], vec![], visual, Point::new(91.0, 90.0)), + ("visual, stroke effect", vec![], vec![far.clone()], visual, Point::new(130.0, 90.0)), + ("cull, object effect", vec![moved.clone()], vec![], cull, Point::new(91.0, 90.0)), + ("drawn, object effect", vec![moved.clone()], vec![], drawn, Point::new(91.0, 90.0)), + ("drawn, stroke effect", vec![], vec![far.clone()], drawn, Point::new(130.0, 90.0)), + ("drawn, stroke raster effect", vec![moved.clone()], vec![shadow.clone()], drawn, Point::new(91.0, 120.0)), + ("drawn, stroke geometry and raster effects", vec![], vec![far.clone(), shadow.clone()], drawn, Point::new(130.0, 120.0)), + ]; + for (what, object, stroke, measure, dot) in cases { + for (closed, cap) in [(true, LineCap::Round), (true, LineCap::Square), (true, LineCap::Butt), (false, LineCap::Round)] { + let d = lone_anchor_doc(true, closed, cap, &object, &stroke); + let b = measure(&d, &d.layers[0].children().unwrap()[0]).unwrap(); + if closed && cap != LineCap::Butt { + // The dot is 4 pt across. + assert!(b.x1 >= dot.x + 2.0 - 1e-6 && b.y1 >= dot.y + 2.0 - 1e-6, "{what}, {cap:?}: {b:?} leaves out the dot at {dot:?}"); + } else { + assert!(b.y1 < dot.y - 2.0, "{what}, closed {closed}, {cap:?}: {b:?} reaches toward a lone anchor that draws nothing"); + } + } + } +} + +/// A path of only a lone anchor is measured at that anchor, not at the origin, and an effect that +/// paints around what the path draws (a drop shadow) is drawn over the dot a round cap draws there. +#[test] +fn a_path_of_a_lone_anchor_is_measured_at_its_dot() { + use vectorcraft_doc::LineCap; + let moved = Effect { id: "distort.transform".into(), params: json!({"moveH": 1}), visible: true }; + let d = lone_anchor_doc(false, true, LineCap::Round, std::slice::from_ref(&moved), &[]); + let n = &d.layers[0].children().unwrap()[0]; + for (what, b) in [("visual", super::visual_bounds(&d.symbol_boxes(), n)), ("drawn", crate::drawn_bounds(&d, n))] { + let b = b.unwrap(); + assert!(b.contains(Point::new(91.0, 90.0)) && !b.contains(Point::ZERO), "{what}: {b:?}"); + } + let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 0, "y": 6, "blur": 0}), visible: true }; + let d = lone_anchor_doc(true, true, LineCap::Round, &[moved, shadow], &[]); + let img = render(&d); + assert!(lum(img.pixel(91, 90)) < 200, "the dot is drawn"); + assert!(lum(img.pixel(91, 96)) < 600, "the dot's shadow is drawn: {:?}", img.pixel(91, 96)); +} + fn render(d: &Document) -> Rendered { Renderer::new().render(d, 100, 100, Affine::IDENTITY, &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) } @@ -2123,3 +2205,29 @@ fn a_3d_effect_that_builds_nothing_draws_the_item_as_without_it() { } } } + +/// Geometry effects work from the object's bounds, lone anchors included, as the selection's box +/// and Expand Appearance measure them: a Transform effect that scales a 10 pt line with a lone +/// anchor at (100, 50) by 200% scales it about (50, 25), the center of the box that holds the +/// anchor, and a path of one anchor stays where it is. +#[test] +fn geometry_effects_work_from_bounds_that_hold_lone_anchors() { + use vectorcraft_geom::{PathData, PathEl, SubPath}; + let scale = Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true }; + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false); + let lone = SubPath::polyline(&[Point::new(100.0, 50.0)], false); + let d = Document::new(200.0, 200.0); + for (path, first) in [(PathData::new(vec![line, lone.clone()]), Point::new(-50.0, -25.0)), (PathData::single(lone), Point::new(100.0, 50.0))] { + let mut n = Node::path(vectorcraft_doc::NodeId(1), path.clone(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + n.appearance.effects.push(scale.clone()); + let bp = super::bounds::node_bezpath(&n).unwrap_or_default(); + let want = crate::effects::apply_geometry(std::slice::from_ref(&scale), &path, path.bounds().unwrap_or_default()).to_bezpath(); + let drawn = super::bounds::effected_path(&d, &n, &bp); + let (carried, _) = super::bounds::effected_path_carrying(&d, &n, &bp); + for g in [&drawn, &carried] { + assert_eq!(g, &want, "{path:?}"); + let Some(PathEl::MoveTo(p)) = g.elements().first() else { panic!("{g:?} starts with no point") }; + assert!((p.x - first.x).abs() < 1e-9 && (p.y - first.y).abs() < 1e-9, "{path:?} starts at {p:?}, not {first:?}"); + } + } +} diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 341aa22ff9..2884e9c4d8 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -176,7 +176,8 @@ struct Shown { /// tilings ([`crate::pattern::hash_tiling`]) of the patterns in the fills and strokes of its /// objects and of type's characters, the address of each symbol instance's art, and the address of /// the read of each placed file that [`vectorcraft_doc::PlacedDocument::art`] shows (none before -/// the file is read), and the address of the document's pixels for each image whose +/// the file is read) with whether that art is the crossed box +/// ([`vectorcraft_doc::placed_document::Crossed`]), and the address of the document's pixels for each image whose /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, @@ -214,6 +215,8 @@ fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, NodeKind::PlacedDocument(p) => { let read = vectorcraft_doc::placed_document::read_cached(p); read.as_ref().map(|r| Arc::as_ptr(r) as usize).hash(h); + // The art is the crossed box instead in some Outline frames. + vectorcraft_doc::placed_document::crossed().hash(h); shown.reads.extend(read.as_ref().map(Arc::downgrade)); shown.text = true; shown.placed = true; diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 702933e95f..c3f7caa40b 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -297,6 +297,74 @@ fn depth() -> usize { DEPTH.with(Cell::get) } +/// How a frame draws art ([`Renderer::layer_mode`]): whether Layer Options apply (on screen; +/// exports and thumbnails ignore them), whether the art draws in Outline mode, and whether Show +/// Images in Outline Mode is on for it ([`Renderer::shows_outline_images`]). Layers are measured +/// in the mode they draw in, and placed documents are their crossed box in Outline mode without +/// Show Images in Outline Mode ([`vectorcraft_doc::placed_document::Crossed`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct LayerMode { + pub(crate) options: bool, + pub(crate) outline: bool, + pub(crate) images: bool, +} + +thread_local! { + /// The mode of the frame being drawn or measured on this thread ([`LayerMode::enter`]). + static MODE: Cell> = const { Cell::new(None) }; +} + +impl LayerMode { + /// The mode layer `n` draws its art in when its Layer Options change it: a template layer stays + /// in Preview in Outline mode (#1486), and a layer whose Preview is off draws in outline. + /// `None` for other objects and for a layer that draws in this mode. + pub(crate) fn inside(self, n: &Node) -> Option { + let vectorcraft_doc::NodeKind::Layer { preview, template, .. } = &n.kind else { return None }; + if !self.options { + return None; + } + let outline = if *template && self.outline { + false + } else if !preview && !template && !self.outline { + true + } else { + return None; + }; + Some(Self { outline, ..self }) + } + + /// The mode of the frame being drawn or measured on this thread, if any. + pub(crate) fn now() -> Option { + MODE.with(Cell::get) + } + + /// Draw and measure in this mode on this thread until the guard returned is dropped. + pub(crate) fn enter(self) -> InMode { + let crossed = vectorcraft_doc::placed_document::Crossed::set(self.outline && !self.images); + InMode { was: MODE.with(|m| m.replace(Some(self))), _crossed: crossed } + } +} + +/// While alive: art on this thread is drawn and measured in a [`LayerMode`]; once dropped, in the +/// mode before it. +#[must_use] +pub(crate) struct InMode { + was: Option, + _crossed: vectorcraft_doc::placed_document::Crossed, +} + +impl Drop for InMode { + fn drop(&mut self) { + MODE.with(|m| m.set(self.was)); + } +} + +/// Measure layer `n` in the mode its Layer Options draw it in, inside the mode on this thread +/// ([`LayerMode::inside`]), until the guard returned is dropped; `None` when that is the same mode. +pub(crate) fn enter_layer(n: &Node) -> Option { + LayerMode::now()?.inside(n).map(LayerMode::enter) +} + /// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent /// pixels through `view`, the placed documents inside it one level deeper. pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc, w: u16, h: u16, view: Affine) -> Option { @@ -489,8 +557,8 @@ impl Renderer { } /// Draw placed document `p` as its box crossed from corner to corner ([`Self::crosses_placed`]). - /// Its file is still read, as when its art is drawn: the art its effects and its group's effects - /// make comes from the read kept. + /// Its file is still read, as when its art is drawn: once the frame shows images again, the art + /// its effects and its group's effects make comes from the read kept. pub(crate) fn draw_crossed_placed(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) { if let Some(blob) = f.doc.images.get(&p.key) { let _ = read_placed(p, blob); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 3e34f4da9b..065055f96c 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -198,6 +198,7 @@ impl Renderer { let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let _crossed = self.cross_placed(&frame); self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) { @@ -484,6 +485,7 @@ impl Renderer { let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); + let _crossed = self.cross_placed(&frame); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 1e47dcf70d..b34f562ca1 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -6,6 +6,27 @@ use super::{ }; use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; +use crate::placed_document::{InMode, LayerMode, enter_layer}; +use vectorcraft_doc::placed_document::crossed; + +/// The key of `a`'s cull bounds in [`Renderer::geom`]: its address, and in its lowest bits what the +/// bounds depend on besides `a`. For a layer that is the mode its sublayers are measured in +/// ([`LayerMode`], [`enter_layer`]); for an object other than a path, whether placed documents are +/// crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the art its effects make from a +/// placed document in it is the crossed box then. A node's address is aligned to 8 bytes, so no +/// other node has that key. +fn geom_key(a: &Node) -> usize { + let at = std::ptr::from_ref(a) as usize; + match a.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => at, + NodeKind::Layer { .. } => { + at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2) + } + _ => at | usize::from(crossed()), + } +} + +const _: () = assert!(std::mem::align_of::() >= 8, "geom_key keeps three bits below a node's address"); fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool { measures_three_d(node) @@ -34,7 +55,7 @@ impl Renderer { if patch.is_some_and(Frame::patch_rejected) { return None; } - let key = Arc::as_ptr(a) as usize; + let key = geom_key(a); if let Some(e) = self.geom.get_mut(&key) && Arc::ptr_eq(&e.node, a) { @@ -53,6 +74,7 @@ impl Renderer { let source = a.extras().trace.is_some().then(|| children.first()).flatten(); for c in children { if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) { + let _mode = enter_layer(c); acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch)); if patch.is_some_and(Frame::patch_rejected) { return None; @@ -158,6 +180,19 @@ impl Renderer { } } + /// How frame `f` draws art ([`LayerMode`]). + pub(crate) fn layer_mode(&self, f: &Frame) -> LayerMode { + LayerMode { options: f.opts.dim_templates && !f.opts.skip_templates, outline: f.opts.outline, images: self.shows_outline_images(f) } + } + + /// Draw and measure art in frame `f`'s mode ([`Self::layer_mode`]) until the guard returned is + /// dropped: placed documents' art ([`vectorcraft_doc::PlacedDocument::art`]) is their box + /// crossed from corner to corner in Outline mode without Document Setup → Show Images in + /// Outline Mode ([`Self::crosses_placed`]), else their file's art. + pub(crate) fn cross_placed(&self, f: &Frame) -> InMode { + self.layer_mode(f).enter() + } + /// When a plug-in has been installed or removed since the last check /// ([`effects::plugin_revision`]), drop what the caches keep from plug-in effects: the effect /// geometry of paths with a plug-in effect, the cull bounds of objects that have one or hold one, @@ -266,6 +301,8 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, a) { return true; } + // A layer is measured in the mode its Layer Options draw it in ([`Self::draw_node`]). + let _mode = self.layer_mode(f).inside(a).map(LayerMode::enter); let bounds = self.frame_bounds_of(f, a); if f.patch_rejected() { return true; @@ -377,6 +414,13 @@ impl Renderer { /// Everything [`Self::draw_arc`] does after culling. fn draw_arc_body(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { + // A layer with effects of its own draws them in the mode its Layer Options give it, as + // `draw_node` draws any other layer. + if let Some(mode) = self.layer_mode(f).inside(a) { + let opts = RenderOptions { outline: mode.outline, ..f.opts.clone() }; + let _mode = mode.enter(); + return self.draw_arc_body(ctx, &Frame { opts: &opts, ..*f }, a); + } // Fast path for plain paths: cached geometry, opacity folded into the paint. // A blend mode on a single plain fill applies per draw (exact for one paint operation); // a blend layer would composite the whole viewport. @@ -459,18 +503,15 @@ impl Renderer { // Layer Options on screen: a layer whose Preview is off draws in outline, and Dim Images // fades its images, a template's too (exports and thumbnails, which leave templates out, // ignore both). - if let NodeKind::Layer { preview, dim_images, template, .. } = &n.kind + if let NodeKind::Layer { dim_images, .. } = &n.kind && f.opts.dim_templates && !f.opts.skip_templates { // A template layer stays in Preview while the view is in Outline (and whatever its own // Preview option says): its picture is there to be traced (#1486). - if *template && f.opts.outline { - let opts = RenderOptions { outline: false, ..f.opts.clone() }; - return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force); - } - if !preview && !template && !f.opts.outline { - let opts = RenderOptions { outline: true, ..f.opts.clone() }; + if let Some(mode) = self.layer_mode(f).inside(n) { + let opts = RenderOptions { outline: mode.outline, ..f.opts.clone() }; + let _mode = mode.enter(); return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force); } if let Some(p) = *dim_images { @@ -763,6 +804,7 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; + let _crossed = self.cross_placed(&frame); // An Abutting trace's seam fills hold no traced outline: a clip group of paths that are // each stroked without a fill or (on a stretched image, the strokes' outlines) filled // without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the @@ -843,7 +885,7 @@ impl Renderer { /// Cull bounds of `n` (symbol instances measured by their art box from `symbols`): cached when /// it is a node of the tree being drawn. fn node_bounds(&mut self, symbols: &SymbolBoxes, n: &Node) -> Option { - match self.geom.get(&(n as *const Node as usize)) { + match self.geom.get(&geom_key(n)) { // The entry keeps its node alive, so the address is that node's. Some(e) if std::ptr::eq(Arc::as_ptr(&e.node), n) => e.bounds, _ => fx::cull_bounds(symbols, n), diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 06cada26f4..eddc139ebb 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -30,6 +30,7 @@ mod meshwarp; mod movedstroke; mod objectfx; mod paintedbrush; +mod paintedlook; mod placed_document; mod rasterize; mod setup; diff --git a/crates/render/src/tests/paintedlook.rs b/crates/render/src/tests/paintedlook.rs new file mode 100644 index 0000000000..d7ce8284c6 --- /dev/null +++ b/crates/render/src/tests/paintedlook.rs @@ -0,0 +1,136 @@ +//! A live-effect plug-in that declares `appearanceOutput` gives each piece it returns an opacity, a +//! blending mode and effects, and the canvas draws the piece with them. A refused look (an unknown +//! blending mode, a plug-in effect) leaves the source as it is. + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Effect, Node}; +use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, shapes}; + +use crate::{RenderOptions, Renderer}; + +/// A 20 × 20 square at `x`, 40. +fn square_at(x: f64) -> PathData { + PathData::single(SubPath::polyline(&[Point::new(x, 40.0), Point::new(x + 20.0, 40.0), Point::new(x + 20.0, 60.0), Point::new(x, 60.0)], true)) +} + +/// The output of a plug-in that returns one piece: the square at `x`, 40 filled red, with `look`'s +/// keys added to it. +fn output(x: f64, look: &serde_json::Value) -> String { + let red = serde_json::to_value(Paint::solid(Color::rgb(1.0, 0.0, 0.0))).unwrap(); + let mut piece = json!({"path": square_at(x), "fills": [red]}); + if let (Some(p), Some(l)) = (piece.as_object_mut(), look.as_object()) { + p.extend(l.clone()); + } + json!({ "objects": [piece] }).to_string() +} + +/// The manifest of live-effect plug-in `id`, which declares `appearanceOutput`. +fn manifest(id: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#) +} + +/// Installs live-effect plug-in `id`, which returns one piece: the square at 120, 40 filled red, +/// with `look`'s keys added to it. +fn install(id: &str, look: serde_json::Value) { + let module = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest(id), &output(120.0, &look))).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); +} + +/// Installs live-effect plug-in `id` as [`install`] does, except that it returns the square at 160, +/// 40 when its input holds the text `moved`. +fn install_moving(id: &str, look: serde_json::Value, moved: &str) { + use vectorcraft_plugins::wat as tpl; + let module = tpl::when_given_else(&manifest(id), tpl::Given::Input, moved, &output(160.0, &look), &output(120.0, &look)); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(module).unwrap()).unwrap(); +} + +/// A document with a blue rectangle over all of it and, above it, the square at `x`, 40 filled +/// green with live-effect plug-in `plugin` as its own effect. +fn document(plugin: &str, x: f64) -> Document { + let mut d = Document::new(300.0, 100.0); + let l = d.layers[0].id; + let blue = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 100.0)), + Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0), + ); + d.insert(Some(l), 0, blue).unwrap(); + let mut ap = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + ap.effects = vec![Effect { id: format!("plugin.{plugin}"), params: json!({}), visible: true }]; + let n = Node::path(d.alloc_id(), square_at(x), ap); + d.insert(Some(l), usize::MAX, n).unwrap(); + d +} + +/// The color a new renderer draws `d` with at (`x`, `y`). +fn pixel(d: &Document, x: f64, y: f64) -> [u8; 4] { + pixel_with(&mut Renderer::new(), d, x, y) +} + +/// The color renderer `r` draws `d` with at (`x`, `y`). +fn pixel_with(r: &mut Renderer, d: &Document, x: f64, y: f64) -> [u8; 4] { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + r.render(d, 1, 1, Affine::translate((-x, -y)), &opts).pixel(0, 0) +} + +fn near(got: [u8; 4], want: [u8; 3]) -> bool { + got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8) +} + +/// A piece at 50% opacity with Multiply draws red multiplied with the blue under it (black) at +/// half strength: half blue. Moved in the same document and drawn by the same renderer, the source +/// runs the plug-in again, which now returns the square at 160, 40, and the new piece draws the +/// same way. Without the look the piece is plain red. +#[test] +fn a_piece_s_opacity_and_blending_mode_draw_and_survive_a_rerun() { + const ID: &str = "test.render.paintedlook.multiply"; + install_moving(ID, json!({"opacity": 0.5, "blend": "Multiply"}), "33.25"); + let mut d = document(ID, 0.0); + let source = d.layers[0].children().and_then(|c| c.last()).map(|n| n.id).unwrap(); + let mut r = Renderer::new(); + let p = pixel_with(&mut r, &d, 130.0, 50.0); + assert!(near(p, [0, 0, 128]), "before the move: {p:?}"); + assert!(near(pixel_with(&mut r, &d, 10.0, 50.0), [0, 0, 255]), "the source is not drawn"); + d.node_mut(source).unwrap().transform(Affine::translate((33.25, 0.0)), false); + let p = pixel_with(&mut r, &d, 170.0, 50.0); + assert!(near(p, [0, 0, 128]), "after the move: {p:?}"); + assert!(near(pixel_with(&mut r, &d, 130.0, 50.0), [0, 0, 255]), "the earlier piece is not drawn"); + assert!(near(pixel_with(&mut r, &d, 43.0, 50.0), [0, 0, 255]), "the moved source is not drawn"); + assert_eq!(vectorcraft_plugins::effect::last_error(ID), None); + install(ID, json!({})); + assert!(near(pixel(&document(ID, 4.0), 130.0, 50.0), [255, 0, 0])); + vectorcraft_plugins::registry::remove(ID); +} + +/// A piece's geometry effect reshapes it: Offset Path by 10 pt draws red 5 pt left of the square. +#[test] +fn a_piece_s_geometry_effect_draws_on_it() { + const ID: &str = "test.render.paintedlook.offset"; + install(ID, json!({"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]})); + let d = document(ID, 0.0); + assert!(near(pixel(&d, 115.0, 50.0), [255, 0, 0]), "{:?}", pixel(&d, 115.0, 50.0)); + assert!(near(pixel(&d, 130.0, 50.0), [255, 0, 0])); + vectorcraft_plugins::registry::remove(ID); +} + +/// An unknown blending mode, a plug-in effect (this one itself) and too many effects refuse the +/// whole result: the source draws as it is, green at its own place, with no piece, and the plug-in +/// reports the field. +#[test] +fn a_refused_look_leaves_the_source_unchanged() { + for (name, look, field) in [ + ("blend", json!({"blend": "multiply"}), "objects[0].blend"), + ("self", json!({"effects": [{"id": "plugin.test.render.paintedlook.self"}]}), "objects[0].effects[0]"), + ("many", json!({"effects": vec![json!({"id": "stylize.dropShadow"}); 17]}), "objects[0].effects"), + ] { + let id = format!("test.render.paintedlook.{name}"); + install(&id, look); + let d = document(&id, 0.0); + assert!(near(pixel(&d, 10.0, 50.0), [0, 255, 0]), "{name}: the source draws"); + assert!(near(pixel(&d, 130.0, 50.0), [0, 0, 255]), "{name}: no piece"); + let e = vectorcraft_plugins::effect::last_error(&id).unwrap_or_default(); + assert!(e.contains(field), "{name}: {e}"); + vectorcraft_plugins::registry::remove(&id); + } +} diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 6d4713930c..738fd44488 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -206,16 +206,18 @@ fn outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_show let r = outline(&d); assert!(inked(&r, 20, 15), "a placed document with a color adjustment is crossed"); assert!(!inked(&r, 50, 20), "and none of its file's art is drawn"); - // A Transform effect reshapes the file's art, read when the crossed box was drawn: its rectangle - // is drawn moved 40 points down to (10, 50)–(90, 90), its bottom edge at y = 90, with no cross - // through it ((20, 55) is on its diagonal) or where the box was. + // A Transform effect reshapes the crossed box: it is drawn moved 40 points down to + // (10, 50)–(90, 90), its bottom edge at y = 90 and crossed ((20, 55) is on its diagonal), with + // nothing where the box was and none of the file's art ((50, 60) is the top edge of the box the + // file places in itself, moved). let mut d = doc_with("outline-cross-4", b"loop"); assert!(inked(&outline(&d), 20, 15), "first drawn crossed"); let params = serde_json::json!({"moveV": 40}); d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); let r = outline(&d); - assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the file's art is drawn moved"); - assert!(!inked(&r, 20, 55), "uncrossed"); + assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the box is drawn moved"); + assert!(inked(&r, 20, 55), "crossed"); + assert!(!inked(&r, 50, 60), "without the file's art"); assert!(!inked(&r, 20, 15), "and nothing is drawn where the box was"); // The same when the box was first drawn crossed with a drop shadow. let mut d = doc_with("outline-cross-5", b"loop"); @@ -229,7 +231,125 @@ fn outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_show let params = serde_json::json!({"moveV": 40}); d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); let r = outline(&d); - assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the file's art is drawn moved after a drop shadow"); + assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the box is drawn moved after a drop shadow"); + assert!(inked(&r, 20, 55), "and crossed"); +} + +#[test] +fn outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects() { + let outline = |r: &mut Renderer, d: &Document| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let inked = |r: &Rendered, x: u32, y: u32| r.pixel(x, y)[0] < 200; + // The box (10, 10)–(90, 50) in a group whose Transform effect moves it 40 points down: crossed at + // (10, 50)–(90, 90), whose diagonal from the top left passes (20, 55). The file places itself in + // its middle: moved, the top edge of that box passes (50, 60). + let mut d = doc_with("outline-group-1", b"loop"); + let placed = d.remove(NodeId(50)).unwrap(); + let mut group = Node::group(NodeId(80), vec![placed]); + let params = serde_json::json!({"moveV": 40}); + group.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut r = Renderer::new(); + let crossed = outline(&mut r, &d); + assert!(inked(&crossed, 20, 55), "the moved box is crossed"); + assert!(!inked(&crossed, 50, 60), "without the file's art"); + assert!(!inked(&crossed, 20, 15), "and nothing is drawn where the box was"); + // With Show Images in Outline Mode the same renderer draws the file's art moved, not the art it + // kept for the crossed box, and back again without it. + d.setup.outline_images = true; + let shown = outline(&mut r, &d); + assert!(!inked(&shown, 20, 55), "with Show Images in Outline Mode the box is not crossed"); + assert!(inked(&shown, 50, 60), "and the file's art is drawn moved"); + assert!(shown.pixels == outline(&mut Renderer::new(), &d).pixels, "as a new renderer draws it"); + d.setup.outline_images = false; + assert!(outline(&mut r, &d).pixels == crossed.pixels, "crossed again as at first"); +} + +#[test] +fn a_template_layer_in_outline_mode_draws_a_placed_documents_art_its_effects_reshape() { + // A template layer stays in Preview in Outline mode: the file's blue art moved 40 points down + // by a Transform effect fills (10, 50)–(90, 90), and is not crossed. + let mut d = doc_with("outline-template-1", b"blue"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + if let NodeKind::Layer { template, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *template = true; + } + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + let [red, _, blue, _] = r.pixel(50, 80); + assert!(blue > red, "the file's art fills the moved box: {:?}", r.pixel(50, 80)); + // The same with the Transform effect on the template layer itself. + let effect = d.node_mut(NodeId(50)).unwrap().appearance.effects.pop().unwrap(); + Arc::make_mut(&mut d.layers[0]).appearance.effects.push(effect); + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + let [red, _, blue, _] = r.pixel(50, 80); + assert!(blue > red, "the layer's effect moves the file's art: {:?}", r.pixel(50, 80)); +} + +#[test] +fn outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame() { + // A file that can't be read, in the box (10, 10)–(90, 50), moved 40 points down by a Transform + // effect: crossed at (10, 50)–(90, 90). The view shows the document from y = 55 down, below + // where the box is without the effect; the moved box's diagonal from the top left passes + // (30, 60), the pixel (30, 5). + let mut d = doc_with("outline-cull-1", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let outline = RenderOptions { outline: true, ..preview.clone() }; + let mut r = Renderer::new(); + r.render(&d, 100, 100, view, &preview); + let crossed = r.render(&d, 100, 100, view, &outline); + assert!(crossed.pixel(30, 5)[0] < 200, "the moved box is drawn crossed after a frame in Preview"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, view, &outline).pixels, "as a new renderer draws it"); + // In Preview, a layer whose Preview is off draws in outline: the same. + if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *preview = false; + } + let r = Renderer::new().render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a layer whose Preview is off"); + // And in a sublayer whose Preview is off, in a layer whose Preview is on. + if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *preview = true; + } + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let l = d.layers[0].id; + d.insert(Some(l), 0, sub).unwrap(); + let mut r = Renderer::new(); + r.render(&d, 100, 100, view, &outline); + let r = r.render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a sublayer whose Preview is off"); +} + +#[test] +fn an_edit_in_outline_mode_redraws_where_the_effects_move_the_crossed_box() { + // A file that can't be read, in the box (10, 10)–(90, 50): a Transform effect added to it moves + // the crossed box 40 points down, to (10, 50)–(90, 90). + let old = doc_with("outline-changed-1", b"bad"); + let mut new = old.clone(); + let params = serde_json::json!({"moveV": 40}); + new.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, 100, 100, Affine::IDENTITY, &opts); + match r.changed(&old, &new, &opts) { + crate::changed::Changed::Area(a) => assert!(a.y1 >= 89.0, "the area reaches the moved box: {a:?}"), + other => panic!("an area, not {other:?}"), + } } #[test] @@ -272,6 +392,82 @@ fn an_enveloped_placed_document_shows_its_file_once_read() { assert!(after == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); } +#[test] +fn outline_mode_warps_an_enveloped_placed_documents_crossed_box() { + let outline = |r: &mut Renderer, d: &Document| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts).pixels + }; + // An Arc warp of the box (10, 10)–(90, 50), once holding the placed document and once holding + // its crossed box as a plain path. + let envelope = |content: Arc| { + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + Node::new( + NodeId(60), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }, + ) + }; + let mut d = doc_with("outline-envelope-1", b"loop"); + let placed = d.remove(NodeId(50)).unwrap(); + let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("a placed document") }; + let crossed = p.crossed_art(&placed); + let l = d.layers[0].id; + d.insert(Some(l), 0, envelope(placed)).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut boxed = d.clone(); + boxed.remove(NodeId(60)).unwrap(); + boxed.insert(Some(l), 0, envelope(Arc::new(crossed))).unwrap(); + let mut r = Renderer::new(); + let warped = outline(&mut r, &d); + assert!(warped == outline(&mut Renderer::new(), &boxed), "the envelope warps the crossed box"); + // With Show Images in Outline Mode the same renderer warps the file's art, and the crossed box + // again without it. + d.setup.outline_images = true; + let shown = outline(&mut r, &d); + assert!(shown != warped, "the file's art is warped"); + assert!(shown == outline(&mut Renderer::new(), &d), "as a new renderer draws it"); + d.setup.outline_images = false; + assert!(outline(&mut r, &d) == warped, "the crossed box again"); +} + +#[test] +fn outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed() { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let inked = |r: &Rendered, x: u32, y: u32| r.pixel(x, y)[0] < 200; + // A blend of the 40×20 file placed at (5, 5) and at (55, 75), with one step between them: its box + // is (30, 40)–(70, 60), and its diagonal from the top left passes (60, 55). The file's art is a + // rectangle the size of the box. + let mut d = Document::new(100.0, 100.0); + d.images.insert("outline-blend-1".into(), ImageBlob::new("application/json", b"blue".to_vec())); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let ends = vec![ + Arc::new(placed_node(51, "outline-blend-1", 40.0, 20.0, Affine::translate((5.0, 5.0)))), + Arc::new(placed_node(52, "outline-blend-1", 40.0, 20.0, Affine::translate((55.0, 75.0)))), + ]; + let spec = vectorcraft_doc::live::BlendSpec { spacing: vectorcraft_doc::live::BlendSpacing::Steps(1), ..Default::default() }; + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(NodeId(60), NodeKind::Blend { children: ends, spec: Box::new(spec) })).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut r = Renderer::new(); + let crossed = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert!(inked(&crossed, 60, 55), "the step between the ends is crossed"); + assert!(inked(&crossed, 15, 10) && inked(&crossed, 65, 80), "and so are the ends"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); + d.setup.outline_images = true; + let shown = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert!(!inked(&shown, 60, 55), "with Show Images in Outline Mode the step is not crossed"); + assert!(inked(&shown, 50, 40), "and its file's art is drawn in outline"); +} + #[test] fn a_placed_document_with_a_drop_shadow_shows_its_file_once_read() { let mut d = doc("shadowed-1"); diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 8d94e6b968..05c9ceaed1 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -290,6 +290,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['exportVariables'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { @@ -310,7 +320,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index dc4249b6a6..bd2b4afc5e 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -76,6 +76,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and @@ -89,8 +92,9 @@ pub(crate) const APP_METHODS: &[&str] = &["executeMenuCommand", "doScript", "loa /// Text an action set written out at run time holds. pub(crate) const ACTION_TEXT: &str = "/actionCount"; -/// Constructors of the language (ECMA-262 3rd edition, section 15) and of E4X (ECMA-357 2nd edition, -/// section 13), and the platform's own: `new` of these is no document-model type. +/// Constructors of the language (ECMA-262 3rd edition, section 15, and the collections and binary +/// data of the 6th edition, sections 22.2 to 24.2) and of E4X (ECMA-357 2nd edition, section 13), and +/// the platform's own: `new` of these is no document-model type. pub(crate) const CONSTRUCTORS: &[&str] = &[ "Object", "Function", @@ -107,6 +111,21 @@ pub(crate) const CONSTRUCTORS: &[&str] = &[ "SyntaxError", "TypeError", "URIError", + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", "Namespace", "QName", "XML", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index dd11c3dd0a..15fe568eb7 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,29 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. +#[test] +fn export_variables_writes_a_file() { + let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); +} + +/// `exportVariables` called with its name as a string literal in brackets writes the file too; +/// reading the method without calling it does not. +#[test] +fn export_variables_in_brackets_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['importVariables'](f);\n", + "app.activeDocument[\"exportVariables\"](f);\n", + "var d = app.activeDocument; d['exportVariables'] (f);\n", + "var n = d['exportVariables'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] @@ -1592,6 +1615,17 @@ fn type_names_compared_or_created_are_listed() { assert_eq!(r.needs, [Need::Dom]); } +#[test] +fn collections_and_typed_arrays_are_not_type_names() { + let r = report(concat!( + "var m = new Map(), s = new Set(), wm = new WeakMap(), ws = new WeakSet();\n", + "var b = new ArrayBuffer(8), v = new DataView(b), u = new Uint8Array(b), c = new Uint8ClampedArray(2);\n", + "var i = [new Int8Array(1), new Int16Array(1), new Uint16Array(1), new Int32Array(1), new Uint32Array(1)];\n", + "var f = [new Float32Array(1), new Float64Array(1)];\n", + )); + assert!(r.types.is_empty(), "{:?}", r.types.iter().map(|t| t.name.as_str()).collect::>()); +} + #[test] fn menu_commands_are_counted_with_their_lines() { let r = report(concat!( diff --git a/crates/text/build.rs b/crates/text/build.rs index 28669285e3..7863efe464 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -1,7 +1,9 @@ //! The optional craft-fonts build input (https://github.com/storytold/craft-fonts, //! `docs/integration.md`): with `CRAFT_FONTS_DIR=` set, every font in its //! `fonts/manifest.txt` is embedded as `CRAFT_FONTS` (the framework's `craft_fonts_build::Embed`); -//! unset, `CRAFT_FONTS` is empty and the app uses its own and the installed fonts. +//! unset, `CRAFT_FONTS` is empty and the app uses its own and the installed fonts. Desktop builds +//! also embed the Noto Sans Condensed SemiBold row of the checkout's `fonts/latin-manifest.txt` +//! (`Embed::tab_face`), which document tab titles draw in; a checkout without it gives a warning. //! `CRAFT_FONTS_REQUIRED=1` turns a bad checkout into a build error (release builds). Nothing is //! fetched: the build reads only the local checkout. //! @@ -40,7 +42,10 @@ fn main() { None => embed, } }; - if let Err(e) = fonts().filter(move |f| !wasm || (f.family == WEB_FONT.0 && f.style == WEB_FONT.1)).write("craft_fonts.rs") { + // Desktop builds also embed the checkout's condensed face for document tab titles. + let embedded = fonts().filter(move |f| !wasm || (f.family == WEB_FONT.0 && f.style == WEB_FONT.1)); + let embedded = if wasm { embedded } else { embedded.tab_face() }; + if let Err(e) = embedded.write("craft_fonts.rs") { println!("cargo::error={e}"); } let mut web = String::new(); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 7e64490b3f..28b2dc2662 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -72,6 +72,7 @@ fn japanese_document_fonts_from(fonts: &[EmbeddedFace]) -> Vec<&EmbeddedFace> { /// first: the fallback for Arabic text; the other families are picked by name), then the Thai ones /// (Noto Sans Thai: the fallback for Thai text where no Thai font is installed, and on the web), /// then the Georgian ones (Noto Sans Georgian, the same for Georgian). Remaining faces follow in manifest order, so every explicitly supplied family can be selected. +/// The tab-title face (role `tab`), which only document tab titles draw in, is left out. /// Empty when built without craft-fonts. pub fn document_fonts() -> Vec<&'static EmbeddedFace> { document_fonts_from(CRAFT_FONTS) @@ -79,7 +80,9 @@ pub fn document_fonts() -> Vec<&'static EmbeddedFace> { fn document_fonts_from(fonts: &[EmbeddedFace]) -> Vec<&EmbeddedFace> { let mut v = japanese_document_fonts_from(fonts); - let rest = |f: &&EmbeddedFace, earlier: &[&str]| !f.has_script("Jpan") && !earlier.iter().any(|s| f.has_script(s)); + let rest = |f: &&EmbeddedFace, earlier: &[&str]| { + f.role != Some(craft_fonts_build::TAB_ROLE) && !f.has_script("Jpan") && !earlier.iter().any(|s| f.has_script(s)) + }; v.extend(fonts.iter().filter(|f| f.has_script("Arab") && rest(f, &[]))); v.extend(fonts.iter().filter(|f| f.has_script("Thai") && rest(f, &["Arab"]))); v.extend(fonts.iter().filter(|f| f.has_script("Geor") && rest(f, &["Arab", "Thai"]))); @@ -131,6 +134,14 @@ mod tests { assert!(document_fonts_from(&[]).is_empty()); } + #[test] + fn document_fonts_leave_out_the_tab_title_face() { + let latin = EmbeddedFace { family: "Latin", style: "Regular", scripts: &["Latn"], index: 0, bytes: &[], role: None }; + let tab = EmbeddedFace { family: "Noto Sans", style: "Condensed SemiBold", role: Some(craft_fonts_build::TAB_ROLE), ..latin }; + let listed: Vec<_> = document_fonts_from(&[latin, tab]).into_iter().map(|f| f.family).collect(); + assert_eq!(listed, ["Latin"]); + } + #[test] fn web_fonts_follow_the_list() { if CRAFT_FONTS.is_empty() { diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index dd26fa28f0..5871d07126 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -171,7 +171,7 @@ mod tests { (TYPE, &["editing"]), (&["puppetWarp"], &["pins", "selected"]), // With nothing queued, `current` (0) is no file's index either. - (&["place"], &["count", "current", "name", "width", "height", "names"]), + (&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]), ]; let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); // Tools that `create` makes and the catalog doesn't list. diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 813ec99429..84f6ee1bad 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -9,9 +9,18 @@ use vectorcraft_geom::{Point, Rect}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +/// Private cursor metadata: the original queue entry for a placement request. The frontend +/// consumes it before opening import options; the engine removes it before direct placement. +pub const SOURCE_INDEX: &str = "__placeSourceIndex"; + +/// Whether a cursor placement was a click under the pointer tolerance, rather than a drag. +pub const CLICK: &str = "__placeCursorClick"; + /// One loaded file. #[derive(Clone, Debug, PartialEq)] struct Entry { + /// Its position in the original load, retained when other entries are discarded. + source_index: usize, /// `file.place` params (the file and its options). params: Value, name: String, @@ -93,9 +102,12 @@ impl Tool for PlaceTool { let Some((a, _)) = self.drag.take() else { return vec![] }; let (Some(r), Some(e)) = (self.target(a, ev.pos, cx.tol(3.0)), self.entry()) else { return vec![] }; let mut p = e.params.clone(); + p[SOURCE_INDEX] = json!(e.source_index); + let clicked = (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0); + p[CLICK] = json!(clicked); p["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); // A Shift-click (not a drag) asks for the file's import options before placing it. - if ev.mods.shift && (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0) { + if ev.mods.shift && clicked { p["showImportOptions"] = json!(true); } let mut acts = vec![Action::Exec("file.place".into(), p)]; @@ -141,12 +153,13 @@ impl Tool for PlaceTool { Cursor::Crosshair } - /// `{count, current, name, width, height, names}`: what the cursor holds (no file data). + /// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data). fn options(&self) -> Value { let e = self.entry(); json!({ "count": self.entries.len(), "current": self.current, + "sourceIndex": e.map(|e| e.source_index), "name": e.map(|e| &e.name), "width": e.map(|e| e.width), "height": e.map(|e| e.height), @@ -163,8 +176,10 @@ impl Tool for PlaceTool { .as_array() .into_iter() .flatten() - .filter_map(|e| { + .enumerate() + .filter_map(|(source_index, e)| { Some(Entry { + source_index, params: e.get("params").filter(|p| p.is_object())?.clone(), name: e["name"].as_str().unwrap_or_default().to_string(), width: e["width"].as_f64().filter(|v| v.is_finite())?, @@ -277,14 +292,26 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0)); - assert_eq!(acts, vec![Action::Exec("file.place".into(), json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0]}))]); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0]}) + )] + ); // A drag up and to the left grows the box from the press point, aspect kept. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0)); let c_marquee_only = ToolContext { measurement_labels: false, ..c }; assert_eq!(t.overlays(&c_marquee_only), vec![Overlay::Marquee(Rect::new(20.0, 60.0, 100.0, 100.0))]); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); assert_eq!(t.options()["count"], 1); // Placing the last file returns to the previous tool. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); @@ -302,18 +329,30 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0).with_mods(shift)); - let asked = json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); + let asked = json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); assert_eq!(acts, vec![Action::Exec("file.place".into(), asked)]); assert_eq!(t.options()["names"], json!(["f1.png", "f2.png"]), "the cursor goes on to the next file"); // A Shift-drag places at the dragged size, as a drag does. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0).with_mods(shift)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0).with_mods(shift)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); // Shift released before the button: a plain click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f2.png", "rect": [0.0, 0.0, 40.0, 20.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + ) + ); assert_eq!(acts.last(), Some(&Action::SwitchTool("pen".into()))); // An empty cursor places nothing on a Shift-click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); @@ -359,4 +398,29 @@ mod tests { t.key(&c, ToolKey::Escape, Mods::default()); assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]); } + + #[test] + fn source_indices_survive_removal_in_cursor_requests() { + let (d, _) = doc_with_rect(); + let (s, p) = (Default::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = loaded(3); + t.key(&c, ToolKey::Right, Mods::default()); + assert_eq!(t.options()["sourceIndex"], 1); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!((t.options()["current"].clone(), t.options()["sourceIndex"].clone()), (json!(1), json!(2))); + t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); + let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + )] + ); + assert_eq!(t.options()["sourceIndex"], 0); + assert!(t.check_option("sourceIndex", &json!(0)).is_err(), "the source identity is read only"); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(t.options()["sourceIndex"], Value::Null); + } } diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index 5e820e5f35..f24542b81d 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,6 +1,7 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners //! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which -//! can also take every other anchor, or only the corners in an angle range). +//! can also take every other anchor, or only the corners in an angle range). Canceling a Radius edit +//! or Corner choice restores its opening tool value; a retired edit supplies no replacement. use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, Sizing, clicked}; @@ -55,12 +56,12 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { let mut set: Option = None; let radius_field = |ui: &mut Ui| { let field = fields::size_field(ui, tl!("Radius"), Some(radius), lengths).range(0.0..=MAX_RADIUS); - typed(field.show(ui).value()) + typed(field.show(ui).events.landed()) }; if let Some(v) = row(ui, "Radius", "corner-tool-radius", radius_field) { set = Some(json!({ "radius": v })); } - let kind_field = |ui: &mut Ui| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).value().copied(); + let kind_field = |ui: &mut Ui| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).events.landed().copied(); if let Some(k) = row(ui, "Corner", "corner-tool-kind", kind_field) { set = Some(json!({ "kind": k })); } @@ -76,3 +77,81 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, super::set_corners::COMMAND, json!({})); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_tools::addons::shared_edge; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.setOption", json!({"tool": ID, "values": {"radius": 12.5, "kind": "round"}})).unwrap(); + app.run("tool.setOption", json!({"tool": shared_edge::ID, "values": {"diameter": 14.25, "tolerance": 0.5}})).unwrap(); + app + } + + #[test] + fn canceling_a_corner_kind_popup_restores_the_tools_complete_options() { + let mut panel = Panel::new(app(), section); + let before = panel.app().session.tool_options_of(ID); + let doc = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = panel.app().session.tool_options_of(ID); + assert_ne!(proposed["kind"], before["kind"], "the choice previews the next corner kind"); + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(ID), before); + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(ID), proposed, "Enter accepts the new tool setting"); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "tool settings do not edit the drawing"); + } + + #[test] + fn canceling_an_option_text_edit_restores_options_and_enter_keeps_accepted_edits() { + for (draw, tool, label, key, typed) in [ + (section as fn(&mut VectorcraftApp, &mut Ui), ID, "Radius", "radius", "19.75"), + (super::super::shared_edge::section, shared_edge::ID, "Diameter", "diameter", "28.5"), + (super::super::shared_edge::section, shared_edge::ID, "Coincidence", "tolerance", "0.75"), + ] { + for cancel in [false, true] { + let mut panel = Panel::new(app(), draw); + let before = panel.app().session.tool_options_of(tool); + let doc = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(typed); + panel.frame(); + let proposed = panel.app().session.tool_options_of(tool); + assert_ne!(proposed[key], before[key], "{label} changes while typing"); + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(tool), before, "{label} restores on Escape"); + } else { + panel.key(Key::Enter, Modifiers::NONE); + } + panel.frame(); + assert_eq!(panel.app().session.tool_options_of(tool), if cancel { before } else { proposed }); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "{label} only changes future tool options"); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools/shared_edge.rs b/crates/ui-egui/src/addons/pathtools/shared_edge.rs index 0aeb9e17eb..a3d977cb94 100644 --- a/crates/ui-egui/src/addons/pathtools/shared_edge.rs +++ b/crates/ui-egui/src/addons/pathtools/shared_edge.rs @@ -1,5 +1,6 @@ //! The Anchor Inspector panel's Shared Edges section: the Shared Edge Merge Tool's brush and -//! coincidence, and Keep Shared Points Together. +//! coincidence, and Keep Shared Points Together. Canceling a Diameter or Coincidence edit restores +//! its opening tool value; a retired edit supplies no replacement. use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _}; @@ -31,14 +32,14 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { let mut set: Option = None; let diameter_field = |ui: &mut Ui| { let field = NumberField::new(tl!("Diameter"), Bind::given(Some(diameter))).range(DIAMETER_RANGE.0..=DIAMETER_RANGE.1); - typed(field.unit_kind(UnitKind::Points).fixed_decimals(2).show(ui).value()) + typed(field.unit_kind(UnitKind::Points).fixed_decimals(2).show(ui).events.landed()) }; if let Some(v) = row(ui, "Diameter", "shared-edge-diameter", diameter_field) { set = Some(json!({ "diameter": v })); } let coincidence_field = |ui: &mut Ui| { let field = NumberField::new(tl!("Coincidence"), Bind::given(Some(tolerance))).range(0.0..=MAX_COINCIDENCE); - typed(field.unit_kind(UnitKind::Points).fixed_decimals(3).show(ui).value()) + typed(field.unit_kind(UnitKind::Points).fixed_decimals(3).show(ui).events.landed()) }; if let Some(v) = row(ui, "Coincidence", "shared-edge-tolerance", coincidence_field) { set = Some(json!({ "tolerance": v })); diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index c2879f7566..24d8d787b9 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -170,7 +170,11 @@ impl Component for CanvasDrops<'_> { } if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. - let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); + let panel = Target::new(rect, view, covered, |p: &PanelDrag| match p { + PanelDrag::Art { .. } => None, + PanelDrag::Appearance { document, .. } if *document != self.document => None, + _ => Some(Payload::Panel(p.clone())), + }); let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); let brush = Target::new(rect, view, covered, |d: &ListDrag| { @@ -340,7 +344,9 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { - None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})), + None if brush_has_art(app, key) && no_art_at(app, at, zoom) => { + run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})) + } None => Ok(()), Some(hit) => { let owner = owner(app, &hit)?; @@ -354,6 +360,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), + // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile art with its tile. + Payload::Panel(PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) + if hit().is_none() && no_art_at(app, at, zoom) => + { + run(app, "pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) + } Payload::Panel(drag @ PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" @@ -382,7 +394,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), } run(app, cmd, params) } - Payload::Panel(PanelDrag::Appearance(source)) => { + Payload::Panel(PanelDrag::Appearance { document, source }) if app.session.active().is_some_and(|st| st.uid == *document) => { let Some(hit) = hit() else { return Ok(()) }; let target = top_object(app, &hit)?; if target == source.0 { @@ -420,6 +432,16 @@ fn brush_has_art(app: &VectorcraftApp, key: &BrushKey) -> bool { .is_some_and(|v| matches!(v["type"].as_str(), Some("scatter" | "art" | "pattern"))) } +/// Whether no art is under document point `p` at `zoom`, with fills counted even with Object Selection by Path Only and +/// type objects by their area even with Type Object Selection by Path Only: a brush's or a pattern swatch's art is +/// placed only there. +fn no_art_at(app: &VectorcraftApp, p: Point, zoom: f64) -> bool { + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..opt }) + }) + .is_none() +} + /// The selected, editable gradient mesh and its points that a solid color dropped at document /// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh /// (fills count even with Object Selection by Path Only, and clipping applies), and the points are diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a09e1e4424..463adbaf98 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -152,12 +152,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(PanelDrag::paint(Paint::Gradient(Box::new(gradient)))), on_b, Move).unwrap(); assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none()), "a gradient fits the object it lands on"); app.run("transparency.set", json!({"opacity": 40})).unwrap(); - drop_at(&mut app, Payload::Panel(PanelDrag::Appearance(a)), on_b, Move).unwrap(); + let document = app.session.active().unwrap().uid; + let appearance = |source| Payload::Panel(PanelDrag::Appearance { document, source }); + drop_at(&mut app, appearance(a), on_b, Move).unwrap(); let doc = &app.session.active().unwrap().doc; let (na, nb) = (doc.node(a).unwrap(), doc.node(b).unwrap()); assert_eq!((&nb.appearance, nb.opacity), (&na.appearance, na.opacity), "the appearance is copied"); let n = undo_len(&app); - drop_at(&mut app, Payload::Panel(PanelDrag::Appearance(b)), on_b, Move).unwrap(); + drop_at(&mut app, appearance(b), on_b, Move).unwrap(); assert_eq!(undo_len(&app), n, "dropped on its own source: nothing changes"); let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); @@ -202,6 +204,64 @@ fn a_drop_runs_the_effect_of_its_payload() { symbol_at(&app, empty); } +/// With Object Selection by Path Only, a point inside a filled rectangle and away from its outline is still on art: +/// a brush with art places nothing there. +#[test] +fn a_brush_with_art_dropped_inside_a_fill_with_path_only_places_nothing() { + let (mut app, _ctx) = app_with_canvas(); + app.run("shape.rectangle", json!({"x": 250, "y": 200, "width": 100, "height": 80})).unwrap(); + app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let uid = app.session.active().unwrap().uid; + let n = undo_len(&app); + drop_at(&mut app, Payload::Brush(BrushKey { doc: uid, name: "Arrow".into(), group: false }), Point::new(300.0, 240.0), DropOperation::Move) + .unwrap(); + assert_eq!(undo_len(&app), n, "{}", app.ui.status); +} + +/// A pattern swatch of the Swatches panel dropped where there is no art places a copy of its tile art and tile there, +/// centered on the drop point and selected, in one undo step; a color swatch, a pattern from elsewhere and a drop +/// inside a fill with Object Selection by Path Only place nothing, and a drop on art fills it. +#[test] +fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { + use crate::panel_drag::SwatchRows; + let (mut app, _ctx) = app_with_canvas(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let tile = app.run("shape.rectangle", json!({"x": 300, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [tile], "name": "Checks", "edit": false})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let document = app.session.active().unwrap().uid; + let swatch = |name: &str, paint: Paint| { + let rows = SwatchRows { document, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + Payload::Panel(PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }) + }; + let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); + let off = Point::new(250.0, 220.0); + let n = undo_len(&app); + drop_at(&mut app, swatch("Red", Paint::solid(Color::from_hex("#ed1c24").unwrap())), off, DropOperation::Move).unwrap(); + let elsewhere = Payload::Panel(PanelDrag::paint(vectorcraft_doc::pattern::pattern_paint("Checks"))); + drop_at(&mut app, elsewhere, off, DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), n, "a color swatch and a pattern from elsewhere place nothing"); + drop_at(&mut app, pattern.clone(), off, DropOperation::Move).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(undo_len(&app), n + 1); + assert_eq!(st.history.undo.last().unwrap().label, "Place Pattern Art"); + let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; + let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); + assert!((b.center() - off).hypot() < 0.1, "{b:?}"); + let inside = Point::new(100.0, 100.0); + app.run("paint.setFill", json!({"ids": [id], "color": "#ffffff"})).unwrap(); + app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let n = undo_len(&app); + drop_at(&mut app, pattern.clone(), inside, DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), n, "inside a fill with Object Selection by Path Only is still on art"); + app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + drop_at(&mut app, pattern, inside, DropOperation::Move).unwrap(); + let fill = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().appearance.fill_paint(); + assert!(matches!(&fill, Paint::Pattern { pattern, .. } if pattern == "Checks"), "{fill:?}"); +} + #[test] fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { let (mut app, ctx) = app_with_canvas(); @@ -551,3 +611,27 @@ fn an_anchor_dragged_off_the_canvas_is_not_carried() { frame(&mut app, &ctx, vec![]); assert!(craft::ui::runtime::drag::active::(&ctx).is_none()); } + +#[test] +fn a_foreign_appearance_drop_never_copies_a_matching_local_object() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let source = add(&mut app, 20); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = add(&mut app, 20); + assert_eq!(source, other, "both documents have different objects with the same local ID"); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + drop_at(&mut app, Payload::Panel(PanelDrag::Appearance { document, source }), Point::new(250.0, 70.0), DropOperation::Move).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "a foreign appearance drop makes no edit"); +} diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 4ea015bac6..4464e67326 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -1,5 +1,4 @@ use std::collections::BTreeSet; -use std::time::Duration; use craft::behavior::CanvasView; use craft::ui::primitives::textures::{CachedTexture, TextureState}; @@ -140,7 +139,8 @@ fn has_picture(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, uid: u64) /// Run frames with `run` until window `w`'s pane has its picture and the upload of it was seen, /// starting from the uploads `seed` holds → the picture and its pixels and size as uploaded. The uploads are handled -/// once read. +/// once read. The test context runs the pictures' renders in line ([`crate::testing::ui_context`]), so a picture asked +/// for in one frame is ready and uploaded within [`READY_FRAMES`] frames on every run. fn wait_ready( app: &mut VectorcraftApp, ctx: &egui::Context, @@ -150,7 +150,7 @@ fn wait_ready( ) -> (CachedTexture, (Vec, [usize; 2])) { let uid = app.session.documents()[w.0].uid; let mut uploads = seed; - for _ in 0..400 { + for frames in 0..=READY_FRAMES { if let TextureState::Ready(texture) = picture_of(app, ctx, w, uid) && (uploads.iter().flat_map(|d| d.set.iter()).any(|e| *e.0 == texture.id) || UPLOADED.with(|u| u.borrow().contains_key(&texture.id))) { @@ -159,13 +159,18 @@ fn wait_ready( uploads.iter_mut().for_each(note_uploads); return (texture, picture); } + if frames == READY_FRAMES { + break; + } let mut out = run(app); uploads.push(std::mem::take(&mut out.textures_delta)); - std::thread::sleep(Duration::from_millis(5)); } - panic!("the pane of window {w:?} never got its picture"); + panic!("the pane of window {w:?} did not get its picture within {READY_FRAMES} frames"); } +/// The frames [`wait_ready`] runs for a pane's picture at most. +const READY_FRAMES: usize = 4; + /// The picture `id` as `uploads` uploaded it, else as a frame of [`frame_in`] did: its pixels and size. fn uploaded(uploads: &[egui::TexturesDelta], id: egui::TextureId) -> (Vec, [usize; 2]) { let image = uploads.iter().rev().flat_map(|d| d.set.iter()).find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| d.image.clone()); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index b96cb93038..9d1cdcb417 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -584,11 +584,14 @@ fn report_deferred(app: &mut VectorcraftApp, effects: &vectorcraft_plugins::defe } } -/// Start the render worker, and upload the frame it finished. +/// Start the render worker, and upload the frame it finished. In unit tests no worker thread +/// starts and every frame renders on this thread, as with `VECTORCRAFT_SYNC_RENDER` set: a test +/// that needs a worker gives the canvas one whose frames it finishes itself +/// ([`crate::render_worker::Worker::test_channel`]). pub(super) fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { if !app.canvas.worker_started { app.canvas.worker_started = true; - if std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() { + if !cfg!(test) && std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() { app.canvas.worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); app.canvas.fill_worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); } @@ -710,6 +713,42 @@ struct Frame<'a> { /// shows the document's paper without the art: about a frame at 60 Hz. pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); +/// How long a render on this thread that began at `t0` ([`monotonic_ms`]) took, in milliseconds. +#[cfg(not(test))] +fn render_ms(t0: f64) -> f64 { + monotonic_ms() - t0 +} + +/// How long the UI thread waits for a document's first frame: [`FIRST_FRAME_GRACE`]. +#[cfg(not(test))] +fn first_frame_grace() -> std::time::Duration { + FIRST_FRAME_GRACE +} + +#[cfg(test)] +thread_local! { + /// The time a render on the UI thread takes in unit tests, in milliseconds: what a frame's + /// time decides (whether the next frame is slow) is the same on every run. A test + /// can set it to make the canvas's renders slow or fast. + pub(crate) static TEST_RENDER_MS: std::cell::Cell = const { std::cell::Cell::new(1.0) }; + /// How long the UI thread waits for a document's first frame in unit tests: none, so only a + /// frame the test finished before it lands in the wait. A test that answers the job from + /// another thread sets [`std::time::Duration::MAX`] to wait for that answer. + pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell = const { std::cell::Cell::new(std::time::Duration::ZERO) }; +} + +/// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds. +#[cfg(test)] +fn render_ms(_t0: f64) -> f64 { + TEST_RENDER_MS.with(std::cell::Cell::get) +} + +/// [`first_frame_grace`] in unit tests: the time [`TEST_FIRST_FRAME_GRACE`] holds. +#[cfg(test)] +fn first_frame_grace() -> std::time::Duration { + TEST_FIRST_FRAME_GRACE.with(std::cell::Cell::get) +} + /// 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. @@ -760,7 +799,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; + app.perf.render_ms = render_ms(t0); true } @@ -855,7 +894,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // A light document's first frame is ready within the grace and shows in this frame, // with no frame of bare paper. Waited for once, when the frame is queued. if first && queued { - landed = worker.wait(FIRST_FRAME_GRACE); + landed = worker.wait(first_frame_grace()); } } _ => { @@ -868,7 +907,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); - app.perf.render_ms = monotonic_ms() - t0; + app.perf.render_ms = render_ms(t0); app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; let stats = app.canvas.renderer.stats; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index b3917613b8..a1613565bb 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -6,6 +6,7 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::CanvasSpace; use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang}; use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger}; +use craft::ui::display::Text; use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; @@ -465,8 +466,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac if *cmd == TASK_BAR_FIDELITY { // The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped. if let Some(v) = offer.fidelity { - // PLAN: assumed `freehand::fidelity_field` draws no label of its own - ui.label(*label); + Text::new(*label).show(ui); if let Some(x) = crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth").filter(|x| *x != v) { run = Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}}))); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 651a1bf72b..4857c67064 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6481,24 +6481,64 @@ fn the_render_worker_waits_for_a_frame_only_as_long_as_asked() { let job = jobs.try_recv().expect("a job to finish"); let (mut w, _, done_tx) = crate::render_worker::Worker::test_channel(); - let t0 = std::time::Instant::now(); - assert!(w.wait(std::time::Duration::from_millis(20)).is_none()); - assert!(t0.elapsed() >= std::time::Duration::from_millis(20), "waited the time asked"); + // No frame finishes: the time is up at once. + assert!(w.wait(std::time::Duration::ZERO).is_none(), "nothing once the time is up"); w.pending = Some(job.key.clone()); done_tx.send(finished(&job)).unwrap(); - assert_eq!(w.wait(std::time::Duration::from_secs(5)).map(|d| d.key), Some(job.key.clone()), "finished before the wait"); + assert_eq!(w.wait(super::raster::FIRST_FRAME_GRACE).map(|d| d.key), Some(job.key.clone()), "finished before the wait"); assert!(w.pending.is_none()); + // The frame is sent once both sides reach the barrier; with no time limit, the wait returns + // it whether it arrives before or during the wait. let late = finished(&job); - let sender = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(30)); - done_tx.send(late).unwrap(); + let ready = std::sync::Arc::new(std::sync::Barrier::new(2)); + let sender = std::thread::spawn({ + let ready = ready.clone(); + move || { + ready.wait(); + done_tx.send(late).unwrap(); + } }); - assert!(w.wait(std::time::Duration::from_secs(5)).is_some(), "finished during the wait"); + ready.wait(); + assert!(w.wait(std::time::Duration::MAX).is_some(), "finished during the wait"); sender.join().unwrap(); } +/// A document's first frame that the worker finishes within the wait (`FIRST_FRAME_GRACE`) shows +/// in the frame that queued it, with no frame of bare paper; one that is not finished in time shows +/// once it lands ([`a_documents_first_frame_renders_on_the_worker`]). +#[test] +fn a_first_frame_finished_within_the_wait_shows_in_the_frame_that_queued_it() { + keeping_color_settings(a_first_frame_finished_within_the_wait); +} + +fn a_first_frame_finished_within_the_wait() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + // The worker finishes the job as soon as it receives it, and the canvas waits for it. + super::raster::TEST_FIRST_FRAME_GRACE.with(|g| g.set(std::time::Duration::MAX)); + let answer = std::thread::spawn(move || { + let job = jobs.recv().expect("the first frame is queued on the worker"); + done_tx.send(finished(&job)).unwrap(); + job.key + }); + let ctx = crate::testing::ui_context(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0))), ..Default::default() }; + ctx.run_ui(raw, |ui| show(&mut app, ui)).textures_delta.clear(); + assert!(app.canvas.texture.is_some(), "shown in the frame that queued it"); + assert!(app.canvas.from_worker); + // Dropping the worker ends the answering thread's wait for a job if none was queued. + let worker = app.canvas.worker.take().expect("the worker"); + assert!(worker.pending.is_none(), "the job is done"); + drop(worker); + let key = answer.join().expect("the first frame was queued on the worker"); + assert_eq!(app.canvas.key.as_ref(), Some(&key)); +} + /// An edit to a 3D effect renders the part it changed on this thread, measured by the renderer /// that drew the frame shown ([`vectorcraft_render::Renderer::changed`]): it draws the part with /// the 3D art it made to measure it. diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 9533d48ba7..b1ff81f958 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -8,9 +8,12 @@ //! The ••• button at a toolbar's foot opens the All Tools drawer beside it, and tools dragged from the //! drawer fill it (`edit_toolbar`, with the `toolbar` param of its commands). The + button above it //! opens Add Tool…, a menu of every tool where a click adds the tool at the end, and whose Remove Tool -//! items take tools out: VectorCraft's own way to fill a toolbar without a drag. Each toolbar is listed -//! under Window › Toolbars, where its item shows or hides it. Window › Toolbars › Manage Toolbars (also -//! in the drawer's menu) renames, copies and deletes them. +//! items take tools out: VectorCraft's own way to fill a toolbar without a drag. The same menu's Add +//! Command submenu searches the Command Palette's results and adds a command button after the tools, +//! which runs what the command's menu item runs (`toolbar.addCommand`, `toolbar.removeCommand`); +//! command buttons are VectorCraft's own. Each toolbar is listed under Window › Toolbars, where its +//! item shows or hides it. Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames, +//! copies and deletes them. //! //! Behavior from the public documentation: //! (Create and manage toolbars: New Toolbar @@ -24,10 +27,10 @@ use std::collections::BTreeSet; use craft::behavior::IconId; use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target}; -use craft::ui::buttons::IconButton; +use craft::ui::buttons::{Button, IconButton}; use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::DialogResult; -use craft::ui::display::Divider; +use craft::ui::display::{Divider, Shade, Text}; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedListManager, HostedParamDialog, ListManagerAction, ListManagerChoice, ListManagerEntry, ListManagerWords, Param, @@ -35,6 +38,7 @@ use craft::ui::patterns::form_dialogs::{ }; use craft::ui::rails::RailFooter; use craft::ui::runtime::commands::CommandRef; +use craft::ui::text::TextField; use egui::pos2; use serde_json::{Value, json}; use vectorcraft_tools::tool_info; @@ -47,6 +51,8 @@ use crate::{VectorcraftApp, panel_docking}; pub(crate) const MAX: usize = 64; /// The most characters a toolbar's name has. const MAX_NAME: usize = 200; +/// The most command buttons a toolbar holds. +const MAX_COMMANDS: usize = 200; /// Where the first toolbar made floats, right of the Tools panel; the next ones go lower. const NEW_AT: [f32; 2] = [96.0, 120.0]; /// The kind every Manage Toolbars entry has: all of them rename in place. @@ -179,6 +185,7 @@ fn blank(id: u32, name: String) -> CustomToolbar { slot_tool: Default::default(), double: false, floating: Vec::new(), + commands: Vec::new(), } } @@ -274,8 +281,10 @@ pub(crate) fn delete(app: &mut VectorcraftApp, name: &str) -> Result<(), String> /// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of /// known tools, each once in its toolbar, each group's tool chosen last only when the group holds it, -/// and each with an id of its own: one saved without an id or repeating an earlier toolbar's gets -/// the lowest id nobody holds (a hand-edited preferences file or workspace). +/// at most [`MAX_COMMANDS`] command buttons, each command once and none for a tool, and each with an +/// id of its own: one saved without an id or repeating an earlier toolbar's gets the lowest id nobody +/// holds (a hand-edited preferences file or workspace). A command that is not known now stays: it may +/// be an uninstalled plug-in's. pub(crate) fn sanitize(bars: &mut Vec) { let mut names = BTreeSet::new(); bars.retain_mut(|b| { @@ -285,6 +294,9 @@ pub(crate) fn sanitize(bars: &mut Vec) { s.retain(|id| tool_info(id).is_some() && seen.insert(id.clone())); } b.slots.retain(|s| !s.is_empty()); + let mut commands = BTreeSet::new(); + b.commands.retain(|id| !id.trim().is_empty() && !id.starts_with("tool:") && commands.insert(id.clone())); + b.commands.truncate(MAX_COMMANDS); let old = std::mem::take(&mut b.last_used); for (first, slot) in b.slots.iter().filter_map(|s| Some((s.first()?, s))) { let at = crate::toolbar::slot_id(first); @@ -559,6 +571,41 @@ fn run_choice(app: &mut VectorcraftApp, choice: &ListManagerChoice) { } } +/// The toolbar the `toolbar` param of `toolbar.addCommand` and `toolbar.removeCommand` names, +/// which must be one made with New Toolbar: the Tools panel's toolbar holds tools only. +fn command_target(ui: &UiState, p: &Value) -> Result { + let name = target(ui, p)?.ok_or("toolbar (a toolbar's name) is required: only toolbars made with New Toolbar hold commands")?; + index(ui, &name) +} + +/// Put the command button for the Command Palette result `id` in `bar`, moving it if it is there +/// already: at place `at` among its command buttons (0 = the first; none: at the end). A command +/// that is gone (an uninstalled plug-in's) can still move, but not be added. A tool, and a UI +/// command that fails without params, can't be added. +pub(crate) fn add_command(bar: &mut CustomToolbar, id: &str, at: Option) -> Result<(), String> { + if id.starts_with("tool:") { + return Err(format!("`{id}` is a tool: toolbar.addTool adds tools")); + } + if crate::shortcut_editor::ui_command_needs_params(id) { + return Err(format!("`{id}` needs params, which a click on a button does not give")); + } + if !bar.commands.iter().any(|c| c == id) && !crate::palette::is_command(id) { + return Err(format!("unknown command `{id}`")); + } + let mut list: Vec = bar.commands.iter().filter(|c| *c != id).cloned().collect(); + if list.len() >= MAX_COMMANDS { + return Err(format!("a toolbar holds at most {MAX_COMMANDS} commands")); + } + let at = match at { + None => list.len(), + Some(n) if n <= list.len() => n, + Some(n) => return Err(format!("`at` must be a whole number from 0 to {} (got {n})", list.len())), + }; + list.insert(at, id.to_string()); + bar.commands = list; + Ok(()) +} + /// The commands of the toolbars made with New Toolbar; `None` for other ids. pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { Some(match id { @@ -591,6 +638,25 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| format!("`at` must be 0 or a larger whole number (got {v})"))?, + ), + }; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + add_command(bar, id, at).map(|_| json!(bar.commands)) + })(), + "toolbar.removeCommand" => (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + bar.commands.retain(|c| c != id); + Ok(json!(bar.commands)) + })(), "window.toolbar.dock" => dock(app, p), "window.toolbar.float" => float(app, p), "window.toolbar.list" => { @@ -609,6 +675,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); - let plus = IconButton::new(IconId::new("plus")).label(tl!("Add Tool…")).popup(PopupKind::Menu).show(ui).response; - // The rail measures its footer too: the menu opens from the button the rail shows. - if measured || craft::ui::runtime::measure::active(ui.ctx()) { +/// What a command button shows, worked out before its toolbar's footer is drawn. +#[derive(Clone, Debug)] +struct CommandLook { + /// The Command Palette result it runs. + id: String, + /// Its label, name and command; none while the palette lists no result with its id (an + /// uninstalled plug-in's command). + text: Option, +} + +impl CommandLook { + /// The label the button shows: the command's, or its id while the command is gone. + fn label(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.label.as_str()) + } + + /// Its full name, with the menu path that tells it apart from a command of the same label, or + /// its id while the command is gone. + fn name(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.name.as_str()) + } +} + +/// How each command button of the toolbar with id `id` looks now. +fn command_looks(app: &mut VectorcraftApp, ui: &egui::Ui, id: u32) -> Vec { + let commands = app.ui.custom_toolbars.iter().find(|b| b.id == id).map(|b| b.commands.clone()).unwrap_or_default(); + let texts = crate::palette::button_texts(app, ui, &commands); + commands.into_iter().zip(texts).map(|(id, text)| CommandLook { id, text }).collect() +} + +/// A command button on the toolbar named `bar`: the command's label, cut short with … when it is +/// longer than the toolbar is wide, and its full name and shortcut in its tooltip. A click runs what a +/// pick of the command in the Command Palette runs, and while the command's menu item is dimmed the +/// button is dimmed too. A command that is gone shows its id, dimmed. Its context menu moves it up or +/// down among the toolbar's command buttons (`place`: its place and how many there are) and takes it +/// out; `measuring`: the rail measures its footer, which draws the button alone. +fn command_button(app: &VectorcraftApp, ui: &mut egui::Ui, bar: &str, look: &CommandLook, place: (usize, usize), measuring: bool) { + let shortcut = crate::menus::shortcut_of(app, &look.id).map(|c| c.display(crate::keymap::platform())); + let tip = match (&look.text, shortcut) { + (None, _) => format!("{}\n{}", look.id, crate::i18n::msg(&format!("command `{}` is not available right now", look.id))), + (Some(t), Some(keys)) => format!("{} {keys}", t.name), + (Some(t), None) => t.name.clone(), + }; + let button = match &look.text { + Some(t) => Button::command(t.command.clone()).label(look.label().to_string()), + None => Button::new(look.label().to_string()).enabled(false), + }; + let response = button.tooltip(tip).show(ui).response; + if measuring { return; } - let command = |verb: &str, tool: &str| CommandRef::with_params(verb, json!({ "tool": tool, "toolbar": bar.name })); + let (i, n) = place; + let moved = |at: usize| CommandRef::with_params("toolbar.addCommand", json!({ "command": look.id, "toolbar": bar, "at": at })); + let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": bar })); + Menu::context(look.name().to_string(), &response).show(ui, |ui, _| { + MenuItem::command(moved(i.saturating_sub(1))).label(tl!("Move Up")).enabled(i > 0).show(ui); + MenuItem::command(moved(i + 1)).label(tl!("Move Down")).enabled(i + 1 < n).show(ui); + MenuItem::command(removed.clone()).label(tl!("Remove from Toolbar")).show(ui); + }); +} + +/// The most commands the Add Command submenu lists for a search. +const COMMAND_RESULTS: usize = 30; + +/// Where the Add Command submenu of the toolbar with id `id` keeps the text of its search field. +pub(crate) fn command_query_id(id: u32) -> egui::Id { + egui::Id::unique(("custom-toolbar-command-query", id)) +} + +/// Add Tool…, in the footer of the toolbar with id `id`, after the toolbar's command buttons +/// ([`command_button`]): the + button opens a menu where, under Remove Tool, a click takes one of the +/// toolbar's tools out; then every tool under the All Tools drawer's headings, where a click adds one +/// at the end (dimmed: in the toolbar already); then, under Remove Command, the toolbar's command +/// buttons by their full names, which a click takes out, and the Add Command submenu: a search field +/// over the Command Palette's results other than tools, whose first [`COMMAND_RESULTS`] matches a +/// click adds at the end (dimmed: on the toolbar already). `measured`: the rail measures its footer, +/// which draws the buttons alone. +pub(crate) fn add_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer: RailFooter, measured: bool) { + let Some(bar) = app.ui.custom_toolbars.iter().find(|b| b.id == id) else { return }; + let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); + let name = bar.name.clone(); + let measuring = measured || craft::ui::runtime::measure::active(ui.ctx()); + let looks = command_looks(app, ui, id); + for (i, look) in looks.iter().enumerate() { + command_button(app, ui, &name, look, (i, looks.len()), measuring); + } + let plus = IconButton::new(IconId::new("plus")).label(tl!("Add Tool…")).popup(PopupKind::Menu).show(ui).response; + // The rail measures its footer too: the menu opens from the button the rail shows. + if measuring { + return; + } + let command = |verb: &str, tool: &str| CommandRef::with_params(verb, json!({ "tool": tool, "toolbar": name })); + let query_id = command_query_id(id); + let mut query: String = ui.data(|d| d.get_temp(query_id)).unwrap_or_default(); Menu::new(tl!("Add Tool…")).opened_by(&plus, Trigger::Click).show(ui, |ui, _| { if !held.is_empty() { MenuItem::heading(crate::i18n::colon(tl!("Remove Tool"))).show(ui); @@ -678,7 +826,35 @@ pub(crate) fn add_menu(app: &VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer MenuItem::command(command("toolbar.addTool", tool.id)).label(tool.label).enabled(!held.contains(&tool.id)).show(ui); } } + Divider::horizontal().show(ui); + if !looks.is_empty() { + MenuItem::heading(crate::i18n::colon(tl!("Remove Command"))).show(ui); + for look in &looks { + let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": name })); + MenuItem::command(removed).label(look.name().to_string()).show(ui); + } + Divider::horizontal().show(ui); + } + Menu::submenu_row(ui, tl!("Add Command"), |ui, cx| { + // The field drives the submenu: Up and Down move its active row and Enter runs it, while + // typing stays in the field. + TextField::search(tl!("Search Commands"), Bind::bound(&mut query)).placeholder(tl!("Search Commands")).drives(cx.resolved.id).show(ui); + if query.trim().is_empty() { + Text::new(tl!("Type to find a command")).shade(Shade::Muted).show(ui); + return; + } + let found = crate::palette::command_matches(app, ui, &query, COMMAND_RESULTS); + if found.is_empty() { + Text::new(tl!("No matching commands")).shade(Shade::Muted).show(ui); + } + for (command, shown) in found { + let on = !looks.iter().any(|l| l.id == command); + let added = CommandRef::with_params("toolbar.addCommand", json!({ "command": command, "toolbar": name })); + MenuItem::command(added).label(shown).enabled(on).show(ui); + } + }); }); + ui.data_mut(|d| d.insert_temp(query_id, query)); } #[cfg(test)] @@ -832,7 +1008,7 @@ mod tests { let names: Vec = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect(); assert_eq!(names, ["Mine", "Toolbar 1"]); let list = app.run("window.toolbar.list", json!({})).unwrap(); - let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null}); + let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "commands": [], "floating": true, "side": "left", "order": null}); assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")])); } @@ -876,7 +1052,10 @@ mod tests { assert!(app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Nope"})).is_err()); let r = app.run("toolbar.removeTool", json!({"tool": "artboard", "toolbar": "Mine"})).unwrap(); assert_eq!(r, json!([["pen", "curvature"]])); + // Its command buttons go with it. + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); let mine = find(&app.ui, "Mine").cloned().unwrap(); + assert_eq!(mine.commands, ["object.group"]); // Another workspace has its own toolbars (none); coming back brings Mine back. app.run("window.workspace", json!({"name": "Essentials"})).unwrap(); assert!(app.ui.custom_toolbars.is_empty()); @@ -1148,7 +1327,12 @@ mod tests { bars[0].last_used.set(slot("rectangle"), "pen".into()); bars[4].last_used.set(slot("pen"), "curvature".into()); bars[5].last_used.set(slot("pen"), "curvature".into()); + // Command buttons: each once, none for a tool or a blank id; one not known now stays. + bars[4].commands = ["object.group", "tool:pen", " ", "object.group", "plugin:gone"].map(String::from).to_vec(); + bars[5].commands = (0..MAX_COMMANDS + 5).map(|i| format!("plugin:p{i}")).collect(); sanitize(&mut bars); + assert_eq!(bars[1].commands, ["object.group", "plugin:gone"]); + assert_eq!(bars[2].commands.len(), MAX_COMMANDS); assert_eq!(bars.iter().map(|b| b.name.as_str()).collect::>(), ["A", "B", "C"], "a name past {MAX_NAME} characters goes too"); assert_eq!(bars.iter().map(|b| b.id).collect::>(), [1, 3, 2], "the first has none, the third repeats the second's"); assert_eq!(bars[0].last_used.get(slot("pen")), Some(&"curvature".to_string())); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6fcff63221..4ee61440a0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -49,6 +49,7 @@ mod export_as; mod export_for_screens; pub(crate) mod export_host; pub mod eyedropper; +pub mod failed_plugins; pub mod file_info; pub mod find_links; pub mod find_replace; diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs index 58980c099c..dda71b4984 100644 --- a/crates/ui-egui/src/dialogs/action_new.rs +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -138,9 +138,7 @@ impl StackDialog for NewActionDialog { TextField::new(label("Name:"), Bind::bound(&mut fields.name)).show(ui); }); Field::new(label("Action Set:")).show(ui, |ui, _| { - if let Some(set) = Select::new(label("Action Set:"), Bind::given(fields.set), &sets).show(ui).value().copied() { - fields.set = set; - } + Select::new(label("Action Set:"), Bind::bound(&mut fields.set), &sets).show(ui); }); key_and_color(ui, &mut fields.options); automatic_align_options(ui, &mut fields.options); @@ -164,3 +162,110 @@ impl StackDialog for NewActionDialog { self.form.set_field(ctx, field, value) } } + +#[cfg(test)] +mod tests { + use craft::automation::actions::{ActionColor, ActionList}; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use super::*; + use crate::dialogs::action_set_options::SetOptionsDialog; + use crate::panels::actions::{FUNCTION_KEYS, STOP_RECORDING, model}; + use crate::tests::panel_harness::Panel; + + fn panel() -> Panel { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.actions = ActionList::new(); + app.ui.actions.new_set("First").unwrap(); + app.ui.actions.new_set("Second").unwrap(); + app.ui.action_set = Some("First".into()); + Panel::new(app, crate::tests::picks::dialogs) + } + + fn fields(panel: &Panel) -> NewActionFields { + panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().form.values.clone()) + } + + fn popup(panel: &mut Panel, name: &str) { + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + } + + #[test] + fn cancelled_choices_keep_the_new_action_destination_key_and_color() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + let original = fields(&panel); + for name in ["Action Set", "Function Key", "Color"] { + popup(&mut panel, name); + assert_ne!(fields(&panel), original, "the popup previews {name}"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), original, "Escape restores {name}"); + } + assert!(panel.enabled("Record")); + panel.click("Record"); + panel.frame(); + panel.frame(); + { + let app = panel.app(); + assert!(app.ui.recording.is_some()); + assert_eq!(model::members(&app.ui.actions, "First").len(), 1); + assert!(model::members(&app.ui.actions, "Second").is_empty()); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.name, original.name); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + panel.app().run(STOP_RECORDING, json!({})).unwrap(); + crate::dialogs::action_set_options::open_action(&mut panel.app(), 0, 0); + panel.frame(); + let options = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().json_fields().unwrap()); + let original = options(&panel); + for name in ["Function Key", "Color"] { + popup(&mut panel, name); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(options(&panel), original, "Action Options restores {name}"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + + #[test] + fn committed_choices_are_used_by_record() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + popup(&mut panel, "Action Set"); + panel.key(Key::Enter, Modifiers::NONE); + popup(&mut panel, "Color"); + panel.key(Key::Enter, Modifiers::NONE); + let key = (1..=FUNCTION_KEYS).find(|&key| key_reason(&ActionOptions { key, ..Default::default() }).is_none()).unwrap(); + panel.click_role("Function Key", Role::COMBO_BOX); + panel.key(Key::Home, Modifiers::NONE); + for _ in 0..key { + panel.key(Key::ArrowDown, Modifiers::NONE); + } + panel.key(Key::Enter, Modifiers::NONE); + let chosen = fields(&panel); + assert_eq!((chosen.set, chosen.options.key, chosen.options.color), (1, key, ActionColor::ALL[1])); + panel.click("Record"); + panel.frame(); + panel.frame(); + let app = panel.app(); + assert!(model::members(&app.ui.actions, "First").is_empty()); + assert_eq!(model::members(&app.ui.actions, "Second").len(), 1); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, chosen.options.color); + assert_eq!(model::function_key(action).map(|key| key.key), Some(key)); + assert!(app.ui.recording.is_some()); + } +} diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 8a6de85fe4..10a0647fc9 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -243,9 +243,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let modifier = if crate::keymap::platform() == craft::keymap::Platform::Mac { "⌘" } else { "Ctrl" }; Field::new(label("Function Key:")).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - if let Some(key) = Select::new(label("Function Key:"), Bind::given(options.key), &keys).show(ui).value().copied() { - options.key = key; - } + Select::new(label("Function Key:"), Bind::bound(&mut options.key), &keys).show(ui); Checkbox::new(Bind::bound(&mut options.cmd)).label(modifier).show(ui); Checkbox::new(Bind::bound(&mut options.shift)).label(label("Shift")).show(ui); }); @@ -255,9 +253,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let colors: Vec> = ActionColor::ALL.into_iter().map(|color| Entry::new(color, label_color_label(color.label_color(), &words))).collect(); Field::new(label("Color:")).show(ui, |ui, _| { - if let Some(color) = Select::new(label("Color:"), Bind::given(options.color), &colors).show(ui).value().copied() { - options.color = color; - } + Select::new(label("Color:"), Bind::bound(&mut options.color), &colors).show(ui); }); } diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 6ff5ddf419..4ca5f2fc23 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -352,7 +352,8 @@ fn length_row(ui: &mut Ui, label: impl Into