mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/promise-host-constructors
This commit is contained in:
commit
95442aa792
271 files changed
+18798
-1583
No files matched your search
@@ -89,14 +89,15 @@ jobs:
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg
|
||||
# starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves
|
||||
# 40 minutes for that.
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 200
|
||||
timeout-minutes: 290
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
@@ -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=<craft-fonts checkout>` (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-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them.
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (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-<family>.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 |
|
||||
|---|---|---|---|---|
|
||||
|
||||
Generated
+11
@@ -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",
|
||||
@@ -8875,6 +8876,16 @@ dependencies = [
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"vectorcraft-plugins",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.24.1"
|
||||
|
||||
@@ -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-<family>.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:
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
path = "src/main.rs"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] }
|
||||
@@ -0,0 +1,37 @@
|
||||
//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the
|
||||
//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each
|
||||
//! module it checks and each filter it runs, through the loader Trunk writes for it
|
||||
//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`.
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
use web_sys::{DedicatedWorkerGlobalScope, MessageEvent};
|
||||
|
||||
let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let poster = scope.clone();
|
||||
let post = Rc::new(move |msg: Vec<u8>| {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
// A message that can't be posted leaves the page waiting, and its time budget ends the run.
|
||||
let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer()));
|
||||
});
|
||||
let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post)));
|
||||
let handler = Rc::clone(&worker);
|
||||
let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
|
||||
let msg = js_sys::Uint8Array::new(&e.data()).to_vec();
|
||||
handler.borrow_mut().handle(&msg);
|
||||
});
|
||||
scope.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
// The handler lives as long as the worker.
|
||||
on_message.forget();
|
||||
worker.borrow().ready();
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() {
|
||||
eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker");
|
||||
}
|
||||
@@ -33,4 +33,4 @@ wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] }
|
||||
@@ -17,6 +17,8 @@
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="icons/32/ai.storyteller.vectorcraft.png">
|
||||
<link rel="apple-touch-icon" href="icons/256/ai.storyteller.vectorcraft.png">
|
||||
<link data-trunk rel="rust" data-bin="vectorcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<!-- The plug-in worker: checks plug-ins being installed and runs filters off the page (apps/vectorcraft-plugin-worker). -->
|
||||
<link data-trunk rel="rust" href="../vectorcraft-plugin-worker/Cargo.toml" data-bin="vectorcraft-plugin-worker" data-type="worker" data-loader-shim data-wasm-opt="z" />
|
||||
<style>
|
||||
/* iPad: no page scroll, bounce, pinch zoom, text selection or callout; the app takes the gestures. */
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262626;
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
//! - no TCP control server (browsers can't listen on sockets);
|
||||
//! - File → Open uses the browser file picker, through the host's file service (`BrowserFiles`);
|
||||
//! - Save / Export trigger a browser download;
|
||||
//! - plug-ins are checked when installed, and filters run, in Web Workers of their own
|
||||
//! (`plugin_workers`, the `vectorcraft-plugin-worker` build), so a plug-in never runs on the page;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
|
||||
//! hover, palm rejection, fingers navigate once a pen has been seen, the pen's eraser end
|
||||
@@ -28,6 +30,8 @@ mod keys;
|
||||
mod locks;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod pencil;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod plugin_workers;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod saved_files;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -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<Wheel>,
|
||||
/// Every reading written into the source, in order.
|
||||
#[cfg(test)]
|
||||
readings: Vec<PointerSample>,
|
||||
}
|
||||
|
||||
/// 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<f32>) {
|
||||
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,
|
||||
/// <https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure>): 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<f32> {
|
||||
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<f32>) {
|
||||
@@ -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::<web_sys::PointerEvent>().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<Option<f32>> {
|
||||
p.readings.drain(..).map(|s| s.wheel).collect()
|
||||
}
|
||||
|
||||
/// The wheel of the source's latest reading.
|
||||
fn current_wheel(p: &Pointers) -> Option<f32> {
|
||||
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<Pos2> = 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::<Vec<_>>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]);
|
||||
assert_eq!(kept.iter().map(|s| s.pressure).collect::<Vec<_>>(), [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]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The plug-in workers ([`vectorcraft_ui_egui::plugin_runs::Workers`]): each one a Web Worker that
|
||||
//! runs `vectorcraft-plugin-worker`, which Trunk builds beside the app (`index.html`), started from
|
||||
//! the loader file Trunk writes for it next to `index.html`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_ui_egui::plugin_runs::{SharedInbox, WorkerLink, Workers};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
|
||||
/// The loader Trunk writes for the worker (`data-loader-shim`), beside `index.html`.
|
||||
const LOADER: &str = "vectorcraft-plugin-worker_loader.js";
|
||||
|
||||
/// Starts the workers; each message or failure asks for a frame, which reads it.
|
||||
pub(crate) struct PageWorkers {
|
||||
pub(crate) ctx: egui::Context,
|
||||
}
|
||||
|
||||
/// One worker and its message and error handlers.
|
||||
struct PageWorker {
|
||||
worker: web_sys::Worker,
|
||||
_on_message: Closure<dyn FnMut(web_sys::MessageEvent)>,
|
||||
_on_error: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
|
||||
/// The text of a browser error value.
|
||||
fn js_err(e: wasm_bindgen::JsValue) -> String {
|
||||
e.as_string().unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
impl Workers for PageWorkers {
|
||||
fn start(&self, inbox: SharedInbox) -> Result<Box<dyn WorkerLink>, String> {
|
||||
let document = web_sys::window().and_then(|w| w.document()).ok_or_else(|| "no document".to_string())?;
|
||||
let base = document.base_uri().map_err(js_err)?.ok_or_else(|| "no document".to_string())?;
|
||||
let url = web_sys::Url::new_with_base(LOADER, &base).map_err(js_err)?.href();
|
||||
let worker = web_sys::Worker::new(&url).map_err(js_err)?;
|
||||
let (to, ctx) = (Rc::clone(&inbox), self.ctx.clone());
|
||||
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
|
||||
to.borrow_mut().push(&js_sys::Uint8Array::new(&e.data()).to_vec());
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let ctx = self.ctx.clone();
|
||||
// A worker that fails to load, panics or posts a message that can't be read.
|
||||
let on_error = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
let why = e.dyn_ref::<web_sys::ErrorEvent>().map_or_else(|| e.type_(), web_sys::ErrorEvent::message);
|
||||
inbox.borrow_mut().fail(why);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
worker.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
worker.set_onerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
worker.set_onmessageerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
Ok(Box::new(PageWorker { worker, _on_message: on_message, _on_error: on_error }))
|
||||
}
|
||||
|
||||
fn now_ms(&self) -> f64 {
|
||||
web_sys::window().and_then(|w| w.performance()).map_or(0.0, |p| p.now())
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkerLink for PageWorker {
|
||||
fn post(&mut self, msg: Vec<u8>) -> Result<(), String> {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
self.worker.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())).map_err(js_err)
|
||||
}
|
||||
|
||||
fn terminate(&mut self) {
|
||||
self.worker.set_onmessage(None);
|
||||
self.worker.set_onerror(None);
|
||||
self.worker.set_onmessageerror(None);
|
||||
self.worker.terminate();
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
.jobs(Arc::new(InlineJobs))
|
||||
.files(Arc::new(files))
|
||||
.install(ctx);
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone());
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone(), ctx.clone());
|
||||
let mut app = match taken.borrow_mut().take() {
|
||||
Some(mut app) => {
|
||||
// The old services asked the old context for frames.
|
||||
@@ -461,8 +461,10 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
}
|
||||
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>) -> Services {
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>, ctx: egui::Context) -> Services {
|
||||
Services {
|
||||
// Plug-ins are checked and filters run in workers of their own, off the page.
|
||||
plugin_workers: vectorcraft_ui_egui::plugin_runs::workers(Box::new(crate::plugin_workers::PageWorkers { ctx })),
|
||||
// A download that couldn't be started fails the save or export it is for (#1693).
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
|
||||
inbox: Some(inbox.dropped),
|
||||
|
||||
@@ -629,6 +629,15 @@ struct StartFile {
|
||||
record: StartRecord,
|
||||
}
|
||||
|
||||
impl Drop for StartFile {
|
||||
/// Frees the lock when the start releases the file. A child process that any thread starts holds
|
||||
/// a copy of the file's handle until it runs its program, and the lock is only freed by closing
|
||||
/// every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl StartFile {
|
||||
/// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is
|
||||
/// none or it can't be read). `Ok(None)` when another copy of the app holds it.
|
||||
|
||||
@@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
/// A log folder of its own for each test.
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -632,10 +630,23 @@ impl AsRef<std::path::Path> for TestDir {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
fn start_dir(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
/// A start that ends frees the start file even while another handle to it is open, as a child
|
||||
/// process that is starting holds one: the next start reads the file instead of taking it for
|
||||
/// another copy of the app that is starting.
|
||||
#[test]
|
||||
fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = start_dir("copy");
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the start holds the file");
|
||||
starting.ended();
|
||||
assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -661,7 +672,7 @@ fn issue_2243() -> Vec<Candidate> {
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let (dir, _spawns) = start_dir("crash");
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
@@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
/// an error, a restart on another adapter), leaves nothing out of the next.
|
||||
#[test]
|
||||
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
let (dir, _spawns) = start_dir("shown");
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
@@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let (dir, _spawns) = start_dir("listing");
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
@@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
/// start shows its first frame on the adapter that crashed, the adapter counts again.
|
||||
#[test]
|
||||
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
let (dir, _spawns) = start_dir("explicit");
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
@@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let (dir, _spawns) = start_dir("damaged");
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
|
||||
@@ -1034,19 +1034,5 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests only: while a test starts another program, the child briefly holds a copy of every file
|
||||
/// this process has open, until it runs that program. A file lock held through such a copy outlives
|
||||
/// its own handle, so a GPU start test that released the start file and opened it again found it
|
||||
/// still locked, as if another copy of the app were running, and failed. A test that starts a
|
||||
/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`].
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]).
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
mod tests;
|
||||
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
_lease: Lease,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
/// The profile's [`LEASE`], open and locked.
|
||||
struct Lease(File);
|
||||
|
||||
impl Lease {
|
||||
/// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it.
|
||||
fn take(root: &Path) -> io::Result<Option<Self>> {
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => Ok(Some(Self(lease))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
/// Frees the lease when the session ends, or when a session could not be started after the lock
|
||||
/// was taken. A child process that any thread starts holds a copy of the lease's handle until it
|
||||
/// runs its program, and the lock is only freed by closing every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
@@ -73,14 +99,13 @@ impl Session {
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let Some(lease) = Lease::take(root)? else { return Ok(None) };
|
||||
Self::record(lease, root, version, commit).map(Some)
|
||||
}
|
||||
|
||||
/// Write this launch's record while `lease` is held. On an error `lease` is dropped, which
|
||||
/// unlocks it.
|
||||
fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result<Self> {
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
@@ -90,7 +115,7 @@ impl Session {
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
Ok(Self { _lease: lease, path, own_record, previous_unclean })
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
@@ -258,6 +283,54 @@ mod tests {
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let first_copy = first._lease.0.try_clone().unwrap();
|
||||
first.complete().unwrap();
|
||||
let second = Session::begin(Some(&fixture.0), "second", None).unwrap();
|
||||
assert!(second.is_some(), "a completed session frees the lease");
|
||||
let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap());
|
||||
drop(second);
|
||||
assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease");
|
||||
drop((first_copy, second_copy));
|
||||
}
|
||||
|
||||
/// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a
|
||||
/// child process that is starting holds.
|
||||
fn locked_with_a_copy(root: &Path) -> (Lease, File) {
|
||||
let lease = Lease::take(root).unwrap().unwrap();
|
||||
let copy = lease.0.try_clone().unwrap();
|
||||
(lease, copy)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::create_dir(fixture.0.join(RECORD)).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record");
|
||||
std::fs::remove_dir(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
// A folder at the temporary file's name makes the write fail after the record was checked.
|
||||
let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id()));
|
||||
std::fs::create_dir(&temporary).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written");
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
std::fs::remove_dir(&temporary).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -145,6 +145,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
|
||||
// No test installs a launch's root in this process, so the settings folder stays the same here.
|
||||
assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others");
|
||||
install_fonts();
|
||||
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
|
||||
assert!(fonts.is_some(), "a home folder to keep the settings in");
|
||||
|
||||
@@ -457,10 +457,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
|
||||
/// process (nextest gives every test its own).
|
||||
/// Runs the test `name` of this module again in a child process of the test binary → whether
|
||||
/// this is that child. For a test that installs the process-wide root, which every test running
|
||||
/// beside it would then read as the settings folder.
|
||||
fn in_own_process(name: &str) -> bool {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return true;
|
||||
}
|
||||
// The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file.
|
||||
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
|
||||
let path = format!("{module}::{name}");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"{path} failed in its own process:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
/// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in
|
||||
/// a process of its own.
|
||||
#[test]
|
||||
fn the_installed_root_is_used_once_and_must_be_absolute() {
|
||||
if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") {
|
||||
return;
|
||||
}
|
||||
let dir = temp("installed-root");
|
||||
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
|
||||
install_data_root(dir.to_path_buf()).unwrap();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Vec<u8>>| 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<Vec<u8>> {
|
||||
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)]) {
|
||||
|
||||
@@ -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<Vec<u8>>, &'a mut Option<Vec<u8>>);
|
||||
|
||||
/// 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<Vec<u8>> {
|
||||
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());
|
||||
}
|
||||
+119
-20
@@ -81,6 +81,11 @@ pub struct HitOptions {
|
||||
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
|
||||
/// hit the art on a layer whose Preview is off as painted, not in outline.
|
||||
pub ignore_layer_preview: bool,
|
||||
/// The selection tools: where a click hits nothing else, a closed path or compound path with
|
||||
/// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with
|
||||
/// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their
|
||||
/// outline only. [`hit_test`] and [`objects_at`] try every other object first.
|
||||
pub unfilled_interiors: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
@@ -94,6 +99,7 @@ impl Default for HitOptions {
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
@@ -417,11 +423,35 @@ impl Drop for DrawnOff {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a clipping path is being tested ([`InMask`]).
|
||||
static IN_MASK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone
|
||||
/// ([`takes_interior`]).
|
||||
struct InMask {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl InMask {
|
||||
fn set() -> Self {
|
||||
Self { was: IN_MASK.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InMask {
|
||||
fn drop(&mut self) {
|
||||
IN_MASK.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
let _mask = mask.then(InMask::set);
|
||||
f()
|
||||
}
|
||||
|
||||
@@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, pass, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break 'passes;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -980,7 +1016,18 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
return painted;
|
||||
}
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
/// One walk of [`hit_test_skipping`], with `opt` as given.
|
||||
fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
@@ -1524,7 +1571,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
hit_order(n, children, p).any(|i| {
|
||||
let _mask = (i == 0 && n.clips()).then(InMask::set);
|
||||
children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))
|
||||
})
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
@@ -1563,6 +1613,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)) {
|
||||
@@ -1613,6 +1672,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1647,7 +1708,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if !near_decoration {
|
||||
return None;
|
||||
return inside();
|
||||
}
|
||||
}
|
||||
let bp = path.to_bezpath();
|
||||
@@ -1657,7 +1718,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
|
||||
return Some(HitKind::Fill);
|
||||
}
|
||||
None
|
||||
inside()
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
|
||||
@@ -1675,7 +1736,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
if n.appearance.has_visible_fill() {
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -1747,6 +1812,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths
|
||||
/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide.
|
||||
fn takes_interior(n: &Node, opt: HitOptions) -> bool {
|
||||
opt.unfilled_interiors
|
||||
&& !opt.outline
|
||||
&& !opt.path_only
|
||||
&& !IN_MASK.get()
|
||||
&& !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside
|
||||
/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths'
|
||||
/// fill does. Open subpaths are left out: they bound no area.
|
||||
fn closed_subpaths_at<'a>(paths: impl IntoIterator<Item = &'a PathData>, p: Point) -> BezPath {
|
||||
let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1;
|
||||
let mut bp = BezPath::new();
|
||||
for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) {
|
||||
for sp in pd.subpaths.iter().filter(|sp| sp.closed) {
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
|
||||
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
|
||||
/// stroke along its shape, a fill inside it except with Selection by Path Only.
|
||||
@@ -2023,13 +2112,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
|
||||
/// symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let walk = ArtWalk::open();
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
let pick = |opt: HitOptions| {
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
return None;
|
||||
}
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
|
||||
@@ -38,6 +38,168 @@ fn unfilled_interior_misses() {
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// The selection tools' options with unfilled closed paths hit inside.
|
||||
const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING };
|
||||
|
||||
/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer.
|
||||
fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId {
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let pts: Vec<Point> = points.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed));
|
||||
d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(INTERIORS), Some(frame));
|
||||
assert_eq!(at(SELECTING), None, "without the option, the interior misses");
|
||||
assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only");
|
||||
assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]);
|
||||
assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_is_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, false);
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None);
|
||||
}
|
||||
|
||||
/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit
|
||||
/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it.
|
||||
#[test]
|
||||
fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let dot = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(&d, 50.0), Some(dot));
|
||||
assert_eq!(at(&d, 20.0), Some(frame));
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]);
|
||||
// The topmost of two unfilled frames is hit inside both.
|
||||
let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true);
|
||||
assert_eq!(at(&d, 20.0), Some(inner));
|
||||
assert_eq!(at(&d, 5.0), Some(frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))];
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
|
||||
compound.appearance = look().into();
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(15.0), Some(id));
|
||||
assert_eq!(at(50.0), None, "in the hole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_and_clipping_paths_are_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let guide = stroked(&mut d, &FRAME, true);
|
||||
if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) {
|
||||
*g = true;
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide");
|
||||
// A clip group whose art covers only part of its unfilled clipping path.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(25.0), Some(art));
|
||||
assert_eq!(at(75.0), None, "inside the mask where no art paints");
|
||||
assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty());
|
||||
}
|
||||
|
||||
/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled
|
||||
/// compound clipping path are not.
|
||||
#[test]
|
||||
fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() {
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 2,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let repeat = |d: &mut Document, source: Node| {
|
||||
let r = d.alloc_id();
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] })))
|
||||
.unwrap();
|
||||
r
|
||||
};
|
||||
// Copies at 0..40 and 60..100.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look());
|
||||
let r = repeat(&mut d, frame);
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r));
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies");
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))];
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let r = repeat(&mut d, clip);
|
||||
assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art");
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints");
|
||||
}
|
||||
|
||||
/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what
|
||||
/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline.
|
||||
#[test]
|
||||
fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art());
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look());
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))];
|
||||
let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS);
|
||||
assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame");
|
||||
assert_eq!(at(20.0), Some(vec![1]), "inside the frame");
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
|
||||
+13
-2
@@ -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();
|
||||
|
||||
@@ -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<Node>, 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)
|
||||
}
|
||||
|
||||
|
||||
@@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
|
||||
|
||||
static LOADER: OnceLock<Loader> = OnceLock::new();
|
||||
|
||||
std::thread_local! {
|
||||
/// Open checks use previews rather than loading placed documents for drawing.
|
||||
static PREVIEWS_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Restores whether only previews are used when an open check ends, including on unwind.
|
||||
struct PreviewsOnly(bool);
|
||||
|
||||
impl Drop for PreviewsOnly {
|
||||
fn drop(&mut self) {
|
||||
PREVIEWS_ONLY.with(|p| p.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an open check using placed documents' previews instead of loading their art on this
|
||||
/// thread. Nested checks keep the scope active until the outer check ends. This prevents an
|
||||
/// open check and drawing from recursively loading each other's nested files.
|
||||
pub fn with_previews<T>(check: impl FnOnce() -> T) -> T {
|
||||
let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true)));
|
||||
check()
|
||||
}
|
||||
|
||||
/// Register how files are read (the first registration stays).
|
||||
pub fn set_loader(l: Loader) {
|
||||
// Already set: the same loader, registered by another session.
|
||||
@@ -454,8 +476,12 @@ impl Cache {
|
||||
}
|
||||
|
||||
/// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a
|
||||
/// placed document from. `None` when it can't be read (or no loader is registered).
|
||||
/// placed document from. `None` when it can't be read, no loader is registered, or an open check
|
||||
/// uses [`with_previews`].
|
||||
pub fn read(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
|
||||
if PREVIEWS_ONLY.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
if let Some(e) = cache().get(&p.key, false, Some(bytes)) {
|
||||
return Some(e);
|
||||
}
|
||||
@@ -738,6 +764,22 @@ mod tests {
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// Nested open checks skip both new and cached art, and restore ordinary reads afterward.
|
||||
#[test]
|
||||
fn open_checks_leave_placed_documents_for_drawing_afterward() {
|
||||
set_loader(stub_loader);
|
||||
let p = placed("open-check-1");
|
||||
let bytes = Arc::new(b"leaf".to_vec());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
with_previews(|| {
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
});
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
}
|
||||
|
||||
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
|
||||
/// names its resources get.
|
||||
#[test]
|
||||
|
||||
+76
-3
@@ -356,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<bool>, 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
|
||||
@@ -374,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
|
||||
@@ -445,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
|
||||
@@ -1001,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]);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -58,10 +58,61 @@ pub fn raster_px_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f
|
||||
documented_range(id, key, "px")
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with, after any number of unit words
|
||||
/// (`key: lo..hi`, `key: unit lo..hi`, `key: screen angle deg lo..hi`) or as the first word of its
|
||||
/// description in parentheses (`key: unit (lo..hi, default)`), and before the rest of that
|
||||
/// description or the next parameter; `None` when its documentation gives none.
|
||||
pub(crate) fn any_documented_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
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::<f64>().ok()?, hi.trim_end_matches([',', ';', ')', '}']).parse::<f64>().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<Vec<&'static str>> {
|
||||
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<std::ops::RangeInclusive<f64>> {
|
||||
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<std::ops::RangeIn
|
||||
(lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi)
|
||||
}
|
||||
|
||||
/// Can a parameter name start at byte `at` of parameter documentation `doc`: after `{`, a space or
|
||||
/// a comma?
|
||||
fn starts_key(doc: &str, at: usize) -> 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<EffectInfo> {
|
||||
"{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<EffectInfo> {
|
||||
"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}),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, 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 };
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -139,6 +139,201 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
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<String, Value>) -> 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::<f64>().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::<Color>(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
|
||||
|
||||
@@ -435,7 +435,7 @@ fn reshapes(n: &Node) -> bool {
|
||||
fn path_art(n: &Node) -> Option<Node> {
|
||||
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<AppearanceItem>| {
|
||||
let mut ap: Appearance = (*n.appearance).clone();
|
||||
ap.items = items;
|
||||
@@ -454,7 +454,7 @@ fn path_art(n: &Node) -> Option<Node> {
|
||||
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()]));
|
||||
|
||||
@@ -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<BlendMode> {
|
||||
let key: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().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).
|
||||
|
||||
+195
-42
@@ -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<Node> {
|
||||
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<Node>) -> Option<Node> {
|
||||
/// ([`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<Node>,
|
||||
mut check: Option<(Budget, &mut bool)>,
|
||||
) -> Option<Node> {
|
||||
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<Node>
|
||||
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<NodeId, bool>,
|
||||
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<crate::Carry>,
|
||||
@@ -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<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
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<Budget> {
|
||||
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<Effect> = 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::<Vec<_>>(), &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<Budget> = 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<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
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<AppearanceItem>| {
|
||||
@@ -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::<Vec<_>>())
|
||||
.map(|pieces| {
|
||||
pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::<Vec<_>>()
|
||||
})
|
||||
.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<Arc<Node>> = 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<AppearanceItem>, 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<Arc<Node>> = 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));
|
||||
|
||||
@@ -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<Arrowhead> {
|
||||
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<BezPath> {
|
||||
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];
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::*;
|
||||
|
||||
mod clipfx;
|
||||
mod imageoutline;
|
||||
mod loneanchor;
|
||||
mod painted;
|
||||
mod rasterfollow;
|
||||
mod scale;
|
||||
|
||||
@@ -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<Point>) {
|
||||
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<Point> = 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:?}");
|
||||
}
|
||||
@@ -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<Rect>| 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::<usize>()));
|
||||
}
|
||||
});
|
||||
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::<Vec<_>>()
|
||||
};
|
||||
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);
|
||||
}
|
||||
@@ -120,8 +120,11 @@ 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, and how many included EPS open checks
|
||||
# an open performs.
|
||||
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"] }
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it; the lowest id wins a tie. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -766,10 +766,12 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<vectorcraft_geom::Rect> {
|
||||
/// 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<vectorcraft_geom::Rect> {
|
||||
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<vectorcraft_geom::Rect> {
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -333,11 +333,18 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
|
||||
}
|
||||
|
||||
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
|
||||
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
|
||||
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
|
||||
/// of the drag.
|
||||
/// under it ([`reach_samples`]), besides the whole of each curved segment, which is measured once
|
||||
/// however many there are: a drag measures no more than this many pieces plus one for each curved
|
||||
/// segment of the paths it searches. Shared equally by the curved segments that come within its
|
||||
/// reach, it is enough to search 300,000 pt of curve within the default reach of the drag.
|
||||
const MAX_REACH_PIECES: usize = 1 << 17;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many pieces of curve [`reach_samples`] measured against a drag on this thread.
|
||||
static PIECES_MEASURED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The box around the control points of `s`, which holds all of `s`.
|
||||
fn control_box(s: CubicBez) -> Rect {
|
||||
Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3)
|
||||
@@ -529,13 +536,24 @@ fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize {
|
||||
/// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within
|
||||
/// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample
|
||||
/// out of reach; the others are halved until their control polygon is no longer than half the
|
||||
/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the
|
||||
/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach
|
||||
/// at its middle. Each piece measures only the stretches near
|
||||
/// reach, or until fewer than the two halves are left in this segment's `budget` or in `shared`,
|
||||
/// the pieces the whole drag may still measure past the first piece of each segment, and then give
|
||||
/// one sample: in reach at the piece's middle or at its place nearest the drag when either is in
|
||||
/// reach, otherwise out of reach at its middle. Both halves of a piece are taken from `budget` and
|
||||
/// from `shared` before either is measured, so a search measures no more than one piece besides
|
||||
/// what it takes from them. Each piece measures only the stretches near
|
||||
/// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag
|
||||
/// per halving, plus the stretches near each piece.
|
||||
fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) {
|
||||
*budget = budget.saturating_sub(1);
|
||||
fn reach_samples(
|
||||
c: CubicBez,
|
||||
(t0, t1): (f64, f64),
|
||||
(pts, of): (&[Point], &[usize]),
|
||||
radius: f64,
|
||||
(budget, shared): (&mut usize, &mut usize),
|
||||
out: &mut Vec<(f64, bool)>,
|
||||
) {
|
||||
#[cfg(test)]
|
||||
PIECES_MEASURED.set(PIECES_MEASURED.get() + 1);
|
||||
let s = c.subsegment(t0..t1);
|
||||
let mid = 0.5 * (t0 + t1);
|
||||
let near = stretches_near(pts, of, control_box(s), radius);
|
||||
@@ -544,7 +562,7 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
return;
|
||||
}
|
||||
let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3);
|
||||
if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 {
|
||||
if len <= (radius / 2.0).max(1e-3) || *budget < 2 || *shared < 2 || mid <= t0 || mid >= t1 {
|
||||
// The piece's middle, or the place on it nearest the drag when the middle is out of reach.
|
||||
let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius {
|
||||
(mid, true)
|
||||
@@ -555,8 +573,10 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
out.push(sample);
|
||||
return;
|
||||
}
|
||||
reach_samples(c, (t0, mid), (pts, &near), radius, budget, out);
|
||||
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
|
||||
*budget -= 2;
|
||||
*shared -= 2;
|
||||
reach_samples(c, (t0, mid), (pts, &near), radius, (&mut *budget, &mut *shared), out);
|
||||
reach_samples(c, (mid, t1), (pts, &near), radius, (budget, shared), out);
|
||||
}
|
||||
|
||||
/// `sp` cut where the reach of the drag crosses its curved segments, and whether each
|
||||
@@ -565,8 +585,11 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
|
||||
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
|
||||
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
|
||||
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
|
||||
fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<bool>) {
|
||||
/// the reach of the drag ([`reach_samples`]): each curved segment is measured whole, and then up
|
||||
/// to `share` more pieces of it are measured while the drag's `shared` pieces last, so the segments
|
||||
/// in reach share the search equally whatever order they come in, and a segment searched after
|
||||
/// the pieces run out is still found where its middle or its place nearest the drag is in reach.
|
||||
fn mark_reached(sp: &SubPath, reach: &DragReach, (share, shared): (usize, &mut usize)) -> (SubPath, Vec<bool>) {
|
||||
let (pts, radius) = (reach.pts, reach.radius);
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect();
|
||||
@@ -578,7 +601,7 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<
|
||||
let c = sp.segment(i);
|
||||
let (mut samples, mut budget) = (vec![], share);
|
||||
let near = reach.near_rect(control_box(c.subsegment(0.0..1.0)));
|
||||
reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples);
|
||||
reach_samples(c, (0.0, 1.0), (pts, &near), radius, (&mut budget, &mut *shared), &mut samples);
|
||||
// Stretches of samples alike, in order: (in reach, first, last).
|
||||
let mut runs: Vec<(bool, usize, usize)> = vec![];
|
||||
for (k, s) in samples.iter().enumerate() {
|
||||
@@ -623,15 +646,16 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<
|
||||
|
||||
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
|
||||
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
|
||||
/// that anchor's place (VectorCraft's own rule).
|
||||
fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
/// that anchor's place (VectorCraft's own rule). `search` is each curved segment's share of the
|
||||
/// drag's search and the pieces the drag has left ([`mark_reached`]).
|
||||
fn smooth_subpath(sp: &SubPath, reach: &DragReach, search: (usize, &mut usize), tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
if sp.anchors.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let radius = reach.radius;
|
||||
let near = &|q: Point| reach.in_reach(q, 0.0);
|
||||
// A drag along a segment smooths it even when its anchors are out of reach.
|
||||
let (sp, marked) = mark_reached(sp, reach, share);
|
||||
let (sp, marked) = mark_reached(sp, reach, search);
|
||||
let sp = &sp;
|
||||
if !marked.iter().any(|m| *m) {
|
||||
return None;
|
||||
@@ -948,15 +972,17 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
paths.push((id, path_of(&st.doc, id)?.0));
|
||||
}
|
||||
let reach = DragReach::new(&pts, radius);
|
||||
// Each curved segment in reach gets the same share of the search, whatever order they come in.
|
||||
// Each curved segment in reach gets the same share of the search, whatever order they come in,
|
||||
// and all of them together measure no more than `MAX_REACH_PIECES` pieces past their first.
|
||||
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum();
|
||||
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
for (id, pd) in paths {
|
||||
let mut changed = false;
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) {
|
||||
.map(|sp| match smooth_subpath(sp, &reach, (share, &mut shared), tol, sigma) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
@@ -1304,19 +1330,106 @@ mod tests {
|
||||
assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring());
|
||||
}
|
||||
|
||||
/// How many pieces `f` makes [`reach_samples`] measure on this thread.
|
||||
fn pieces_measured(f: impl FnOnce()) -> usize {
|
||||
let before = PIECES_MEASURED.get();
|
||||
f();
|
||||
PIECES_MEASURED.get() - before
|
||||
}
|
||||
|
||||
/// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more
|
||||
/// pieces than the budget it is given, and a search with none left gives one sample.
|
||||
/// than one piece besides the drag's `MAX_REACH_PIECES`, counting the pieces it halves as well
|
||||
/// as those it samples, and a search with none of the drag's pieces left measures the curve
|
||||
/// once and gives one sample, whatever share of its own it has.
|
||||
#[test]
|
||||
fn searching_a_segment_under_a_drag_stays_within_its_budget() {
|
||||
let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0));
|
||||
let pts: Vec<Point> = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect();
|
||||
let all = drag_stretches(&pts);
|
||||
let mut budget = MAX_REACH_PIECES;
|
||||
let (mut budget, mut shared) = (MAX_REACH_PIECES, MAX_REACH_PIECES);
|
||||
let (mut first, mut second) = (vec![], vec![]);
|
||||
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first);
|
||||
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second);
|
||||
assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len());
|
||||
assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample");
|
||||
let measured = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut budget, &mut shared), &mut first));
|
||||
assert!(measured <= MAX_REACH_PIECES + 1, "{measured} pieces measured");
|
||||
assert!(first.len() <= measured && first.len() > 1, "{} samples", first.len());
|
||||
assert!(shared < 2, "{shared} pieces left");
|
||||
let mut fresh = MAX_REACH_PIECES;
|
||||
let again = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut fresh, &mut shared), &mut second));
|
||||
assert_eq!((again, second.len()), (1, 1), "the drag's pieces are spent, so the next search gives one sample");
|
||||
}
|
||||
|
||||
/// One curved segment `w` pt wide from `(x, y)`, bowed `h` pt up.
|
||||
fn bow((x, y): (f64, f64), w: f64, h: f64) -> CubicBez {
|
||||
CubicBez::new(Point::new(x, y), Point::new(x + w / 3.0, y + h), Point::new(x + 2.0 * w / 3.0, y + h), Point::new(x + w, y))
|
||||
}
|
||||
|
||||
/// An open subpath of the curved segments `segs`, each starting where the one before ends.
|
||||
fn chain(segs: &[CubicBez]) -> SubPath {
|
||||
let mut anchors: Vec<Anchor> = vec![];
|
||||
for s in segs {
|
||||
match anchors.last_mut() {
|
||||
Some(last) => *last = Anchor::with_handles(s.p0, last.h_in, s.p1),
|
||||
None => anchors.push(Anchor::with_handles(s.p0, s.p0, s.p1)),
|
||||
}
|
||||
anchors.push(Anchor::with_handles(s.p3, s.p2, s.p3));
|
||||
}
|
||||
SubPath::new(anchors, false)
|
||||
}
|
||||
|
||||
/// A drag along two subpaths of 21,845 curved segments 100 pt long each, which share the search
|
||||
/// three pieces to a segment, and past a third of 1,000 curved segments far from the drag: every
|
||||
/// segment is measured whole and the whole drag measures no more than `MAX_REACH_PIECES` pieces
|
||||
/// past those, though each segment in reach would halve its pieces while its share lasts. Each
|
||||
/// segment in reach, the last one included, is halved once with its share of three, so the
|
||||
/// segments searched first leave the later ones their share.
|
||||
#[test]
|
||||
fn a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each() {
|
||||
let row = |(x, y): (f64, f64), n: u32| chain(&(0..n).map(|i| bow((x + f64::from(i) * 100.0, y), 100.0, 8.0)).collect::<Vec<_>>());
|
||||
let subs = [row((0.0, 0.0), 21_845), row((3_000_000.0, 0.0), 21_845), row((0.0, 1e6), 1000)];
|
||||
let pts = [Point::new(-10.0, 0.0), Point::new(6_000_000.0, 0.0)];
|
||||
let segments: usize = subs.iter().map(SubPath::segment_count).sum();
|
||||
assert_eq!(segments, 2 * 21_845 + 1000);
|
||||
let reach = DragReach::new(&pts, 12.0);
|
||||
let in_reach = segments_in_reach(&PathData::new(subs.to_vec()), &reach);
|
||||
assert_eq!(in_reach, 2 * 21_845, "the far segments are not counted");
|
||||
let share = (MAX_REACH_PIECES / in_reach).max(1);
|
||||
assert_eq!(share, 3);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
let mut marks = vec![];
|
||||
let measured = pieces_measured(|| {
|
||||
for sp in &subs {
|
||||
marks.push(mark_reached(sp, &reach, (share, &mut shared)).1);
|
||||
}
|
||||
});
|
||||
assert!(measured >= segments && measured <= segments + MAX_REACH_PIECES, "{measured} pieces measured for {segments} segments");
|
||||
assert_eq!((measured, shared), (segments + 2 * in_reach, MAX_REACH_PIECES - 2 * in_reach), "every segment in reach is halved once");
|
||||
assert!(marks[0].iter().all(|m| *m), "the first path's anchors are all on the drag");
|
||||
}
|
||||
|
||||
/// More than `MAX_REACH_PIECES` short curved segments in reach are each measured once, and a
|
||||
/// segment searched after the drag's pieces are spent is still found in reach where only a
|
||||
/// narrow stretch of it, away from its middle, comes near the drag.
|
||||
#[test]
|
||||
fn every_curved_segment_is_searched_after_the_drags_pieces_run_out() {
|
||||
let n = 140_000;
|
||||
let tiny = chain(&(0..n).map(|i| bow((f64::from(i) * 4.0, 0.0), 4.0, 1.0)).collect::<Vec<_>>());
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(f64::from(n) * 4.0, 0.0)];
|
||||
let reach = DragReach::new(&pts, 12.0);
|
||||
let share = (MAX_REACH_PIECES / segments_in_reach(&PathData::single(tiny.clone()), &reach).max(1)).max(1);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
let measured = pieces_measured(|| {
|
||||
mark_reached(&tiny, &reach, (share, &mut shared));
|
||||
});
|
||||
assert_eq!(measured, 140_000, "each segment is measured whole once");
|
||||
// An arch 1,000 pt wide and 300 pt high, with the drag on it a quarter of the way along.
|
||||
let arch = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 400.0), Point::new(1000.0, 400.0), Point::new(1000.0, 0.0));
|
||||
let sp = chain(&[arch]);
|
||||
let hit = [arch.eval(0.25)];
|
||||
assert!(dist_to_polyline(&hit, arch.eval(0.5)) > 12.0, "the arch's middle is out of reach");
|
||||
let mut spent = 0;
|
||||
let (out, marked) = mark_reached(&sp, &DragReach::new(&hit, 12.0), (MAX_REACH_PIECES, &mut spent));
|
||||
assert_eq!(out.anchors.len(), 3, "{out:?}");
|
||||
assert_eq!(marked, vec![false, true, false]);
|
||||
assert!(out.anchors[1].p.distance(hit[0]) <= 12.0, "{out:?}");
|
||||
}
|
||||
|
||||
/// A small piece of curve is measured only against the few stretches of a drag of 100,000
|
||||
@@ -1384,14 +1497,14 @@ mod tests {
|
||||
assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures");
|
||||
let share = (MAX_REACH_PIECES / in_reach).max(1);
|
||||
let mut got = None;
|
||||
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share)));
|
||||
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, (share, &mut { MAX_REACH_PIECES }))));
|
||||
assert!(marks < 100_000, "{marks} measures");
|
||||
let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0);
|
||||
let smoothed = smooth_subpath(&sp, &reach, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0);
|
||||
assert!(smoothed.is_some());
|
||||
let all = linear(&pts, 12.0);
|
||||
assert_eq!(segments_in_reach(&pd, &all), in_reach);
|
||||
assert_eq!(Some(mark_reached(&sp, &all, share)), got);
|
||||
assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed);
|
||||
assert_eq!(Some(mark_reached(&sp, &all, (share, &mut { MAX_REACH_PIECES }))), got);
|
||||
assert_eq!(smooth_subpath(&sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0), smoothed);
|
||||
}
|
||||
|
||||
/// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer
|
||||
@@ -1444,10 +1557,20 @@ mod tests {
|
||||
let in_reach = segments_in_reach(&pd, &all);
|
||||
assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
|
||||
assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
assert_eq!(
|
||||
mark_reached(sp, &grid, (share, &mut { MAX_REACH_PIECES })),
|
||||
mark_reached(sp, &all, (share, &mut { MAX_REACH_PIECES })),
|
||||
"path {k}, reach {radius}, drag {:?}",
|
||||
pts.first()
|
||||
);
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let want = smooth_subpath(sp, &all, share, 2.5, sigma);
|
||||
assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
let want = smooth_subpath(sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma);
|
||||
assert_eq!(
|
||||
smooth_subpath(sp, &grid, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma),
|
||||
want,
|
||||
"path {k}, reach {radius}, drag {:?}",
|
||||
pts.first()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -403,9 +403,8 @@ impl DocSettings {
|
||||
if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn {
|
||||
self.rows = 0;
|
||||
}
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
// While rows are set, `grid_columns` gives the columns they make; the stored columns stay as
|
||||
// they were given, and are the ones a later layout without rows uses.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ type PlacedPages = Vec<(u32, bool, vectorcraft_doc::PageBox)>;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many placed PDF or `.ai` pages [`page_fonts`] read on this thread.
|
||||
/// Tests: how many placed PDF, `.ai` or EPS pages [`page_fonts`] read on this thread.
|
||||
pub(crate) static PAGES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many linked `.vectorcraft` files had their preview and PDF read on this thread,
|
||||
/// to keep them in the rewritten copy.
|
||||
@@ -196,16 +196,41 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
/// The fonts of the type on `pages` of the PDF, `.ai` or EPS file `name` (`bytes`, found at
|
||||
/// `path`), and on the placed documents that art holds (an EPS file whose bytes a legacy `.ai` or
|
||||
/// EPS file includes), [`MAX_NESTED_PAGES`] deep; none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
nested_page_fonts(name, bytes, path, pages, 0)
|
||||
}
|
||||
|
||||
/// The most placed documents [`page_fonts`] reads inside one another.
|
||||
const MAX_NESTED_PAGES: usize = 8;
|
||||
|
||||
/// [`page_fonts`], `depth` placed documents in.
|
||||
fn nested_page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages, depth: usize) -> BTreeSet<super::fonts::UsedFont> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
if super::place::document::is_pdf(name, bytes) {
|
||||
if super::place::document::is_pdf(name, bytes) || super::place::document::is_postscript(bytes) {
|
||||
for &(page, bounding, page_box) in pages {
|
||||
#[cfg(test)]
|
||||
PAGES_READ.with(|c| c.set(c.get() + 1));
|
||||
if let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) {
|
||||
fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes));
|
||||
let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) else { continue };
|
||||
fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes));
|
||||
if depth + 1 >= MAX_NESTED_PAGES {
|
||||
continue;
|
||||
}
|
||||
let mut inner = Vec::new();
|
||||
let patterns = a.doc.patterns.iter().flat_map(|p| p.art.iter().map(|n| &**n));
|
||||
for n in a.doc.layers.iter().map(|l| &**l).chain(a.doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(&a.nodes) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind {
|
||||
inner.push(p.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
for p in inner {
|
||||
// Only the bytes the art keeps: its own file isn't looked for.
|
||||
let Some(blob) = a.doc.images.get(&p.key).filter(|b| !b.is_proxy()) else { continue };
|
||||
fonts.extend(nested_page_fonts(p.link.name(), &blob.bytes, &p.link.path, &vec![(p.page(), p.bounding, p.page_box)], depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,7 +344,7 @@ impl<'a> Collector<'a> {
|
||||
// Different linked documents can reuse the same stale absolute path yet
|
||||
// resolve it to distinct local assets. Keep a mapping per document.
|
||||
let mut local = BTreeMap::<String, Copied>::new();
|
||||
// The fonts of the type on the PDF and `.ai` pages placed linked.
|
||||
// The fonts of the type on the PDF, `.ai` and EPS pages placed linked.
|
||||
let mut placed_fonts = BTreeSet::new();
|
||||
let mut placed = BTreeMap::<String, PlacedPages>::new();
|
||||
let linked_files = |doc: &Document| match lookup {
|
||||
|
||||
@@ -260,6 +260,8 @@ thread_local! {
|
||||
pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Whether [`known`] is skipped on this thread ([`uncached`]).
|
||||
static UNCACHED: std::cell::Cell<bool> = 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<usize> = 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<char>, Vec<char>) = (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<usize>, Vec<usize>) = (Vec::new(), (0..=b.len()).collect());
|
||||
for (i, ca) in a.iter().enumerate() {
|
||||
let mut row = vec![i + 1];
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<Strin
|
||||
}
|
||||
|
||||
/// Give pattern `name` fresh-id copies of the selected art (or of `ids`) as its tile art, as one
|
||||
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch, tile and options,
|
||||
/// and its tile fits the new art when its Size Tile to Art is on; paints refer to a pattern by
|
||||
/// name, so every fill and stroke of it draws the new tile. The art stays where it is, selected as
|
||||
/// before. Art that matches the tile art already records nothing.
|
||||
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch and options. An
|
||||
/// unpainted rectangle at the back of the art becomes the tile ([`tile_and_art`]); without one the
|
||||
/// tile keeps its size and moves as far as the art's bounds moved from the old tile art's, so art
|
||||
/// drawn anywhere stays in its tile. With Size Tile to Art on, the tile fits the new art. Paints
|
||||
/// refer to a pattern by name, so every fill and stroke of it draws the new tile. The art stays
|
||||
/// where it is, selected as before. Art and a tile that match the pattern's already record nothing.
|
||||
fn pattern_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Arc<Node>> = 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<Node>]| 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<Arc<Node>> = 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<Arc<Node>>) -> (Vec<Arc<Node>>, Option<Rect>) {
|
||||
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<Value> {
|
||||
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> {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -487,10 +487,18 @@ fn operand_len(sprm: u16, rest: &[u8]) -> Option<usize> {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The Prls [`each_prl`] read on this thread.
|
||||
pub(crate) static PRLS_READ: std::cell::Cell<usize> = 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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file
|
||||
//! from a file, with `link`): one locked object showing an artboard of the document, a page of the
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`].
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`]. An EPS file whose bytes a `.ai` file's editing
|
||||
//! data includes opens as one too, read from those bytes.
|
||||
//!
|
||||
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
|
||||
//! art it shows is read from them the way placing the file without Link reads it
|
||||
@@ -223,6 +224,27 @@ impl Drop for Reading {
|
||||
}
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// How many placed documents [`read_document`] is reading inside one another on this thread.
|
||||
static DRAWING: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A placed document being read for drawing ([`DRAWING`]): the count goes down when this goes.
|
||||
struct Drawing;
|
||||
|
||||
impl Drawing {
|
||||
/// `None` when [`MAX_NESTED_READS`] are being read.
|
||||
fn enter() -> Option<Self> {
|
||||
DRAWING.with(|d| (d.get() < MAX_NESTED_READS).then(|| d.set(d.get() + 1))).map(|()| Drawing)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Drawing {
|
||||
fn drop(&mut self) {
|
||||
DRAWING.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads).
|
||||
fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
|
||||
let mut children: Vec<Arc<Node>> = nodes.into_iter().map(Arc::new).collect();
|
||||
@@ -234,11 +256,22 @@ fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
|
||||
|
||||
/// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents
|
||||
/// ([`vectorcraft_doc::placed_document::set_loader`]).
|
||||
/// `None` past [`MAX_NESTED_READS`] placed documents read inside one another: opening a file can
|
||||
/// draw the placed documents in it, whose files can place others.
|
||||
pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
let _drawing = Drawing::enter()?;
|
||||
#[cfg(test)]
|
||||
DOCUMENT_READS.with(|n| n.set(n.get() + 1));
|
||||
let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, "draw").ok()?;
|
||||
Some((a.doc, group(a.nodes, a.clip), a.frame))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// Placed documents read for drawing on this thread, for tests that count work.
|
||||
pub(crate) static DOCUMENT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `p`'s file read again, while it is the file it was read from (how the document model gets it
|
||||
/// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]).
|
||||
pub(crate) fn read_file_again(p: &PlacedDocument) -> Option<Vec<u8>> {
|
||||
|
||||
+222
-11
@@ -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);
|
||||
@@ -204,6 +207,36 @@ pub struct FilterRun {
|
||||
limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// What running a [`FilterRun`] away from the session takes ([`FilterRun::job`]).
|
||||
pub struct FilterJob {
|
||||
pub plugin: Arc<Plugin>,
|
||||
pub input: Vec<u8>,
|
||||
pub params: Vec<u8>,
|
||||
pub limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// The run of a filter that calls commands that holds the documents ([`FilterRun::begin_calls`]):
|
||||
/// the run, what its calls keep fixed, and its open undo step.
|
||||
pub(crate) struct Calling {
|
||||
/// The command that applies its output: `plugin.run`, or the plug-in command it runs, and the
|
||||
/// params it was started with, which that command must be given.
|
||||
cmd: String,
|
||||
params: Value,
|
||||
run: FilterRun,
|
||||
calls: super::plugin_call::Calls,
|
||||
tx: super::plugin_call::Transaction,
|
||||
}
|
||||
|
||||
/// A module that a load in another place checked ([`Session::hand_in_checked_plugin`]): its
|
||||
/// SHA-256 and the manifest JSON that load read.
|
||||
pub(crate) struct Checked {
|
||||
hash: String,
|
||||
manifest: Vec<u8>,
|
||||
}
|
||||
|
||||
/// How many checked modules the session keeps.
|
||||
const MAX_CHECKED: usize = 4;
|
||||
|
||||
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
|
||||
/// was made of: only a run of the same installation of the plug-in on the same input with the same
|
||||
/// parameters takes it (a plug-in's output depends on nothing else).
|
||||
@@ -338,6 +371,53 @@ impl FilterRun {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// The input JSON it gives the plug-in: the objects.
|
||||
pub fn input(&self) -> &[u8] {
|
||||
&self.input
|
||||
}
|
||||
|
||||
/// The parameters JSON it gives the plug-in, `_context` included.
|
||||
pub fn params(&self) -> &[u8] {
|
||||
&self.params
|
||||
}
|
||||
|
||||
/// What running it away from the session takes: the plug-in, its input and parameters, and the
|
||||
/// limits it runs under.
|
||||
pub fn job(&self) -> FilterJob {
|
||||
FilterJob { plugin: Arc::clone(&self.plugin), input: self.input.clone(), params: self.params.clone(), limits: self.limits.clone() }
|
||||
}
|
||||
|
||||
/// [`FilterRun::prepare_for`] command `c` (`plugin.run` or a plug-in command) of a filter that
|
||||
/// calls commands, which runs away from the session (the web build's plug-in worker) while the
|
||||
/// session makes its command calls ([`Session::plugin_call`]). The edit in progress is kept
|
||||
/// first, as `c` keeps it. The session then holds the run's undo step open and refuses every
|
||||
/// command but queries and `c` ([`EngineError::PluginBusy`]) until `c` applies the output handed
|
||||
/// in for it ([`Session::hand_in_plugin_calls`]) or [`Session::end_plugin_calls`] ends it → what
|
||||
/// running it takes.
|
||||
pub fn begin_calls(s: &mut Session, c: &str, p: &Value) -> Result<FilterJob> {
|
||||
if s.plugin_calls_open() {
|
||||
return Err(EngineError::PluginBusy);
|
||||
}
|
||||
let r = FilterRun::prepare_for(s, c, p)?;
|
||||
let r = if super::plugin_call::settle(s)? { FilterRun::prepare_for(s, c, p)? } else { r };
|
||||
let tx = super::plugin_call::Transaction::begin(s, &r.label())?;
|
||||
let may = r.plugin.manifest().permissions();
|
||||
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
|
||||
let job = r.job();
|
||||
s.plugin_calling = Some(Calling { cmd: c.to_string(), params: p.clone(), run: r, calls, tx });
|
||||
Ok(job)
|
||||
}
|
||||
|
||||
/// The run command `c`'s params `p` ask for: `plugin.run`'s ([`FilterRun::prepare`]), or a
|
||||
/// plug-in command's (`plugin.<id>.<command>`), on the active document.
|
||||
pub fn prepare_for(s: &Session, c: &str, p: &Value) -> Result<FilterRun> {
|
||||
if c == "plugin.run" {
|
||||
return FilterRun::prepare(s, p);
|
||||
}
|
||||
let (plugin, command) = command_of(c).ok_or_else(|| EngineError::UnknownCommand(c.into()))?;
|
||||
FilterRun::prepare_with(s, plugin, Some(command), c, p)
|
||||
}
|
||||
|
||||
/// The parameters it hands the plug-in, `_context` included.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn params_json(&self) -> Value {
|
||||
@@ -520,7 +600,10 @@ pub fn keep_unapplied_typing(s: &mut Session) -> Result<bool> {
|
||||
/// was applied, with the plug-in's name.
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An output handed in is for this run only (the app hands it in just before), whatever it does.
|
||||
let handed = s.plugin_output.take();
|
||||
let mut handed = s.plugin_output.take();
|
||||
if let Some(r) = end_held(s, "plugin.run", p, &mut handed) {
|
||||
return r;
|
||||
}
|
||||
let r = FilterRun::prepare(s, p)?;
|
||||
// One that calls commands runs here, where it can make them, on the document with any edit in
|
||||
// progress committed.
|
||||
@@ -540,6 +623,32 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
r.finish(s, &output)
|
||||
}
|
||||
|
||||
/// Ends the run that holds the documents ([`FilterRun::begin_calls`]) when command `c` (with params
|
||||
/// `p`, the params the run was started with) is the one that applies its output and `handed` is
|
||||
/// that output: applied in the run's own undo step, to the objects the run was given → the
|
||||
/// command's result. Any other command, or other params, is refused while a run holds them, and so
|
||||
/// is the output once the plug-in is no longer installed as the run had it. `None`: no run holds
|
||||
/// them.
|
||||
fn end_held(s: &mut Session, c: &str, p: &Value, handed: &mut Option<HandedIn>) -> Option<Result<Value>> {
|
||||
let held = s.plugin_calling.take()?;
|
||||
let serial = held.run.plugin.serial();
|
||||
let installed = registry::get(held.run.plugin.id()).is_some_and(|plugin| plugin.serial() == serial);
|
||||
let same = held.cmd == c && *p == held.params && installed;
|
||||
let mine = handed.take().filter(|h| same && (h.serial, &h.input, &h.params) == (serial, &held.run.input, &held.run.params));
|
||||
let Some(h) = mine else {
|
||||
s.plugin_calling = Some(held);
|
||||
return Some(Err(EngineError::PluginBusy));
|
||||
};
|
||||
let Calling { cmd, run, calls, tx, .. } = held;
|
||||
// A panic applying the output still ends the run, so what its calls did is undone.
|
||||
let r = if calls.kept(s) {
|
||||
crate::guard::catch_panic(|| run.finish(s, &h.output)).unwrap_or_else(|msg| Err(EngineError::Internal { cmd, msg }))
|
||||
} else {
|
||||
Err(EngineError::Cancelled)
|
||||
};
|
||||
Some(tx.end(s, r))
|
||||
}
|
||||
|
||||
/// The command id of plug-in `plugin`'s command `command`: `plugin.<plugin>.<command>`.
|
||||
pub fn command_id(plugin: &str, command: &str) -> String {
|
||||
format!("{}{plugin}.{command}", vectorcraft_plugins::PREFIX)
|
||||
@@ -931,10 +1040,11 @@ fn unrouted(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named
|
||||
/// after the command → `{plugin, command, ids, notice?, pluginName?}`. A run that fails (a trap, an exhausted
|
||||
/// budget, an output it may not make) leaves the document as it was, and the error names the
|
||||
/// plug-in and the command.
|
||||
/// plug-in and the command. An output handed in for this very run ([`FilterRun::hand_in`]) is
|
||||
/// applied instead of running the plug-in, as `plugin.run` applies one.
|
||||
pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
// An output handed in is for `plugin.run` alone.
|
||||
s.plugin_output = None;
|
||||
// An output handed in is for this run only, whatever it does.
|
||||
let mut handed = s.plugin_output.take();
|
||||
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
let failed = {
|
||||
let (name, label) = (permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME), command.shown_label());
|
||||
@@ -943,6 +1053,9 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
e => EngineError::Other(format!("“{name}” › {label}: {e}")),
|
||||
}
|
||||
};
|
||||
if let Some(r) = end_held(s, id, p, &mut handed) {
|
||||
return r.map_err(failed);
|
||||
}
|
||||
let r = FilterRun::prepare_with(s, plugin, Some(command), id, p)?;
|
||||
if r.calls() {
|
||||
let r = match super::plugin_call::settle(s)? {
|
||||
@@ -961,7 +1074,11 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
}
|
||||
false => r,
|
||||
};
|
||||
let output = r.run().map_err(&failed)?;
|
||||
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
|
||||
let output = match handed {
|
||||
Some(h) => h.output,
|
||||
None => r.run().map_err(&failed)?,
|
||||
};
|
||||
r.finish(s, &output).map_err(failed)
|
||||
}
|
||||
|
||||
@@ -1022,15 +1139,22 @@ const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4;
|
||||
pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT];
|
||||
|
||||
/// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a
|
||||
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source).
|
||||
fn load_given(c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
|
||||
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). A module that a
|
||||
/// load in another place checked ([`Session::hand_in_checked_plugin`]) runs none of its code here.
|
||||
fn load_given(s: &Session, c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
|
||||
match (str_param(p, "path").filter(|s| !s.is_empty()), str_param(p, "dataBase64")) {
|
||||
(_, Some(data)) => {
|
||||
if data.len() > MAX_DATA_CHARS {
|
||||
return Err(bad(c, "`dataBase64` is larger than the module limit"));
|
||||
}
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(c, "`dataBase64` is not valid base64"))?;
|
||||
let plugin = Plugin::load(&bytes, vectorcraft_plugins::Limits::default()).map_err(err)?;
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let hash = permissions::sha256_hex(&bytes);
|
||||
let plugin = match s.plugin_checked.iter().find(|k| k.hash == hash) {
|
||||
Some(k) => Plugin::load_checked(&bytes, limits, &k.manifest),
|
||||
None => Plugin::load(&bytes, limits),
|
||||
}
|
||||
.map_err(err)?;
|
||||
let plugin = match str_param(p, "name") {
|
||||
Some(name) => plugin.with_source(name),
|
||||
None => plugin,
|
||||
@@ -1078,6 +1202,93 @@ impl InstallApproval {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Hands in the manifest JSON `manifest` that a load of the module with SHA-256 `hash` read in
|
||||
/// another place (the web build's plug-in worker, [`vectorcraft_plugins::worker`]): a
|
||||
/// `plugin.inspect` or `plugin.install` of those very bytes (`dataBase64`) then loads the module
|
||||
/// with [`Plugin::load_checked`], which runs none of its code here. The newest
|
||||
/// [`MAX_CHECKED`] are kept.
|
||||
pub fn hand_in_checked_plugin(&mut self, hash: &str, manifest: Vec<u8>) {
|
||||
self.plugin_checked.retain(|c| c.hash != hash);
|
||||
if self.plugin_checked.len() >= MAX_CHECKED {
|
||||
self.plugin_checked.remove(0);
|
||||
}
|
||||
self.plugin_checked.push(Checked { hash: hash.to_string(), manifest });
|
||||
}
|
||||
|
||||
/// Has a load in another place checked the module with SHA-256 `hash`
|
||||
/// ([`Session::hand_in_checked_plugin`])?
|
||||
pub fn plugin_checked(&self, hash: &str) -> bool {
|
||||
self.plugin_checked.iter().any(|c| c.hash == hash)
|
||||
}
|
||||
|
||||
/// Does a plug-in run that calls commands hold the documents ([`FilterRun::begin_calls`])?
|
||||
pub fn plugin_calls_open(&self) -> bool {
|
||||
self.plugin_calling.is_some()
|
||||
}
|
||||
|
||||
/// Applies the edit the active tool computes on another thread (a Shape Builder merge), as a
|
||||
/// command that edits waits for it, and keeps the edit in progress (a drag, a preview, typing)
|
||||
/// as its own undo step, as a run that calls commands does before it starts, so a run made away
|
||||
/// from the session is given the document with them and applies as an undo step of its own →
|
||||
/// whether that changed the document or the selection.
|
||||
pub fn settle_for_plugin_run(&mut self) -> Result<bool> {
|
||||
let before = self.active().map(|d| (Arc::clone(&d.doc), d.selection.clone()));
|
||||
self.finish_tool_edit_later()?;
|
||||
let finished = match (&before, self.active()) {
|
||||
(Some((doc, selection)), Some(d)) => !Arc::ptr_eq(doc, &d.doc) || *selection != d.selection,
|
||||
(None, None) => false,
|
||||
_ => true,
|
||||
};
|
||||
Ok(super::plugin_call::settle(self)? || finished)
|
||||
}
|
||||
|
||||
/// Is command `id` the one that applies the output of the run that holds the documents?
|
||||
pub fn plugin_calls_end_with(&self, id: &str) -> bool {
|
||||
self.plugin_calling.as_ref().is_some_and(|c| c.cmd == id)
|
||||
}
|
||||
|
||||
/// Makes the command call `id` with `args` that the run [`FilterRun::begin_calls`] started asked
|
||||
/// for, as a call of that run on the page makes it → its result, or why it didn't run. With no
|
||||
/// such run, nothing runs.
|
||||
pub fn plugin_call(&mut self, id: &str, args: &Value) -> std::result::Result<Value, vectorcraft_plugins::host::CallFailure> {
|
||||
let Some(c) = self.plugin_calling.take() else {
|
||||
return Err(vectorcraft_plugins::host::CallFailure {
|
||||
code: vectorcraft_plugins::host::CALL_NO_CONTEXT,
|
||||
why: EngineError::Cancelled.to_string(),
|
||||
});
|
||||
};
|
||||
// As a step of `plugin.run`: not journaled on its own, and a panic fails the call.
|
||||
let depth = self.depth;
|
||||
self.depth += 1;
|
||||
let r = crate::guard::catch_panic(|| super::plugin_call::call(self, &c.calls, id, args));
|
||||
self.depth = depth;
|
||||
self.plugin_calling = Some(c);
|
||||
r.unwrap_or_else(|msg| {
|
||||
let why = EngineError::Internal { cmd: id.to_string(), msg }.to_string();
|
||||
Err(vectorcraft_plugins::host::CallFailure { code: vectorcraft_plugins::host::CALL_COMMAND_FAILED, why })
|
||||
})
|
||||
}
|
||||
|
||||
/// Hands in `output`, the output of the run [`FilterRun::begin_calls`] started, for the next run
|
||||
/// of the command that started it, with that run's params, to apply in its undo step.
|
||||
pub fn hand_in_plugin_calls(&mut self, output: Vec<u8>) {
|
||||
if let Some(c) = &self.plugin_calling {
|
||||
let r = &c.run;
|
||||
self.plugin_output = Some(HandedIn { serial: r.plugin.serial(), input: r.input.clone(), params: r.params.clone(), output });
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the run [`FilterRun::begin_calls`] started, which has no output (it failed, or was
|
||||
/// canceled): every document and the session state go back to how they were before it.
|
||||
pub fn end_plugin_calls(&mut self) {
|
||||
if let Some(c) = self.plugin_calling.take() {
|
||||
// An output handed in for it is dropped with it: a later run with the same input and
|
||||
// params is not given it.
|
||||
self.plugin_output = None;
|
||||
let _ = c.tx.end(self, Err(EngineError::Cancelled));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets the next `plugin.install` take its `grant` and `allowHeavy`, for the module `approval`
|
||||
/// describes. Call it only with what a person approved, just before that install.
|
||||
pub fn approve_plugin_install(&mut self, approval: InstallApproval) {
|
||||
@@ -1187,7 +1398,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let allow_heavy = switch_or(p, "allowHeavy", false, C)?;
|
||||
let grant = grant_param(C, p)?;
|
||||
let (plugin, bytes) = load_given(C, p)?;
|
||||
let (plugin, bytes) = load_given(s, C, p)?;
|
||||
// `hash` pins the module the user was shown: one with other bytes is refused.
|
||||
if let Some(h) = p.get("hash").filter(|v| !v.is_null())
|
||||
&& h.as_str() != Some(plugin.hash())
|
||||
@@ -1384,7 +1595,7 @@ pub(crate) fn keep_installed(s: &Session, turn: &StoreTurn, id: &str, bytes: &[u
|
||||
/// needs the user to grant its permissions first (`needsApproval`) and whether it would take
|
||||
/// another module's place (`needsReplace`).
|
||||
fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
load_given("plugin.inspect", p).map(|(plugin, _)| {
|
||||
load_given(s, "plugin.inspect", p).map(|(plugin, _)| {
|
||||
let mut v = describe(&plugin);
|
||||
v["needsApproval"] = json!(!s.plugin_approved(&plugin));
|
||||
v["needsReplace"] = json!(takes_over(s, &plugin));
|
||||
@@ -2191,7 +2402,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), 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.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), 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)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), 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.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), 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
|
||||
),
|
||||
|
||||
@@ -424,7 +424,7 @@ impl Calls {
|
||||
|
||||
/// Is `s` still as the run needs it: the same documents open, the same one active and the
|
||||
/// interaction holding the run's changes still open?
|
||||
fn kept(&self, s: &Session) -> bool {
|
||||
pub(crate) fn kept(&self, s: &Session) -> bool {
|
||||
s.active().map(|d| d.uid) == self.document
|
||||
&& s.docs.iter().map(|d| d.uid).eq(self.open.iter().copied())
|
||||
&& (!self.interaction || s.in_interaction())
|
||||
@@ -476,44 +476,77 @@ fn execute_confined(s: &mut Session, id: &str, args: &Value) -> Result<Value> {
|
||||
/// changes. A trace handed in for the next Image Trace is set aside while `f` runs, so a call
|
||||
/// traces anew, and handed back after; the next Image Trace still checks it was made of its inputs.
|
||||
pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
|
||||
if s.active().is_some() && !s.previewing {
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let own = s.active().is_some() && !s.previewing && !s.in_interaction();
|
||||
if own {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
let saved = Saved::of(s);
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
let trace = s.trace_hand_off.take();
|
||||
let t = Transaction::begin(s, label)?;
|
||||
let r = f(s);
|
||||
s.trace_hand_off = trace;
|
||||
match r {
|
||||
Ok(v) => {
|
||||
if own
|
||||
&& let Some(st) = s.active_mut()
|
||||
&& let Some(it) = st.interaction.take()
|
||||
{
|
||||
st.keep_interaction(it);
|
||||
}
|
||||
Ok(v)
|
||||
t.end(s, r)
|
||||
}
|
||||
|
||||
/// A [`transaction`] that stays open between calls: [`Transaction::begin`] starts it, and
|
||||
/// [`Transaction::end`] keeps or undoes what was done meanwhile. A run of a plug-in that calls
|
||||
/// commands from the web build's plug-in worker holds one while it waits for the worker.
|
||||
pub(crate) struct Transaction {
|
||||
own: bool,
|
||||
saved: Saved,
|
||||
start: Vec<crate::DocState>,
|
||||
active: Option<usize>,
|
||||
trace: Option<super::Traced>,
|
||||
}
|
||||
|
||||
impl Transaction {
|
||||
/// Starts one undo step named `label` in the active document, as [`transaction`] does before it
|
||||
/// runs its function.
|
||||
pub(crate) fn begin(s: &mut Session, label: &str) -> Result<Transaction> {
|
||||
if s.active().is_some() && !s.previewing {
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
Err(e) => {
|
||||
let open = std::mem::replace(&mut s.docs, start);
|
||||
for st in &mut s.docs {
|
||||
// Past the newest revision the document reached, so the restored one redraws.
|
||||
let newest = open.iter().filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision);
|
||||
st.revision = newest.max(st.revision).saturating_add(1);
|
||||
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
|
||||
let own = s.active().is_some() && !s.previewing && !s.in_interaction();
|
||||
if own {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
let saved = Saved::of(s);
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
let trace = s.trace_hand_off.take();
|
||||
Ok(Transaction { own, saved, start, active, trace })
|
||||
}
|
||||
|
||||
/// Ends it with `r`, what was done in it: kept as one undo step when it succeeded, else every
|
||||
/// document and the session state go back to how they were when it began → `r`.
|
||||
pub(crate) fn end(self, s: &mut Session, r: Result<Value>) -> Result<Value> {
|
||||
let Transaction { own, saved, start, active, trace } = self;
|
||||
s.trace_hand_off = trace;
|
||||
match r {
|
||||
Ok(v) => {
|
||||
if own
|
||||
&& let Some(st) = s.active_mut()
|
||||
&& let Some(it) = st.interaction.take()
|
||||
{
|
||||
st.keep_interaction(it);
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
s.active = active;
|
||||
if own && let Some(st) = s.active_mut() {
|
||||
st.interaction = None;
|
||||
Err(e) => {
|
||||
let open = std::mem::replace(&mut s.docs, start);
|
||||
for st in &mut s.docs {
|
||||
// Past the newest revision the document reached, so the restored one redraws. A
|
||||
// document the transaction left as it was keeps its revision, so a run made
|
||||
// away from the session on it still applies.
|
||||
let reached: Vec<_> = open.iter().filter(|d| d.uid == st.uid).collect();
|
||||
let unchanged = !reached.is_empty() && reached.iter().all(|d| d.revision == st.revision && d.selection == st.selection);
|
||||
if !unchanged {
|
||||
let newest = reached.iter().map(|d| d.revision).max().unwrap_or(st.revision);
|
||||
st.revision = newest.max(st.revision).saturating_add(1);
|
||||
}
|
||||
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
|
||||
}
|
||||
s.active = active;
|
||||
if own && let Some(st) = s.active_mut() {
|
||||
st.interaction = None;
|
||||
}
|
||||
saved.restore(s);
|
||||
s.sync_front_profiles();
|
||||
Err(e)
|
||||
}
|
||||
saved.restore(s);
|
||||
s.sync_front_profiles();
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
];
|
||||
|
||||
@@ -294,7 +294,7 @@ impl Line {
|
||||
let mut origins = |text: String| -> Vec<Point> {
|
||||
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<Point> {
|
||||
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<usize> {
|
||||
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<usize> = 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<GlyphMatch> = 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;
|
||||
|
||||
@@ -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<String> = 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<String> = 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
|
||||
|
||||
@@ -455,6 +455,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<VariableKind> {
|
||||
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<String> {
|
||||
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<Value> {
|
||||
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<String> = 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<Option<String>> {
|
||||
let name = optional_name(p, "variable", cmd)?;
|
||||
@@ -694,13 +761,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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<Value> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -3,6 +3,9 @@ use super::{NodeId, cancel};
|
||||
/// The text of [`EngineError::Busy`], which ends every error a frontend reports for it.
|
||||
pub const SCRIPT_BUSY: &str = "a script is running: stop it or wait for it to finish";
|
||||
|
||||
/// The text of [`EngineError::PluginBusy`].
|
||||
pub const PLUGIN_BUSY: &str = "a plug-in is running: cancel it or wait for it to finish";
|
||||
|
||||
/// Stable prefix for a save refused by the filesystem: choose another destination.
|
||||
pub const READ_ONLY_LOCATION: &str = "READ_ONLY_LOCATION";
|
||||
|
||||
@@ -33,6 +36,10 @@ pub enum EngineError {
|
||||
/// A running script holds the documents until it ends. Nothing was changed.
|
||||
#[error("{}", SCRIPT_BUSY)]
|
||||
Busy,
|
||||
/// A plug-in run that calls commands holds the documents until it ends
|
||||
/// ([`crate::cmd::plugin::FilterRun::begin_calls`]). Nothing was changed.
|
||||
#[error("{}", PLUGIN_BUSY)]
|
||||
PluginBusy,
|
||||
/// A bug: the command panicked. The document was rolled back to its state before the command.
|
||||
#[error("internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug)")]
|
||||
Internal { cmd: String, msg: String },
|
||||
|
||||
@@ -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)?;
|
||||
}
|
||||
|
||||
@@ -247,6 +247,12 @@ pub struct Session {
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
/// The modules a load in another place checked, with the manifest it read
|
||||
/// ([`Session::hand_in_checked_plugin`]), the newest last.
|
||||
plugin_checked: Vec<cmd::plugin::Checked>,
|
||||
/// The run of a filter that calls commands that holds the documents while the web build's
|
||||
/// plug-in worker runs it ([`cmd::plugin::FilterRun::begin_calls`]).
|
||||
plugin_calling: Option<cmd::plugin::Calling>,
|
||||
/// What a person approved for the next `plugin.install` ([`Session::approve_plugin_install`]);
|
||||
/// that install spends it, whatever it does.
|
||||
plugin_install_approval: Option<cmd::plugin::InstallApproval>,
|
||||
|
||||
+396
-107
@@ -6,9 +6,10 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describe them.
|
||||
//!
|
||||
//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the
|
||||
//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the
|
||||
//! document and the object up again. An object that was deleted, a document that was closed and an
|
||||
//! object from an earlier run of a named engine throw an error on every member. Every change runs
|
||||
//! document's [`crate::DocState::uid`] and, for art and layers, the object's id and the document's
|
||||
//! [`crate::DocState::reverts`], and every read looks the document and the
|
||||
//! object up again. An object that was deleted, a document that was closed, an object from before
|
||||
//! File › Revert and an object from an earlier run of a named engine throw an error on every member. Every change runs
|
||||
//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each
|
||||
//! changed document; a change that changes nothing runs no command. A change to a document that is
|
||||
//! not the active one makes it active for the command and makes the other one active again after.
|
||||
@@ -29,7 +30,8 @@
|
||||
//! false then. Assigning to such a name throws the same error.
|
||||
//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the
|
||||
//! active document's selection. A top-level `var selection = ...` does the same and does
|
||||
//! not make a variable of the script. Assigning `documents` keeps its value.
|
||||
//! not make a variable of the script. An assignment to `documents` is ignored outside strict
|
||||
//! mode and throws a `TypeError` in strict mode code or with `#strict on`.
|
||||
//! - After `documents[0]`, documents are listed from the one active most recently to the one
|
||||
//! active longest ago. A change a script makes to a document in the back does not move it.
|
||||
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
|
||||
@@ -41,8 +43,11 @@
|
||||
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
//! - `app.activeDocument` with no document open throws `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so.
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
|
||||
//! leaves them out.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change
|
||||
//! nothing, even for the value the object has. The exception is `opacity` given the value the
|
||||
@@ -54,6 +59,10 @@
|
||||
//! - A compound path whose last path `move` or `remove()` takes out stays, empty.
|
||||
//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out,
|
||||
//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing.
|
||||
//! - `reflect` on an object or a class gives each member's type from the declaration that installs
|
||||
//! the member ([`classes`]): a class name, `boolean`, `number`, `string`, `Array` for a list of
|
||||
//! numbers, the enumeration's name for an enumerated value, and `*` where the value can be of
|
||||
//! more than one type.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -62,12 +71,28 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts};
|
||||
use vectorcraft_js::{
|
||||
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
|
||||
};
|
||||
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
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<crate::doc::DataSet>)> {
|
||||
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<crate::doc::DataSet>)>) {
|
||||
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 +143,9 @@ 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, with the size of the values they hold
|
||||
/// now and the most they may hold (the run's heap), and the `Variable` and `Dataset` objects it
|
||||
/// gave out.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
@@ -126,9 +153,17 @@ pub(super) struct State {
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The state of a run whose heap is `heap_bytes`.
|
||||
pub(super) fn new(heap_bytes: usize) -> Self {
|
||||
Self { preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
}
|
||||
|
||||
/// Whether a call's own savepoint is open: its commands take none of their own.
|
||||
pub(super) fn saving(&self) -> bool {
|
||||
self.saving.get()
|
||||
@@ -137,20 +172,25 @@ impl State {
|
||||
|
||||
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
|
||||
/// document, the selection and the undo histories are as they were before it, with no undo step
|
||||
/// and no change to the document's saved state.
|
||||
/// and no change to the document's saved state, and the growth its commands were charged is not
|
||||
/// counted.
|
||||
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
if h.dom.saving.get() {
|
||||
return f(h);
|
||||
}
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let mark = h.growth_mark();
|
||||
h.dom.saving.set(true);
|
||||
let r = f(h);
|
||||
h.dom.saving.set(false);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
} else {
|
||||
h.put_growth_back(mark);
|
||||
if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
@@ -235,10 +275,24 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(function(link, f))
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
MemberInfo { data_type: data_type.into(), ..MemberInfo::default() }
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it,
|
||||
/// so a script that checks for the member first skips it.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) {
|
||||
/// so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -255,7 +309,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM
|
||||
}
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f))
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
fn text(s: impl Into<String>) -> Data {
|
||||
@@ -368,12 +422,27 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result<Doc, HostError
|
||||
}
|
||||
}
|
||||
|
||||
fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [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<Item, HostError> {
|
||||
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 +479,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,
|
||||
}
|
||||
@@ -572,6 +641,8 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
.map(|i| {
|
||||
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
|
||||
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
|
||||
// A path with only segments selected gets them back below, with no anchors.
|
||||
None if before.segments.contains_key(i) => Vec::new(),
|
||||
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
|
||||
};
|
||||
json!({"id": i.0, "anchors": anchors})
|
||||
@@ -1150,17 +1221,42 @@ fn new_preset(h: &Host) -> Answer {
|
||||
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
|
||||
}
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
presets.push(vec![
|
||||
let fields = vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
]);
|
||||
];
|
||||
hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?;
|
||||
presets.push(fields);
|
||||
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
|
||||
}
|
||||
|
||||
/// Counts that the run's presets now hold `added` bytes of values in place of `replaced`, and
|
||||
/// refuses when they would hold more than the run's heap.
|
||||
fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result<(), HostError> {
|
||||
let total = h.dom.preset_bytes.get().saturating_sub(replaced).saturating_add(added);
|
||||
if total > h.dom.preset_limit {
|
||||
return Err(HostError::Range(format!("the DocumentPreset settings would hold more than {} bytes", h.dom.preset_limit)));
|
||||
}
|
||||
h.dom.preset_bytes.set(total);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bytes the host's copy of `d` takes: a `Data` for the value and each element or property
|
||||
/// in it, plus the text of its strings and property names.
|
||||
fn held_bytes(d: &Data) -> u64 {
|
||||
let owned = match d {
|
||||
Data::String(s) => s.len() as u64,
|
||||
Data::Array(a) => a.iter().map(held_bytes).sum(),
|
||||
Data::Object(o) => o.iter().map(|(k, v)| (size_of::<String>() + k.len()) as u64 + held_bytes(v)).sum(),
|
||||
Data::Undefined | Data::Null | Data::Bool(_) | Data::Number(_) => 0,
|
||||
};
|
||||
size_of::<Data>() as u64 + owned
|
||||
}
|
||||
|
||||
/// The most `DocumentPreset` objects one run can make.
|
||||
const MAX_PRESETS: usize = 10_000;
|
||||
|
||||
@@ -1267,8 +1363,12 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
|
||||
check_preset_value(key, &value)?;
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
let fields = &mut presets[i];
|
||||
match fields.iter_mut().find(|(k, _)| k == key) {
|
||||
Some((_, v)) => *v = value,
|
||||
// The values the presets hold now count against the run's heap: a value assigned again
|
||||
// replaces the one before it.
|
||||
let at = fields.iter().position(|(k, _)| k == key);
|
||||
hold_preset_bytes(&h, at.map_or(0, |n| held_bytes(&fields[n].1)), held_bytes(&value))?;
|
||||
match at {
|
||||
Some(n) => fields[n].1 = value,
|
||||
None => fields.push((key.to_string(), value)),
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
@@ -1416,10 +1516,12 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
}
|
||||
|
||||
/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or
|
||||
/// `[]`. Every one must be an object of that document that can be selected.
|
||||
/// `[]`. Every one must be an object of that document that can be selected. `undefined`, such as
|
||||
/// an index past the end of `pageItems`, is refused and clears nothing.
|
||||
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
let list: Vec<&Data> = match v {
|
||||
Data::Null => Vec::new(),
|
||||
Data::Undefined => return Err(HostError::Type("a selection is a page item, a list of them, null or []".into())),
|
||||
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
|
||||
Data::Array(a) => a.iter().collect(),
|
||||
d => vec![d],
|
||||
@@ -1440,6 +1542,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
|
||||
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
|
||||
}
|
||||
// Repeated objects are kept once.
|
||||
if seen.insert(item.id) {
|
||||
ids.push(item.id);
|
||||
}
|
||||
@@ -1778,6 +1881,26 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
|
||||
bounds(h, a, true)
|
||||
}
|
||||
|
||||
/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in
|
||||
/// the object.
|
||||
fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
// An object with nothing in it reads zeros, as its other bounds do.
|
||||
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
|
||||
let r = with_doc(h, item.doc, |_, st| {
|
||||
let mut r = r;
|
||||
if let Some(n) = st.doc.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) {
|
||||
r = r.union(handles);
|
||||
}
|
||||
});
|
||||
}
|
||||
r
|
||||
});
|
||||
Ok(f.bounds(h.dom.coords.get(), r))
|
||||
}
|
||||
|
||||
fn item_position(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
match item_rect(h, item, false)? {
|
||||
@@ -1958,17 +2081,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 +2256,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())))
|
||||
}
|
||||
|
||||
@@ -2174,12 +2296,30 @@ fn typename_of(name: &'static str) -> HostMember {
|
||||
HostMember::Get(Rc::new(move |_| Ok(text(name))))
|
||||
}
|
||||
|
||||
fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option<HostFunction>) -> HostClass {
|
||||
HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None }
|
||||
fn class(name: &str, parent: Option<&str>, members: Vec<Described>, index: Option<HostFunction>) -> HostClass {
|
||||
let info = members.iter().map(|(n, _, i)| (n.clone(), i.clone())).collect();
|
||||
let members = members.into_iter().map(|(n, m, _)| (n, m)).collect();
|
||||
HostClass { name: name.into(), parent: parent.map(Into::into), members, info, index, construct: None }
|
||||
}
|
||||
|
||||
fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> {
|
||||
items.into_iter().map(|(n, m)| (n.to_string(), m)).collect()
|
||||
fn named(items: Vec<(&str, HostMember, MemberInfo)>) -> Vec<Described> {
|
||||
items.into_iter().map(|(n, m, i)| (n.to_string(), m, i)).collect()
|
||||
}
|
||||
|
||||
/// The type of a `DocumentPreset` field's value.
|
||||
fn preset_type(field: &str) -> &'static str {
|
||||
match field {
|
||||
"artboardLayout" => "DocumentArtboardLayout",
|
||||
"colorMode" => "DocumentColorSpace",
|
||||
"documentBleedLink" => "boolean",
|
||||
"documentBleedOffsetRect" => "Array",
|
||||
"previewMode" => "DocumentPreviewMode",
|
||||
"rasterResolution" => "DocumentRasterResolution",
|
||||
"title" => "string",
|
||||
"transparencyGrid" => "DocumentTransparencyGrid",
|
||||
"units" => "RulerUnits",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
/// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings.
|
||||
@@ -2216,16 +2356,30 @@ 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)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
realm.define_host_globals(vec![
|
||||
("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))),
|
||||
("documents".into(), function(l, app_documents), None),
|
||||
("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))),
|
||||
])
|
||||
}
|
||||
|
||||
/// The classes of the object model, each member with the type `reflect` gives for it.
|
||||
fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let l = link;
|
||||
let placement = [("relativeObject", "*"), ("insertionLocation", "ElementPlacement")];
|
||||
let mut application = named(vec![
|
||||
("typename", typename_of("Application")),
|
||||
("documents", get(l, app_documents)),
|
||||
("activeDocument", property(l, app_active, app_set_active)),
|
||||
("selection", property(l, app_selection, app_set_selection)),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords)),
|
||||
("getIsFileOpen", method(l, app_is_open)),
|
||||
("executeMenuCommand", method(l, app_menu_command)),
|
||||
("toString", class_text("Application")),
|
||||
("typename", typename_of("Application"), typed("string")),
|
||||
("documents", get(l, app_documents), MemberInfo { collection: true, ..typed("Documents") }),
|
||||
("activeDocument", property(l, app_active, app_set_active), typed("Document")),
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
application.push(later(l, "Application", "beep"));
|
||||
let preset = {
|
||||
@@ -2235,9 +2389,12 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
h.charge_call(64)?;
|
||||
new_preset(&h)
|
||||
});
|
||||
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))];
|
||||
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k))));
|
||||
HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) }
|
||||
let mut members = vec![
|
||||
("typename".to_string(), typename_of("DocumentPreset"), typed("string")),
|
||||
("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])),
|
||||
];
|
||||
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k)))));
|
||||
HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) }
|
||||
};
|
||||
let mut classes = vec![
|
||||
class("Application", None, application, None),
|
||||
@@ -2246,78 +2403,108 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
"Documents",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of("Documents")),
|
||||
("length", get(l, docs_length)),
|
||||
("parent", get(l, app_ref)),
|
||||
("index", method(l, docs_index)),
|
||||
("getByName", method(l, docs_by_name)),
|
||||
("add", method(l, docs_add)),
|
||||
("addDocument", method(l, docs_add_document)),
|
||||
("toString", class_text("Documents")),
|
||||
("typename", typename_of("Documents"), typed("string")),
|
||||
("length", get(l, docs_length), typed("number")),
|
||||
("parent", get(l, app_ref), typed("Application")),
|
||||
("index", method(l, docs_index), returns("Document", &[("itemKey", "*")])),
|
||||
("getByName", method(l, docs_by_name), returns("Document", &[("name", "string")])),
|
||||
(
|
||||
"add",
|
||||
method(l, docs_add),
|
||||
returns(
|
||||
"Document",
|
||||
&[
|
||||
("colorSpace", "DocumentColorSpace"),
|
||||
("width", "number"),
|
||||
("height", "number"),
|
||||
("numArtBoards", "number"),
|
||||
("artboardLayout", "DocumentArtboardLayout"),
|
||||
("artboardSpacing", "number"),
|
||||
("artboardRowsOrCols", "number"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"addDocument",
|
||||
method(l, docs_add_document),
|
||||
returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]),
|
||||
),
|
||||
("toString", class_text("Documents"), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, docs_at)),
|
||||
),
|
||||
];
|
||||
let mut document = named(vec![
|
||||
("typename", get(l, doc_typename)),
|
||||
("parent", get(l, doc_parent)),
|
||||
("name", get(l, doc_name)),
|
||||
("width", get(l, doc_width)),
|
||||
("height", get(l, doc_height)),
|
||||
("rulerUnits", get(l, doc_units)),
|
||||
("documentColorSpace", get(l, doc_color_space)),
|
||||
("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)),
|
||||
("convertCoordinate", method(l, doc_convert)),
|
||||
("pageItems", get(l, doc_page_items)),
|
||||
("selection", property(l, doc_selection, doc_set_selection)),
|
||||
("toString", method(l, doc_to_string)),
|
||||
("typename", get(l, doc_typename), typed("string")),
|
||||
("parent", get(l, doc_parent), typed("Application")),
|
||||
("name", get(l, doc_name), typed("string")),
|
||||
("width", get(l, doc_width), typed("number")),
|
||||
("height", get(l, doc_height), typed("number")),
|
||||
("rulerUnits", get(l, doc_units), typed("RulerUnits")),
|
||||
("documentColorSpace", get(l, doc_color_space), typed("DocumentColorSpace")),
|
||||
("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin), typed("Array")),
|
||||
(
|
||||
"convertCoordinate",
|
||||
method(l, doc_convert),
|
||||
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.push(("tags".into(), get(l, tags::doc_tags)));
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
"PageItems",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, items_typename)),
|
||||
("length", get(l, items_length)),
|
||||
("parent", get(l, items_parent)),
|
||||
("index", method(l, items_index)),
|
||||
("getByName", method(l, items_by_name)),
|
||||
("removeAll", method(l, items_remove_all)),
|
||||
("toString", method(l, items_to_string)),
|
||||
("typename", get(l, items_typename), typed("string")),
|
||||
("length", get(l, items_length), typed("number")),
|
||||
("parent", get(l, items_parent), typed("Document")),
|
||||
("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
("toString", method(l, items_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, items_at)),
|
||||
));
|
||||
let mut page_item = named(vec![
|
||||
("typename", get(l, item_typename)),
|
||||
("parent", get(l, item_parent)),
|
||||
("name", property(l, item_name, item_set_name)),
|
||||
("note", property(l, item_note, item_set_note)),
|
||||
("tags", get(l, tags::item_tags)),
|
||||
("hidden", property(l, item_hidden, item_set_hidden)),
|
||||
("locked", property(l, item_locked, item_set_locked)),
|
||||
("selected", property(l, item_selected, item_set_selected)),
|
||||
("opacity", property(l, item_opacity, item_set_opacity)),
|
||||
("position", property(l, item_position, item_set_position)),
|
||||
("left", property(l, item_left, item_set_left)),
|
||||
("top", property(l, item_top, item_set_top)),
|
||||
("width", property(l, item_width, item_set_width)),
|
||||
("height", property(l, item_height, item_set_height)),
|
||||
("geometricBounds", get(l, item_geometric)),
|
||||
("visibleBounds", get(l, item_visible)),
|
||||
("controlBounds", get(l, item_visible)),
|
||||
("editable", get(l, item_editable)),
|
||||
("zOrderPosition", get(l, item_z_order_position)),
|
||||
("duplicate", method(l, item_duplicate)),
|
||||
("move", method(l, item_move)),
|
||||
("remove", method(l, item_remove)),
|
||||
("zOrder", method(l, item_z_order)),
|
||||
("toString", method(l, item_to_string)),
|
||||
("typename", get(l, item_typename), typed("string")),
|
||||
("parent", get(l, item_parent), typed("*")),
|
||||
("name", property(l, item_name, item_set_name), typed("string")),
|
||||
("note", property(l, item_note, item_set_note), typed("string")),
|
||||
("tags", get(l, tags::item_tags), MemberInfo { collection: true, ..typed("Tags") }),
|
||||
("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")),
|
||||
("locked", property(l, item_locked, item_set_locked), typed("boolean")),
|
||||
("selected", property(l, item_selected, item_set_selected), typed("boolean")),
|
||||
("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("position", property(l, item_position, item_set_position), typed("Array")),
|
||||
("left", property(l, item_left, item_set_left), typed("number")),
|
||||
("top", property(l, item_top, item_set_top), typed("number")),
|
||||
("width", property(l, item_width, item_set_width), typed("number")),
|
||||
("height", property(l, item_height, item_set_height), typed("number")),
|
||||
("geometricBounds", get(l, item_geometric), typed("Array")),
|
||||
("visibleBounds", get(l, item_visible), typed("Array")),
|
||||
("controlBounds", get(l, item_control), typed("Array")),
|
||||
("editable", get(l, item_editable), typed("boolean")),
|
||||
("zOrderPosition", get(l, item_z_order_position), typed("number")),
|
||||
("duplicate", method(l, item_duplicate), returns("PageItem", &placement)),
|
||||
("move", method(l, item_move), {
|
||||
let mut info = returns("PageItem", &placement);
|
||||
if let Some(at) = info.arguments.get_mut(1) {
|
||||
at.default = Some(text("ElementPlacement.PLACEATBEGINNING"));
|
||||
}
|
||||
info
|
||||
}),
|
||||
("remove", method(l, item_remove), returns("undefined", &[])),
|
||||
("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, item_to_string), returns("string", &[])),
|
||||
]);
|
||||
page_item.extend(
|
||||
[
|
||||
@@ -2329,7 +2516,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
"sliced",
|
||||
"uRL",
|
||||
"uuid",
|
||||
"visibilityVariable",
|
||||
"wrapInside",
|
||||
"wrapOffset",
|
||||
"wrapped",
|
||||
@@ -2342,22 +2528,22 @@ 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,
|
||||
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
|
||||
named(vec![
|
||||
("typename", get(l, layer_typename), typed("string")),
|
||||
("name", get(l, layer_name), typed("string")),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.extend(tags::classes(l));
|
||||
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
realm.define_host_globals(vec![
|
||||
("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))),
|
||||
("documents".into(), function(l, app_documents), None),
|
||||
("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))),
|
||||
])
|
||||
classes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2397,4 +2583,107 @@ mod tests {
|
||||
assert_eq!(kept_items(&lists, 2, &docs[1]), None);
|
||||
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
|
||||
}
|
||||
|
||||
/// A script function that writes a reflection as one line, in the form [`expected_line`] gives.
|
||||
const LINE: &str = "function line(r) {\
|
||||
function args(a) { var s = []; for (var i = 0; i < a.length; i++) s.push([a[i].name, a[i].type, a[i].dataType, a[i].defaultValue].join('=')); return s.join(','); }\
|
||||
function list(a) { var s = []; for (var i = 0; i < a.length; i++) { var e = a[i];\
|
||||
s.push([e.name, e.type, e.dataType, e.isCollection, e.min, e.max, e.defaultValue, args(e.arguments)].join(':')); } return s.join(' '); }\
|
||||
return r.name + '|' + list(r.properties) + '|' + list(r.methods); }";
|
||||
|
||||
fn shown(d: Option<&Data>) -> String {
|
||||
match d {
|
||||
None | Some(Data::Undefined) => String::new(),
|
||||
Some(Data::String(s)) => s.clone(),
|
||||
Some(Data::Number(n)) => n.to_string(),
|
||||
Some(other) => panic!("no form for {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The line [`LINE`] should write for `class`: its parents' members, then its own, a member it
|
||||
/// declares again in its parent's place, without the members that are not available.
|
||||
fn expected_line(classes: &[HostClass], class: &HostClass) -> String {
|
||||
let mut chain = vec![class];
|
||||
while let Some(p) = chain.last().and_then(|c| c.parent.as_ref()) {
|
||||
chain.push(classes.iter().find(|c| &c.name == p).unwrap_or_else(|| panic!("no class {p}")));
|
||||
}
|
||||
let mut members: Vec<(String, &'static str, MemberInfo)> = Vec::new();
|
||||
for c in chain.iter().rev() {
|
||||
for (name, member) in &c.members {
|
||||
let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i.clone()).unwrap_or_default();
|
||||
let kind = match member {
|
||||
HostMember::Get(_) => "readonly",
|
||||
HostMember::Property { .. } | HostMember::Unavailable(_) => "readwrite",
|
||||
HostMember::Method(_) => "method",
|
||||
};
|
||||
match members.iter_mut().find(|(n, ..)| n == name) {
|
||||
Some(slot) => *slot = (name.clone(), kind, info),
|
||||
None => members.push((name.clone(), kind, info)),
|
||||
}
|
||||
}
|
||||
}
|
||||
members.retain(|(.., i)| !i.unavailable);
|
||||
let one = |(name, kind, i): &(String, &str, MemberInfo)| {
|
||||
let args: Vec<String> =
|
||||
i.arguments.iter().map(|a| format!("{}=parameter={}={}", a.name, a.data_type, shown(a.default.as_ref()))).collect();
|
||||
let number = |n: Option<f64>| n.map(|n| n.to_string()).unwrap_or_default();
|
||||
format!(
|
||||
"{name}:{kind}:{}:{}:{}:{}:{}:{}",
|
||||
i.data_type,
|
||||
i.collection,
|
||||
number(i.min),
|
||||
number(i.max),
|
||||
shown(i.default.as_ref()),
|
||||
args.join(",")
|
||||
)
|
||||
};
|
||||
let properties: Vec<String> = members.iter().filter(|m| m.1 != "method").map(one).collect();
|
||||
let methods: Vec<String> = members.iter().filter(|m| m.1 == "method").map(one).collect();
|
||||
format!("{}|{}|{}", class.name, properties.join(" "), methods.join(" "))
|
||||
}
|
||||
|
||||
fn logged(s: &mut Session, source: &str) -> Vec<String> {
|
||||
let r = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().unwrap_or_else(|| panic!("{r}")).iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_of_every_class_equals_its_declaration() {
|
||||
let link = Link::default();
|
||||
let classes = classes(&link);
|
||||
// Every member that is available declares its type, so `reflect` never answers `unknown`.
|
||||
for c in &classes {
|
||||
for (name, _) in &c.members {
|
||||
let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i);
|
||||
assert!(info.is_some_and(|i| i.unavailable || !i.data_type.is_empty()), "{}.{name} declares no type", c.name);
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let logs: Vec<String> = classes.iter().map(|c| format!("vc.log(line({}.reflect));", c.name)).collect();
|
||||
let script = format!("{LINE} {}", logs.join(" "));
|
||||
let got = logged(&mut s, &script);
|
||||
let want: Vec<String> = classes.iter().map(|c| expected_line(&classes, c)).collect();
|
||||
assert_eq!(got, want);
|
||||
assert!(want.iter().any(|w| w.contains("insertionLocation=parameter=ElementPlacement=ElementPlacement.PLACEATBEGINNING")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_of_an_object_equals_its_class_and_calls_no_member() {
|
||||
let link = Link::default();
|
||||
let classes = classes(&link);
|
||||
let want = |name: &str| expected_line(&classes, classes.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name}")));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap_or_else(|e| panic!("{e}"));
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let script = format!(
|
||||
"{LINE} var d = app.activeDocument, p = d.pageItems[0]; vc.log(line(app.reflect)); vc.log(line(app.documents.reflect));\
|
||||
vc.log(line(d.reflect)); vc.log(line(d.pageItems.reflect)); vc.log(line(p.reflect)); vc.log(line(new DocumentPreset().reflect));\
|
||||
p.remove(); vc.log(line(p.reflect)); vc.log(String(p.reflect.find('opacity').max));"
|
||||
);
|
||||
let got = logged(&mut s, &script);
|
||||
let path = want("PathItem");
|
||||
let expected =
|
||||
[want("Application"), want("Documents"), want("Document"), want("PageItems"), path.clone(), want("DocumentPreset"), path, "100".into()];
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,11 @@ use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
|
||||
|
||||
use super::{
|
||||
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::NodeId;
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, host_ref};
|
||||
|
||||
/// The error for a tag that was deleted, or that came from an earlier run.
|
||||
pub const STALE_TAG: &str = "Stale tag";
|
||||
@@ -286,21 +286,21 @@ fn tag_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// The `Tags` and `Tag` classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let tags: Vec<(String, HostMember)> = named(vec![
|
||||
("typename", get(l, tags_typename)),
|
||||
("length", get(l, tags_length)),
|
||||
("parent", get(l, tags_parent)),
|
||||
("index", method(l, tags_index)),
|
||||
("getByName", method(l, tags_by_name)),
|
||||
("add", method(l, tags_add)),
|
||||
("removeAll", method(l, tags_remove_all)),
|
||||
let tags = named(vec![
|
||||
("typename", get(l, tags_typename), typed("string")),
|
||||
("length", get(l, tags_length), typed("number")),
|
||||
("parent", get(l, tags_parent), typed("*")),
|
||||
("index", method(l, tags_index), returns("Tag", &[("itemKey", "*")])),
|
||||
("getByName", method(l, tags_by_name), returns("Tag", &[("name", "string")])),
|
||||
("add", method(l, tags_add), returns("Tag", &[])),
|
||||
("removeAll", method(l, tags_remove_all), returns("undefined", &[])),
|
||||
]);
|
||||
let tag = named(vec![
|
||||
("typename", get(l, tag_typename)),
|
||||
("name", property(l, tag_name, tag_set_name)),
|
||||
("value", property(l, tag_value, tag_set_value)),
|
||||
("parent", get(l, tag_parent)),
|
||||
("remove", method(l, tag_remove)),
|
||||
("typename", get(l, tag_typename), typed("string")),
|
||||
("name", property(l, tag_name, tag_set_name), typed("string")),
|
||||
("value", property(l, tag_value, tag_set_value), typed("string")),
|
||||
("parent", get(l, tag_parent), typed("PageItem")),
|
||||
("remove", method(l, tag_remove), returns("undefined", &[])),
|
||||
]);
|
||||
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
//! 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 <https://ai-scripting.docsforadobe.dev/jsobjref/Variables/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Variable/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/> 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, MemberInfo, Realm, RunError, file_ref_path, host_ref};
|
||||
|
||||
use super::{
|
||||
Answer, Described, 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, returns, text, typed, 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<VariableKind>,
|
||||
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<Entry>,
|
||||
/// 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<VariableKind>, what: &str) -> std::result::Result<usize, HostError> {
|
||||
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<VariableKind>) {
|
||||
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<usize> = 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<Table>,
|
||||
sets: RefCell<Table>,
|
||||
seen: RefCell<Vec<(u64, u64)>>,
|
||||
}
|
||||
|
||||
/// 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<DataSet>)> {
|
||||
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<DataSet>)>) {
|
||||
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<u64> = {
|
||||
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<u64, HashMap<&str, VariableKind>> = HashMap::new();
|
||||
let mut sets: HashMap<u64, HashSet<&str>> = 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<VariableKind, HostError> {
|
||||
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<String> {
|
||||
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<VariableKind>,
|
||||
}
|
||||
|
||||
/// 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<Named, HostError> {
|
||||
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, HostError> {
|
||||
named_of(h, arg(a, 0), true)
|
||||
}
|
||||
|
||||
fn this_set(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
|
||||
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<usize> {
|
||||
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, HostError> {
|
||||
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<String, HostError> {
|
||||
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, HostError> {
|
||||
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<String> = 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<crate::NodeId> =
|
||||
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, HostError> {
|
||||
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<String> = 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<VariableKind, HostError> {
|
||||
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::<Vec<_>>())
|
||||
})?;
|
||||
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<Described> {
|
||||
named(vec![
|
||||
("variables", get(l, doc_variables), MemberInfo { collection: true, ..typed("Variables") }),
|
||||
("dataSets", get(l, doc_datasets), MemberInfo { collection: true, ..typed("Datasets") }),
|
||||
("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset), typed("Dataset")),
|
||||
("variablesLocked", property(l, doc_locked, doc_set_locked), typed("boolean")),
|
||||
("importVariables", method(l, doc_import), returns("undefined", &[("fileSpec", "File")])),
|
||||
("exportVariables", method(l, doc_export), returns("undefined", &[("fileSpec", "File")])),
|
||||
])
|
||||
}
|
||||
|
||||
/// The members this module adds to `PageItem`.
|
||||
pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility), typed("Variable"))])
|
||||
}
|
||||
|
||||
/// The members this module adds to the page item class `class`.
|
||||
pub(super) fn item_members(l: &Link, class: &str) -> Vec<Described> {
|
||||
match class {
|
||||
"TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => {
|
||||
named(vec![("contentVariable", property(l, item_content, item_set_content), typed("Variable"))])
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The classes this module adds.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
vec![
|
||||
class(
|
||||
"Variables",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, vars_typename), typed("string")),
|
||||
("length", get(l, vars_length), typed("number")),
|
||||
("parent", get(l, vars_parent), typed("Document")),
|
||||
("index", method(l, vars_index), returns("Variable", &[("itemKey", "*")])),
|
||||
("getByName", method(l, vars_by_name), returns("Variable", &[("name", "string")])),
|
||||
("add", method(l, vars_add), returns("Variable", &[])),
|
||||
("removeAll", method(l, vars_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, vars_at)),
|
||||
),
|
||||
class(
|
||||
"Variable",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, var_typename), typed("string")),
|
||||
("parent", get(l, var_parent), typed("Document")),
|
||||
("name", property(l, var_name, var_set_name), typed("string")),
|
||||
("kind", property(l, var_kind, var_set_kind), typed("VariableKind")),
|
||||
("pageItems", get(l, var_page_items), typed("Array")),
|
||||
("remove", method(l, var_remove), returns("undefined", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
class(
|
||||
"Datasets",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, sets_typename), typed("string")),
|
||||
("length", get(l, sets_length), typed("number")),
|
||||
("parent", get(l, sets_parent), typed("Document")),
|
||||
("index", method(l, sets_index), returns("Dataset", &[("itemKey", "*")])),
|
||||
("getByName", method(l, sets_by_name), returns("Dataset", &[("name", "string")])),
|
||||
("add", method(l, sets_add), returns("Dataset", &[])),
|
||||
("removeAll", method(l, sets_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, sets_at)),
|
||||
),
|
||||
class(
|
||||
"Dataset",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, set_typename), typed("string")),
|
||||
("parent", get(l, set_parent), typed("Document")),
|
||||
("name", property(l, set_name, set_set_name), typed("string")),
|
||||
("display", method(l, set_display), returns("undefined", &[])),
|
||||
("update", method(l, set_update), returns("undefined", &[])),
|
||||
("remove", method(l, set_remove), returns("undefined", &[])),
|
||||
]),
|
||||
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)
|
||||
}
|
||||
@@ -1107,6 +1107,20 @@ impl Host {
|
||||
self.pause.set(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about
|
||||
/// it, for [`Host::put_growth_back`].
|
||||
fn growth_mark(&self) -> (u64, u64, bool) {
|
||||
(self.objects.get(), self.bytes_kept.get(), self.waiting.get())
|
||||
}
|
||||
|
||||
/// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added
|
||||
/// it were put back.
|
||||
fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) {
|
||||
self.objects.set(objects);
|
||||
self.bytes_kept.set(bytes);
|
||||
self.waiting.set(waiting);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run in progress.
|
||||
@@ -1350,16 +1364,15 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
let id = id.to_string();
|
||||
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)
|
||||
step(&mut s, host, id, params)
|
||||
};
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
let mut times = host.commands.borrow_mut();
|
||||
let row = times.entry(spec.id).or_insert((0, 0, 0));
|
||||
@@ -1372,13 +1385,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())),
|
||||
Err(e) => return Err(HostError::Error(e.to_string())),
|
||||
};
|
||||
let mark = host.growth_mark();
|
||||
let crossed = host.charge_growth(objects, added).and_then(|()| {
|
||||
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
|
||||
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
|
||||
host.charge_call(data_size(&data))?;
|
||||
Ok(data)
|
||||
});
|
||||
// A command whose result does not reach the script is put back, like one that failed.
|
||||
// A command whose result does not reach the script is put back, like one that failed, and so is
|
||||
// the growth it was charged.
|
||||
if crossed.is_err() {
|
||||
host.put_growth_back(mark);
|
||||
}
|
||||
if let Some(save) = save {
|
||||
let mut s = session.borrow_mut();
|
||||
if crossed.is_ok() {
|
||||
@@ -1387,6 +1405,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))
|
||||
}
|
||||
|
||||
@@ -2134,7 +2153,7 @@ impl Session {
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::default(),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
|
||||
@@ -120,6 +120,8 @@ impl Session {
|
||||
proof_setup_saves: 0,
|
||||
script_data_dir: None,
|
||||
plugin_output: None,
|
||||
plugin_checked: Vec::new(),
|
||||
plugin_calling: None,
|
||||
plugin_install_approval: None,
|
||||
plugin_grants_from_requests: false,
|
||||
recent_urls: vec![],
|
||||
|
||||
@@ -15,6 +15,9 @@ impl Session {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
if self.plugin_calls_open() {
|
||||
return Err(EngineError::PluginBusy);
|
||||
}
|
||||
// An edit made while typing (the Transform panel) is a step of its own: inside the typing
|
||||
// session, the next keystroke's preview would start again from before it (#1881).
|
||||
if !self.previewing && cmd::typing_in_progress(self) {
|
||||
@@ -516,6 +519,9 @@ impl Session {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
if self.plugin_calls_open() {
|
||||
return Err(EngineError::PluginBusy);
|
||||
}
|
||||
// Typing in progress is kept first: a drag or a dialog's preview would otherwise start
|
||||
// from the snapshot taken before the typing, and drop it (#1881).
|
||||
if label != "Typing" && cmd::typing_in_progress(self) {
|
||||
|
||||
@@ -95,6 +95,14 @@ impl Session {
|
||||
if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
// A command-calling plug-in run blocks external document, selection and preference changes.
|
||||
// Its completion command can still apply the output.
|
||||
let find_selects = id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true);
|
||||
let changes = (waits_for_tool_edit(id) && !JOURNALED_READS.contains(&id) && (id != "document.find" || find_selects))
|
||||
|| id.starts_with("clipboard.import");
|
||||
if self.depth == 0 && self.plugin_calls_open() && !self.plugin_calls_end_with(id) && changes {
|
||||
return Err(EngineError::PluginBusy);
|
||||
}
|
||||
// A step of a batch a script runs is held to the same rule as the script's own commands.
|
||||
if self.script_in_run && crate::script::refused_to_scripts(id) {
|
||||
return Err(EngineError::Other(crate::script::refused_text(id)));
|
||||
@@ -109,7 +117,6 @@ impl Session {
|
||||
// A command from outside the tool, while the tool's drag is in progress, is a step of its
|
||||
// own before the drag's ([`Session::outside_interaction`]). Find Objects with `select` is
|
||||
// journaled (`Session::journal_query`), so it is one too.
|
||||
let find_selects = id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true);
|
||||
let outside = (spec.journal || find_selects) && !self.previewing && !self.in_tool_actions;
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
|
||||
@@ -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"))]
|
||||
|
||||
@@ -1115,6 +1115,82 @@ fn package_reads_no_placed_pdf_page_without_copy_fonts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Copy Fonts on, Package reads the type of a placed EPS file whose bytes a `.ai` file's
|
||||
/// editing data included, as it reads a placed PDF page's.
|
||||
#[test]
|
||||
fn package_reads_a_placed_eps_files_type_for_copy_fonts() {
|
||||
use cmd::package::PAGES_READ;
|
||||
use vectorcraft_testkit::ai;
|
||||
let dir = Folder::new("package-placed-eps-fonts");
|
||||
let eps =
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n";
|
||||
let src = dir.file("art/shape.eps");
|
||||
write(&src, eps.as_bytes());
|
||||
let src = src.replace('\\', "/");
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n({src})`\n%%BeginDocument: {src}\n{eps}\n%%EndDocument\n~\n%AI5_EndPlace\n"
|
||||
);
|
||||
let doc_path = dir.file("poster.ai");
|
||||
let page = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET";
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)).as_bytes(), page));
|
||||
let mut s = session();
|
||||
open(&mut s, &doc_path);
|
||||
let mut placed = 0;
|
||||
s.doc().unwrap().doc.visit_placed(|_, _| placed += 1);
|
||||
assert_eq!(placed, 1);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let before = PAGES_READ.with(std::cell::Cell::get);
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(PAGES_READ.with(std::cell::Cell::get) - before, 1, "{r}");
|
||||
let listed = |r: &Value| r["fonts"].as_u64().unwrap_or(0) + r["skippedFonts"].as_array().map_or(0, |a| a.len() as u64);
|
||||
assert_eq!(listed(&r), 1, "the type's font: {r}");
|
||||
|
||||
// Type only in an EPS file that the placed one, a legacy-format file, includes in turn.
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let typed =
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Courier findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n";
|
||||
let inner = format!("[1 0 0 1 0 0] 0 0 60 60 (inner.eps) `\n%%BeginDocument: inner.eps\n{typed}%%EndDocument\n~\n");
|
||||
let outer = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n\
|
||||
%%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\
|
||||
{inner}LB\n%AI5_EndLayer--\nshowpage\n%%EOF\n"
|
||||
);
|
||||
write(&dir.file("art/shape.eps"), outer.as_bytes());
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page));
|
||||
open(&mut s, &doc_path);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out2"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(listed(&r), 1, "the inner file's font: {r}");
|
||||
|
||||
// The included file is only in a pattern definition, outside the page's nodes.
|
||||
let pattern = format!("%AI3_BeginPattern: (Type)\n(Type) 0 0 60 60\n0 A\n0 Xw\n{inner}E\n%AI3_EndPattern\n");
|
||||
let outer = outer.replace(&inner, "").replace("%AI5_BeginLayer", &format!("{pattern}%AI5_BeginLayer"));
|
||||
let a = cmd::place::document::document_art("shape.eps", outer.as_bytes(), Some(&src), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap();
|
||||
let pattern = a.doc.pattern("Type").expect("the pattern definition is read");
|
||||
let mut placements = 0;
|
||||
for n in &pattern.art {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| {
|
||||
assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)), "the type is only in the included file");
|
||||
if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind {
|
||||
placements += 1;
|
||||
let blob = &a.doc.images[&p.key];
|
||||
assert!(!blob.is_proxy());
|
||||
assert_eq!(blob.bytes.as_slice(), typed.as_bytes());
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(placements, 1, "the pattern holds the included file");
|
||||
for n in &a.nodes {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_))));
|
||||
}
|
||||
write(&dir.file("art/shape.eps"), outer.as_bytes());
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page));
|
||||
open(&mut s, &doc_path);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out3"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(listed(&r), 1, "the pattern's included file's font: {r}");
|
||||
}
|
||||
|
||||
/// `dir/art/badge.ai`, saved without its PDF part, its art placing each of `pics` (600 × 300 px,
|
||||
/// with a 2×1 preview) → its path.
|
||||
fn ai_placing(dir: &Folder, pics: &[&str]) -> String {
|
||||
|
||||
@@ -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<Node>]| 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
|
||||
|
||||
@@ -934,6 +934,127 @@ fn an_ai_file_that_places_itself_opens() {
|
||||
assert_eq!(found, [at], "{r}");
|
||||
}
|
||||
|
||||
/// A placed EPS file whose bytes a `.ai` file's editing data includes (between `%%BeginDocument:`
|
||||
/// and `%%EndDocument`) opens as a placed document of those bytes: it draws its art with its file
|
||||
/// missing, and its file found unchanged is neither missing nor modified. A native save keeps the
|
||||
/// bytes, so the copy reopens and draws without the file.
|
||||
#[test]
|
||||
fn a_placed_eps_file_included_in_an_ai_files_editing_data_draws_without_its_file() {
|
||||
use vectorcraft_testkit::ai;
|
||||
let dir = Folder::new("placed-eps-in-ai");
|
||||
// The file draws red and the page blue, so each check shows which one drew.
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor\n0 0 60 60 rectfill\n%%EOF\n";
|
||||
let (red, blue) = ([255, 0, 0], [0, 0, 255]);
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n(/no/such/folder/src/shape.eps)`\n\
|
||||
%%BeginDocument: /no/such/folder/src/shape.eps\n{eps}\n%%EndDocument\n%AI17_Begin_Content_if_version_gt:24 12\n\
|
||||
%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"
|
||||
);
|
||||
let doc_path = dir.file("poster.ai");
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &place));
|
||||
write(&doc_path, &ai::ai(data.as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
let shown = |s: &Session| {
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true);
|
||||
let [r, g, b, _] = img.pixel(50, 50);
|
||||
[r, g, b]
|
||||
};
|
||||
let one = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut found = vec![];
|
||||
d.visit_placed(|n, p| found.push((n.id, p.clone())));
|
||||
let [(id, p)] = &found[..] else { panic!("one placed document: {found:?}") };
|
||||
(*id, p.clone(), d.images[&p.key].clone())
|
||||
};
|
||||
let mut s = session();
|
||||
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("shape.eps"), "{r}");
|
||||
let (id, p, blob) = one(&s);
|
||||
assert_eq!((blob.bytes.as_slice(), blob.mime.as_str()), (eps.as_bytes(), "application/postscript"));
|
||||
assert_eq!(p.link.relative.as_deref(), Some("src/shape.eps"));
|
||||
let at = bounds(&s, id);
|
||||
assert!((at.x0 - 20.0).abs() < 0.01 && (at.y0 - 20.0).abs() < 0.01 && (at.width() - 60.0).abs() < 0.01, "{at:?}");
|
||||
assert!(near(shown(&s), red), "its art draws: {:?}", shown(&s));
|
||||
|
||||
write(&dir.file("src/shape.eps"), eps.as_bytes());
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
|
||||
assert!(near(shown(&s), red));
|
||||
|
||||
let copy = dir.file("copy.vectorcraft");
|
||||
save(&mut s, ©);
|
||||
std::fs::remove_file(dir.file("src/shape.eps")).unwrap();
|
||||
open(&mut s, ©);
|
||||
let (_, _, blob) = one(&s);
|
||||
assert_eq!(blob.bytes.as_slice(), eps.as_bytes(), "the bytes are saved");
|
||||
assert!(near(shown(&s), red), "and draw: {:?}", shown(&s));
|
||||
|
||||
// A file named as PostScript of another kind, or with a name that doesn't say, draws the same.
|
||||
for name in ["shape.ps", "shape", "shape.dat"] {
|
||||
let named = place.replace("shape.eps", name);
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &named)).as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
open(&mut s, &doc_path);
|
||||
let (_, p, blob) = one(&s);
|
||||
assert_eq!((p.link.name(), blob.mime.as_str()), (name, "application/postscript"));
|
||||
assert!(near(shown(&s), red), "{name} draws: {:?}", shown(&s));
|
||||
}
|
||||
|
||||
// Bytes that can't be read leave the placed file unread: the file is read from its PDF part,
|
||||
// and the object comes in as what the page draws there.
|
||||
let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, broken))).as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert!(near(shown(&s), blue), "the page's art: {:?} {r}", shown(&s));
|
||||
}
|
||||
|
||||
/// A synthetic EPS file that includes another placed EPS file, `depth` levels deep.
|
||||
fn nested_included_eps(depth: usize) -> String {
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let mut eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n10 20 40 30 rectfill\n%%EOF\n".to_string();
|
||||
for _ in 0..depth {
|
||||
eps = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\
|
||||
%%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\
|
||||
[1 0 0 1 0 0] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\nLB\n%AI5_EndLayer--\nshowpage\n%%EOF\n"
|
||||
);
|
||||
}
|
||||
eps
|
||||
}
|
||||
|
||||
/// Open checks and drawing must not recursively multiply each other's work.
|
||||
#[test]
|
||||
fn placed_eps_files_included_open_work_is_bounded() {
|
||||
let dir = Folder::new("placed-eps-open-work");
|
||||
let path = dir.file("deep.eps");
|
||||
write(&path, nested_included_eps(12).as_bytes());
|
||||
let mut s = session();
|
||||
let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get);
|
||||
let checks = vectorcraft_eps::included_eps_reads();
|
||||
open(&mut s, &path);
|
||||
let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get) - drawings;
|
||||
let checks = vectorcraft_eps::included_eps_reads() - checks;
|
||||
eprintln!("included EPS work: {drawings} drawing reads, {checks} open checks");
|
||||
// At most 8 drawing loads, each with at most 8 parses for checks, plus the outer import's 8.
|
||||
// Repeated structural reads share completed checks within each chain.
|
||||
assert!(drawings <= 8, "{drawings} drawing reads, {checks} open checks");
|
||||
assert!(checks <= 8 * 8 + 8, "{drawings} drawing reads, {checks} open checks");
|
||||
assert!(drawings > 0 && checks > 0, "both read paths were exercised");
|
||||
}
|
||||
|
||||
/// A legacy-format file (version 7 specification §16) placing an EPS file whose bytes it includes,
|
||||
/// which is such a file in turn, 300 deep: it opens, reading a bounded number of them.
|
||||
#[test]
|
||||
fn placed_eps_files_included_300_deep_open() {
|
||||
let dir = Folder::new("placed-eps-300-deep");
|
||||
let path = dir.file("deep.eps");
|
||||
write(&path, nested_included_eps(300).as_bytes());
|
||||
let mut s = session();
|
||||
open(&mut s, &path);
|
||||
let mut placed = 0;
|
||||
s.doc().unwrap().doc.visit_placed(|_, _| placed += 1);
|
||||
assert_eq!(placed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() {
|
||||
let dir = Folder::new("placed-ai-linked");
|
||||
|
||||
@@ -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
|
||||
@@ -7978,3 +8032,280 @@ fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() {
|
||||
assert_moved_once(&s, r);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Installs a filter `id` that calls `select.all` and then returns no objects, so it removes the
|
||||
/// objects it was given.
|
||||
fn install_select_all_then_remove(s: &mut Session, id: &str) {
|
||||
let grant = json!(["doc.read", "doc.write", "commands"]);
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"]}}"#);
|
||||
let imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))
|
||||
(data (i32.const 0x2000) "select.all")
|
||||
(data (i32.const 0x2100) "{}")"#;
|
||||
let first = "(drop (call $vc_call (i32.const 0x2000) (i32.const 10) (i32.const 0x2100) (i32.const 2)))";
|
||||
let wasm = wat::parse_str(tpl::with_imports(&manifest, imports, first, r#"{"objects":[]}"#)).unwrap();
|
||||
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
|
||||
}
|
||||
|
||||
/// Runs the job of a run that [`FilterRun::begin_calls`] started as the web build's plug-in worker
|
||||
/// does, making each command call in `s` → its output.
|
||||
fn run_job_away(s: &mut Session, job: &cmd::plugin::FilterJob) -> Vec<u8> {
|
||||
let (mut held, mut step) = job.plugin.begin_run(&job.input, &job.params, &job.limits, true);
|
||||
loop {
|
||||
match step {
|
||||
vectorcraft_plugins::Step::Done(out, _) => return out.unwrap(),
|
||||
vectorcraft_plugins::Step::Call { command, args } => {
|
||||
let answer = s.plugin_call(&command, &args);
|
||||
step = job.plugin.resume_run(&mut held, answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of a filter that calls commands, made away from the session, holds the documents while
|
||||
/// it waits: edits are refused, its calls run on the document, and `plugin.run` with its output
|
||||
/// applies the calls and the output as one undo step, as a run on the page does.
|
||||
#[test]
|
||||
fn a_calling_run_made_away_from_the_session_is_one_undo_step() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.callsaway";
|
||||
let mut s = session();
|
||||
install_select_all_then_remove(&mut s, id);
|
||||
let (a, b) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap();
|
||||
assert!(s.plugin_calls_open());
|
||||
assert!(matches!(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})), Err(EngineError::PluginBusy)));
|
||||
assert!(matches!(s.edit("x", |_, _| Ok(())), Err(EngineError::PluginBusy)));
|
||||
assert!(matches!(FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})), Err(EngineError::PluginBusy)));
|
||||
assert!(s.execute("document.inspect", &json!({})).is_ok(), "queries still run");
|
||||
let output = run_job_away(&mut s, &job);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&b), "the call selected everything");
|
||||
s.hand_in_plugin_calls(output);
|
||||
run(&mut s, "plugin.run", json!({"id": id}));
|
||||
assert!(!s.plugin_calls_open());
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_some(), "only the given object went");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(s.doc().unwrap().doc.node(a).is_some());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "undo brings back the selection the run started from");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A run made away from the session that ends without an output changes nothing: what its calls
|
||||
/// did is undone and the documents are free again. `plugin.run` without its output is refused
|
||||
/// while it holds them.
|
||||
#[test]
|
||||
fn a_calling_run_made_away_from_the_session_that_ends_changes_nothing() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.callsawayend";
|
||||
let mut s = session();
|
||||
install_select_all_then_remove(&mut s, id);
|
||||
let (a, _) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap();
|
||||
run_job_away(&mut s, &job);
|
||||
assert!(matches!(s.execute("plugin.run", &json!({"id": id})), Err(EngineError::PluginBusy)), "no output was handed in");
|
||||
s.end_plugin_calls();
|
||||
assert!(!s.plugin_calls_open());
|
||||
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
|
||||
assert!(s.plugin_call("select.all", &json!({})).is_err(), "no run waits for a call");
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5}));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// An output handed in for a run that holds the documents is dropped when that run ends: a later
|
||||
/// run with the same input and params is not given it, and `plugin.run` without its own output is
|
||||
/// refused.
|
||||
#[test]
|
||||
fn an_ended_calling_run_drops_the_output_handed_in_for_it() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.callsawaystale";
|
||||
let mut s = session();
|
||||
install_select_all_then_remove(&mut s, id);
|
||||
let (a, b) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap();
|
||||
let output = run_job_away(&mut s, &job);
|
||||
s.hand_in_plugin_calls(output);
|
||||
s.end_plugin_calls();
|
||||
FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap();
|
||||
assert!(matches!(s.execute("plugin.run", &json!({"id": id})), Err(EngineError::PluginBusy)), "the ended run's output was not kept");
|
||||
assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some(), "nothing applied");
|
||||
s.end_plugin_calls();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A plug-in command's run made away from the session applies through the command itself: an
|
||||
/// output handed in for it, and the calls of one that holds the documents, are one undo step named
|
||||
/// after the command.
|
||||
#[test]
|
||||
fn a_plugin_command_run_made_away_from_the_session_applies_through_the_command() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.awaycommand";
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
// It renames the object, so its run changes the document: a run that changes nothing records no step.
|
||||
let grant = json!(["doc.read", "doc.write", "commands"]);
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"],"commands":[{{"id":"same","label":"Same"}}]}}"#
|
||||
);
|
||||
let renamed = json!({"objects": [{"id": a.0, "name": "Renamed"}]});
|
||||
let wasm = wat::parse_str(tpl::returning(&manifest, &renamed.to_string())).unwrap();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
|
||||
let cmd = format!("plugin.{id}.same");
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let job = FilterRun::begin_calls(&mut s, &cmd, &json!({})).unwrap();
|
||||
assert!(matches!(s.execute("plugin.run", &json!({"id": id})), Err(EngineError::PluginBusy)), "only the command applies it");
|
||||
let output = run_job_away(&mut s, &job);
|
||||
s.hand_in_plugin_calls(output);
|
||||
run(&mut s, &cmd, json!({}));
|
||||
assert!(!s.plugin_calls_open());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Same");
|
||||
assert_eq!(node(&s, a).name.as_deref(), Some("Renamed"));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// The output of a plug-in command's held run does not apply once another session has installed
|
||||
/// another module with the plug-in's id: the command is refused, and the run still holds the
|
||||
/// documents until it ends, changing nothing.
|
||||
#[test]
|
||||
fn a_held_plugin_command_run_does_not_apply_after_its_plugin_is_replaced() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.heldreplaced";
|
||||
let mut s = session();
|
||||
install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#);
|
||||
let cmd = format!("plugin.{id}.same");
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let job = FilterRun::begin_calls(&mut s, &cmd, &json!({})).unwrap();
|
||||
let output = run_job_away(&mut s, &job);
|
||||
install_echo_calling(&mut session(), id, r#"[{"id":"same","label":"Same"}]"#);
|
||||
s.hand_in_plugin_calls(output);
|
||||
assert!(s.execute(&cmd, &json!({})).is_err(), "the plug-in was replaced");
|
||||
assert!(s.plugin_calls_open());
|
||||
s.end_plugin_calls();
|
||||
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A module that a load in another place checked installs from its bytes and the manifest that
|
||||
/// load read, without running any of its code: a start function that would spend its whole budget
|
||||
/// doesn't run.
|
||||
#[test]
|
||||
fn a_checked_module_installs_without_running_its_code() {
|
||||
let id = "test.engine.checked";
|
||||
let mut s = session();
|
||||
let manifest = tpl::manifest(id, "filter", "{}");
|
||||
let spins = "(start $spin) (func $spin (loop $l (br $l)))";
|
||||
let wasm = wat::parse_str(tpl::module(&manifest, tpl::ECHO, spins, 1)).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&wasm);
|
||||
assert!(s.execute("plugin.inspect", &json!({"dataBase64": data})).is_err(), "loading here runs the start function");
|
||||
s.hand_in_checked_plugin(&vectorcraft_plugins::permissions::sha256_hex(&wasm), manifest.clone().into_bytes());
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": data}))["id"], json!(id));
|
||||
assert_eq!(run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true}))["id"], json!(id));
|
||||
// Other bytes are loaded here, as before.
|
||||
let other = wat::parse_str(tpl::module(&manifest, tpl::ECHO, "(start $spin) (func $spin (loop $l (br $l))) (func $x)", 1)).unwrap();
|
||||
assert!(s.execute("plugin.inspect", &json!({"dataBase64": vectorcraft_format::base64_encode(&other)})).is_err());
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A run that holds the documents and ends before it changed anything leaves the document's
|
||||
/// revision as it was, so another run made away from the session on that document still applies;
|
||||
/// one whose calls changed the selection moves it on, so the restored document redraws.
|
||||
#[test]
|
||||
fn a_calling_run_that_ends_unchanged_keeps_the_revision() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let (plain, caller) = ("test.engine.keeprev.plain", "test.engine.keeprev.caller");
|
||||
let mut s = session();
|
||||
install_wat(&mut s, &tpl::returning(&tpl::manifest(plain, "filter", "{}"), r#"{"objects":[]}"#));
|
||||
install_select_all_then_remove(&mut s, caller);
|
||||
let (a, _) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let first = FilterRun::prepare(&s, &json!({"id": plain})).unwrap();
|
||||
// It fails before its first call.
|
||||
FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": caller})).unwrap();
|
||||
s.end_plugin_calls();
|
||||
assert!(first.current(&s), "nothing changed: the other run still applies");
|
||||
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": caller})).unwrap();
|
||||
run_job_away(&mut s, &job);
|
||||
s.end_plugin_calls();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
|
||||
assert!(!first.current(&s), "its call changed the selection, which was put back");
|
||||
run(&mut s, "plugin.remove", json!({"id": plain}));
|
||||
run(&mut s, "plugin.remove", json!({"id": caller}));
|
||||
}
|
||||
|
||||
/// The output of a run that holds the documents applies only through the command and the params
|
||||
/// it was started with: `plugin.run` for other objects is refused and leaves the run holding them.
|
||||
#[test]
|
||||
fn a_held_run_applies_only_with_the_params_it_was_started_with() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.heldparams";
|
||||
let mut s = session();
|
||||
install_select_all_then_remove(&mut s, id);
|
||||
let (a, b) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
|
||||
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id, "ids": [a.0]})).unwrap();
|
||||
let output = run_job_away(&mut s, &job);
|
||||
s.hand_in_plugin_calls(output.clone());
|
||||
assert!(matches!(s.execute("plugin.run", &json!({"id": id, "ids": [b.0]})), Err(EngineError::PluginBusy)));
|
||||
assert!(s.plugin_calls_open());
|
||||
assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some(), "nothing applied");
|
||||
s.hand_in_plugin_calls(output);
|
||||
run(&mut s, "plugin.run", json!({"id": id, "ids": [a.0]}));
|
||||
assert!(!s.plugin_calls_open());
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_some());
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A clipboard import is refused while a run holds the documents: the run's end would put back the
|
||||
/// clipboard it started with.
|
||||
#[test]
|
||||
fn a_clipboard_import_is_refused_while_a_run_holds_the_documents() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.heldclipboard";
|
||||
let mut s = session();
|
||||
install_select_all_then_remove(&mut s, id);
|
||||
rect(&mut s, 10.0, "#ff0000");
|
||||
FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap();
|
||||
assert!(matches!(s.execute("clipboard.importText", &json!({"text": "Hello"})), Err(EngineError::PluginBusy)));
|
||||
s.end_plugin_calls();
|
||||
run(&mut s, "clipboard.importText", json!({"text": "Hello"}));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutating_queries_are_refused_while_a_run_holds_the_documents() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let id = "test.engine.heldqueries";
|
||||
let mut s = session();
|
||||
install_select_all_then_remove(&mut s, id);
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
rect(&mut s, 40.0, "#00ff00");
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let prefs = s.prefs.to_json();
|
||||
FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap();
|
||||
for (command, params) in [
|
||||
("document.find", json!({"intersects": [0, 0, 400, 400], "select": true})),
|
||||
("prefs.set", json!({"key": "marqueeSelection", "value": "enclosed"})),
|
||||
] {
|
||||
assert!(matches!(s.execute(command, ¶ms), Err(EngineError::PluginBusy)), "{command}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.prefs.to_json(), prefs);
|
||||
}
|
||||
assert!(s.execute("prefs.get", &json!({})).is_ok());
|
||||
assert!(s.execute("document.find", &json!({"intersects": [0, 0, 400, 400]})).is_ok());
|
||||
s.end_plugin_calls();
|
||||
run(&mut s, "document.find", json!({"intersects": [0, 0, 400, 400], "select": true}));
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2);
|
||||
run(&mut s, "prefs.set", json!({"key": "marqueeSelection", "value": "enclosed"}));
|
||||
assert_eq!(s.prefs.marquee_selection, "enclosed");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
@@ -301,6 +301,41 @@ fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
assert!(e.contains("Cannot select"), "{e}");
|
||||
}
|
||||
|
||||
/// An index past the end of `pageItems` gives `undefined`, which does not clear the selection;
|
||||
/// `null` and `[]` do.
|
||||
#[test]
|
||||
fn assigning_an_index_past_the_end_to_the_selection_throws_and_keeps_it() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let caught = "var d = app.activeDocument, m = '';\
|
||||
try { d.selection = d.pageItems[99]; } catch (e) { m = e.name; }\
|
||||
vc.log(m); vc.log(d.selection.length);";
|
||||
assert_eq!(log(&mut s, caught), vec![json!("TypeError"), json!(1)]);
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
|
||||
for clear in ["null", "[]"] {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
log(&mut s, &format!("app.activeDocument.selection = {clear};"));
|
||||
assert!(s.active().unwrap().selection.objects.is_empty(), "{clear}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `controlBounds` takes in a direction point that lies past the curve; `visibleBounds` does not.
|
||||
#[test]
|
||||
fn control_bounds_take_in_direction_points_past_the_curve() {
|
||||
let (mut s, _, _) = doc();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.pageItems;\
|
||||
vc.log(p[0].controlBounds); vc.log(p[0].visibleBounds); vc.log(p[2].controlBounds); vc.log(p[2].visibleBounds);",
|
||||
);
|
||||
let top = |v: &Value| v[1].as_f64().unwrap();
|
||||
assert!((top(&out[0]) + 100.0).abs() < 1e-9, "{out:?}");
|
||||
assert!(top(&out[1]) > -90.0, "{out:?}");
|
||||
// A rectangle's direction points lie on its edges.
|
||||
assert_eq!(out[2], out[3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guide_path_is_not_selected_while_guides_are_locked() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -490,6 +525,17 @@ fn a_copy_that_cannot_be_placed_is_deleted() {
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
// The refused copy leaves no undo step and does not change the document's step.
|
||||
assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step));
|
||||
// Nor does it count toward the run's growth allowance: many refused copies stay within one
|
||||
// that a few kept copies would pass.
|
||||
crate::script::TEST_GROWTH.with(|g| g.set(Some(5)));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], refused = 0;\
|
||||
for (var k = 0; k < 20; k++) { try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { refused++; } }\
|
||||
vc.log(refused);",
|
||||
);
|
||||
crate::script::TEST_GROWTH.with(|g| g.set(None));
|
||||
assert_eq!(r.unwrap()["log"], json!([20]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -559,14 +605,14 @@ fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
|
||||
m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\
|
||||
vc.log([c.typename, c === d.pageItems[2]]);\
|
||||
var bad = []; for (var k in c) { try { c[k]; } catch (e) { bad.push(k + ': ' + e.message); } } vc.log(bad);\
|
||||
vc.log([c.geometricBounds, c.visibleBounds, c.position, c.width, c.height]);\
|
||||
vc.log([c.geometricBounds, c.visibleBounds, c.controlBounds, c.position, c.width, c.height]);\
|
||||
c.left = 5; c.top = 5; c.position = [1, 2]; c.width = 10; c.height = 10; vc.log(c.geometricBounds);",
|
||||
);
|
||||
let zeros = json!([0, 0, 0, 0]);
|
||||
assert_eq!(out[..3], [json!(3), json!(3), json!(["CompoundPathItem", true])]);
|
||||
// Every property `for`-`in` lists reads, and the emptied compound path has zero bounds that
|
||||
// moving or resizing leaves as they are.
|
||||
assert_eq!(out[3..], [json!([]), json!([zeros, zeros, [0, 0], 0, 0]), zeros]);
|
||||
assert_eq!(out[3..], [json!([]), json!([zeros, zeros, zeros, [0, 0], 0, 0]), zeros]);
|
||||
let doc = &s.active().unwrap().doc;
|
||||
assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty");
|
||||
// Each path went directly above the compound path, the second above the first.
|
||||
@@ -687,6 +733,14 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
|
||||
let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap();
|
||||
assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}");
|
||||
}
|
||||
// A change of spacing alone leaves the stored columns as they are, so leaving the rows later
|
||||
// gives the same grid with or without it.
|
||||
let to_row = json!({"artboardLayout": {"layout": "gridByRow"}});
|
||||
let plain = stored.clone().with_params(&json!({"artboards": 9}), "file.new").unwrap();
|
||||
let spaced = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": {"spacing": 20}}), "file.new").unwrap();
|
||||
assert_eq!((plain.grid_columns(), spaced.grid_columns()), (3, 3));
|
||||
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
|
||||
assert_eq!(plain.grid_columns(), spaced.grid_columns());
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows must be 1 or more"), "{e}");
|
||||
for layout in ["gridByRow", "row", "column"] {
|
||||
@@ -758,6 +812,26 @@ fn an_edit_keeps_the_order_of_a_mixed_selection() {
|
||||
assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors));
|
||||
}
|
||||
|
||||
/// A path with segments selected and no anchors gets the segments back, not every anchor.
|
||||
#[test]
|
||||
fn an_edit_keeps_a_path_with_only_a_segment_selected() {
|
||||
let (mut s, a, b) = doc();
|
||||
rect(&mut s, 200.0, 200.0, 20.0, 20.0);
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap();
|
||||
s.doc_mut().unwrap().selection.anchors.remove(&b);
|
||||
let before = s.active().unwrap().selection.clone();
|
||||
log(&mut s, "app.activeDocument.pageItems[2].duplicate();");
|
||||
let sel = &s.active().unwrap().selection;
|
||||
assert_eq!((&sel.objects, &sel.segments, sel.anchors.get(&a)), (&before.objects, &before.segments, before.anchors.get(&a)));
|
||||
// The segment brings back its own two end points, as `select.segments` selects them, and none
|
||||
// of the path's other anchors: the journaled restore selects none of them first.
|
||||
assert_eq!(sel.anchors.get(&b).map(|k| k.len()), Some(2), "{sel:?}");
|
||||
let restore = s.journal.iter().rev().find(|(id, _)| id == "select.anchorsMany").map(|(_, p)| p.clone()).unwrap();
|
||||
let path = restore["items"].as_array().unwrap().iter().find(|i| i["id"] == json!(b.0)).cloned().unwrap();
|
||||
assert_eq!(path["anchors"], json!([]), "{restore}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_the_selection_clears_a_layers_panel_target() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -985,6 +1059,55 @@ fn a_document_preset_is_an_instance_of_its_class() {
|
||||
assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]);
|
||||
}
|
||||
|
||||
/// The values the presets hold count against the run's heap, a value assigned again in place of
|
||||
/// the one before it.
|
||||
#[test]
|
||||
fn document_preset_values_are_bounded_by_the_runs_heap() {
|
||||
use crate::script::TEST_ENGINE_HEAP;
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20)));
|
||||
let mut s = Session::new();
|
||||
// A title of 4,092 bytes, which with the loop counter stays within the 4,096 a title may have.
|
||||
let big = "var s = 'a'; while (s.length < 4092) s += 'a';";
|
||||
let again =
|
||||
format!("#targetengine presets\n{big} var p = new DocumentPreset(); for (var k = 0; k < 1000; k++) p.title = s + k; vc.log(p.title.length);");
|
||||
assert_eq!(log(&mut s, &again), vec![json!(4095)]);
|
||||
let many = format!(
|
||||
"#targetengine presets\n{big} var m = '';\
|
||||
try {{ for (var k = 0; k < 2000; k++) {{ var p = new DocumentPreset(); p.title = s; }} }} catch (e) {{ m = e.name + ': ' + e.message; }}\
|
||||
vc.log(k < 2000); vc.log(m);"
|
||||
);
|
||||
let out = log(&mut s, &many);
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(None));
|
||||
assert_eq!(out[0], json!(true), "{out:?}");
|
||||
assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}");
|
||||
}
|
||||
|
||||
/// An array a preset holds counts a whole value for each element: presets that each hold a
|
||||
/// `documentBleedOffsetRect` of four numbers reach the run's heap after fewer presets than ones
|
||||
/// that each hold an eight-byte `title`, which counts one value and its text.
|
||||
#[test]
|
||||
fn document_preset_arrays_count_each_element_they_hold() {
|
||||
use crate::script::TEST_ENGINE_HEAP;
|
||||
let made = |assign: &str| {
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(Some(1 << 20)));
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"#targetengine presets\nvar m = '';\
|
||||
try {{ for (var k = 0; k < 10000; k++) {{ var p = new DocumentPreset(); {assign} }} }} catch (e) {{ m = e.name + ': ' + e.message; }}\
|
||||
vc.log(k); vc.log(m);"
|
||||
),
|
||||
);
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(None));
|
||||
assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{assign}: {out:?}");
|
||||
out[0].as_f64().unwrap()
|
||||
};
|
||||
let with_title = made("p.title = 'abcdefgh';");
|
||||
let with_rect = made("p.documentBleedOffsetRect = [1, 2, 3, 4];");
|
||||
assert!(with_rect < with_title, "{with_rect} presets with a rectangle, {with_title} with a title");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_document_or_item_is_the_same_object() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -1265,20 +1388,75 @@ fn wrappers_go_stale_after_delete_and_undo() {
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
}
|
||||
|
||||
/// File › Revert loads objects with the ids they were saved with: an object or a layer read before
|
||||
/// the revert does not name the loaded one.
|
||||
#[test]
|
||||
fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_ones() {
|
||||
// `pageItems[0]` is the topmost object, the one made last.
|
||||
let (mut s, _, b) = doc();
|
||||
let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("saved.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] {
|
||||
let source = format!("var i = app.activeDocument.pageItems[0], l = i.parent; i.name = 'before'; vc.run('file.revert'); {read};");
|
||||
let e = failure(&mut s, &source);
|
||||
assert!(e.contains("Stale page item"), "{read}: {e}");
|
||||
}
|
||||
// Objects read after the revert are the loaded ones.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems; p[0].name = 'before'; vc.run('file.revert');\
|
||||
app.activeDocument.pageItems[0].name = 'loaded'; vc.log(app.activeDocument.pageItems.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2)]);
|
||||
assert_eq!(s.active().unwrap().doc.node(b).unwrap().name.as_deref(), Some("loaded"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[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();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();");
|
||||
assert!(e.contains(&b.0.to_string()), "{e}");
|
||||
assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
// The script catches the error and finds both objects still there before the run ends, so the
|
||||
// run's own rollback cannot hide a deletion.
|
||||
let caught = "var p = app.activeDocument.pageItems, m = '';\
|
||||
try { p.removeAll(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(p.length);";
|
||||
let out = log(&mut s, caught);
|
||||
assert!(out[0].as_str().unwrap().contains(&b.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some());
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
|
||||
// A locked object inside an unlocked group stops it too.
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();");
|
||||
assert!(e.contains(&g.to_string()), "{e}");
|
||||
let out = log(&mut s, caught);
|
||||
assert!(out[0].as_str().unwrap().contains(&g.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(3));
|
||||
assert!(s.active().unwrap().doc.node(b).is_some());
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
|
||||
let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);");
|
||||
@@ -1898,7 +2076,8 @@ fn objects_of_the_object_model_print_their_class_and_name() {
|
||||
}
|
||||
|
||||
/// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and
|
||||
/// assigning one assigns the member: `selection` selects, `documents` keeps its value.
|
||||
/// assigning one assigns the member: `selection` selects, and `documents` keeps its value outside
|
||||
/// strict mode and throws a `TypeError` in strict mode code or with `#strict on`.
|
||||
#[test]
|
||||
fn the_application_members_can_be_named_without_app() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1925,6 +2104,8 @@ fn the_application_members_can_be_named_without_app() {
|
||||
assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document"));
|
||||
let e = failure(&mut s, "'use strict'; documents = 5;");
|
||||
assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}");
|
||||
let e = failure(&mut s, "#strict on\ndocuments = 5;");
|
||||
assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}");
|
||||
// With no document open, reading `activeDocument` throws as `app.activeDocument` does.
|
||||
let mut s = Session::new();
|
||||
assert!(failure(&mut s, "activeDocument;").contains("No active document"));
|
||||
|
||||
@@ -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<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
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::<Vec<_>>()), Some(vec!["other".to_string()]));
|
||||
assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::<Vec<_>>()), 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::<Vec<_>>()), 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#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<variableSets>
|
||||
<variableSet varSetName="binding1" locked="none">
|
||||
<variables>
|
||||
<variable varName="title" trait="textcontent"/>
|
||||
<variable varName="badge" trait="visibility"/>
|
||||
</variables>
|
||||
<sampleDataSets>
|
||||
<sampleDataSet dataSetName="One"><title><p>Hello</p></title><badge>true</badge></sampleDataSet>
|
||||
<sampleDataSet dataSetName="Two"><title><p>World</p></title><badge>false</badge></sampleDataSet>
|
||||
</sampleDataSets>
|
||||
</variableSet>
|
||||
</variableSets>
|
||||
"#;
|
||||
|
||||
/// 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<Value> {
|
||||
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#"<?xml version="1.0"?><!DOCTYPE v [<!ENTITY x SYSTEM "file:///etc/hosts">]><variableSets><variableSet><variables><variable varName="a" trait="textcontent"/></variables></variableSet></variableSets>"#;
|
||||
std::fs::write(base.join("main/external.xml"), external).unwrap();
|
||||
let deep = format!("<variableSets>{}{}</variableSets>", "<a>".repeat(300), "</a>".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\"", "<p>Hello</p>"] {
|
||||
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)]);
|
||||
}
|
||||
@@ -52,6 +52,9 @@ fn a_click_outside_an_outside_stroke_selects_it() {
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 20, "align": "outside"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// Object Selection by Path Only: the inside of the unfilled square takes no click of its own,
|
||||
// so only the stroke is tested.
|
||||
s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap();
|
||||
// 0.8 × the weight outside the path: past where a centred stroke (plus the tolerance) reaches.
|
||||
assert_eq!(click(&mut s, 84.0, 200.0), [r]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
@@ -59,6 +62,9 @@ fn a_click_outside_an_outside_stroke_selects_it() {
|
||||
s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach");
|
||||
// With it off, a click inside the unfilled square selects it (#9175).
|
||||
s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap();
|
||||
assert_eq!(click(&mut s, 116.0, 200.0), [r]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -966,7 +966,9 @@ fn pdf_of(objs: &[Vec<u8>]) -> Vec<u8> {
|
||||
|
||||
/// 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.
|
||||
@@ -4940,6 +4950,37 @@ proptest! {
|
||||
survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose placed EPS files have their bytes included between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` (one on `%_` lines, one with a nested document and counted data in it),
|
||||
/// damaged, opened and drawn: their bytes are read as an EPS file when drawn.
|
||||
#[test]
|
||||
fn ai_placed_eps_files_with_included_bytes_never_panic(
|
||||
cut in 0usize..4_000,
|
||||
edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', '`', '~', 'E', 'D'])), 0..12),
|
||||
) {
|
||||
use vectorcraft_testkit::ai;
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 40\n%%EndComments\n0 0 1 setrgbcolor\n0 0 60 40 rectfill\n%%EOF\n";
|
||||
let nested = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n%%BeginDocument: c.eps\nnewpath\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n";
|
||||
let place = |path: &str, matrix: &str, doc: &str| {
|
||||
format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n{matrix} 0 0 60 40 4 4 0\n({path})`\n%%BeginDocument: {path}\n{doc}\n%%EndDocument\n\
|
||||
%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"
|
||||
)
|
||||
};
|
||||
let hidden: String = place("/tmp/b.eps", "[1 0 0 1 20 20]", eps).lines().map(|l| format!("%_{l}\n")).collect();
|
||||
let body = format!("{}{hidden}{}", place("/tmp/a.eps", "[1 0 0 1 20 20]", eps), place("/tmp/c.eps", "[1 0 0 1 0 0]", nested));
|
||||
let fixture = ai::editing_data(200.0, 100.0, &ai::layer("L", &body));
|
||||
// A session reads placed documents' files when they are drawn.
|
||||
let _ = vectorcraft_engine::Session::new();
|
||||
let whole = vectorcraft_engine::cmd::fileio::load("x.ai", &ai::ai(fixture.as_bytes(), "0 0 1 rg 20 20 60 40 re f"));
|
||||
let mut placed = 0;
|
||||
whole.iter().for_each(|l| l.doc.visit_placed(|_, _| placed += 1));
|
||||
prop_assert!(placed == 3 && fixture.len() < 4_000, "{placed} placed documents, {} bytes: {:?}", fixture.len(), whole.map(|l| l.warnings));
|
||||
let text = mutate_text(&fixture, cut, &edits);
|
||||
let file = ai::ai(text.as_bytes(), "0 0 1 rg 20 20 60 40 re f");
|
||||
survive("hostile .ai placed EPS files with included bytes", || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type
|
||||
/// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai`
|
||||
/// writer writes them) is damaged: read from its editing data alone and beside a page.
|
||||
@@ -6380,6 +6421,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
|
||||
"\n%%BeginData: 14 Binary Bytes\n",
|
||||
"\n%%BeginBinary: 99999999999\n",
|
||||
"\n%%BeginData: 3 Hex Lines\n",
|
||||
// A placed EPS file's bytes included in the data: one drawn, one with a box it can't
|
||||
// take, one on `%_` lines.
|
||||
"\n%%BeginDocument: a.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n0 0 1 setrgbcolor 0 0 9 9 rectfill\n%%EndDocument\n",
|
||||
"\n%%BeginDocument: a.eps\n%!PS\n%%BoundingBox: 0 0 1e308 -5\n%%EndDocument\n",
|
||||
"\n%_%%BeginDocument: a.eps\n%_%!PS\n%_0 0 9 9 rectfill\n%_%%EndDocument\n",
|
||||
"[1 0 0 1 0 0] 0 0 1e308 1e308 4 4 0 (a.eps) `",
|
||||
"\n%AI5_EndPlace\n",
|
||||
"Xm",
|
||||
"50 -50 -100 -100 5000 -2000 Xm",
|
||||
@@ -7716,7 +7763,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 +7772,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 +8408,30 @@ fn ai_private(layer_art: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// 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! {
|
||||
|
||||
@@ -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"),
|
||||
];
|
||||
|
||||
@@ -46,7 +47,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// documents; `Document.saveAs` and `close` throw "not available yet".
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue alert confirm localize prompt toSource"),
|
||||
("Object.prototype.", "toSource"),
|
||||
("Object.prototype.", "reflect toSource"),
|
||||
("UnitValue.", "baseUnit baseUnit= length prototype"),
|
||||
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
|
||||
("localize.", "length"),
|
||||
@@ -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.
|
||||
|
||||
@@ -481,6 +481,44 @@ fn arb_object() -> impl Strategy<Value = (Option<usize>, 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<Value = Map<String, Value>> {
|
||||
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::<bool>().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<usize>, Value)], inputs: &[u64], junk: Option<Value>) -> 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::<bool>(),
|
||||
) {
|
||||
let mut s = rich_session();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let pieces: Vec<(Option<usize>, 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]
|
||||
|
||||
@@ -8,6 +8,11 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# `vectorcraft_eps::blend_work` and `vectorcraft_eps::included_eps_reads` for other crates' tests
|
||||
# (dev-dependencies only).
|
||||
work-count = []
|
||||
|
||||
[dependencies]
|
||||
craft-eps = { workspace = true }
|
||||
craft-ps = { workspace = true }
|
||||
@@ -48,3 +53,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"] }
|
||||
@@ -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")
|
||||
|
||||
@@ -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)]
|
||||
@@ -278,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result<Rect, String> {
|
||||
Ok(Rect::new(0.0, 0.0, urx - llx, ury - lly))
|
||||
}
|
||||
|
||||
/// An EPS or PostScript file's bounding box (`%%HiResBoundingBox` when it has one) in its own
|
||||
/// space, as `[llx, lly, urx, ury]`, read from its comments; `None` without one.
|
||||
pub(crate) fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> {
|
||||
Dsc::read(program(bytes).ok()?).bbox
|
||||
}
|
||||
|
||||
/// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data`
|
||||
/// (else what its page prints, as any EPS).
|
||||
pub fn import_with(bytes: &[u8], editing_data: bool) -> Result<Imported, String> {
|
||||
|
||||
@@ -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,
|
||||
@@ -60,12 +62,12 @@ pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color,
|
||||
read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
BLEND_BUDGET, LINKED_PREVIEWS, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with,
|
||||
parsed_type_color, read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
palette, read_beside, read_in, symbols, variables,
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedEps, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes,
|
||||
graphic_styles, palette, read_beside, read_in, symbols, variables,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use style::ART_STYLE_PARSES;
|
||||
|
||||
@@ -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<NodeId, (String, Option<String>)>;
|
||||
|
||||
@@ -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<f64> {
|
||||
.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.
|
||||
|
||||
@@ -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;
|
||||
@@ -59,6 +59,9 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str {
|
||||
pub(super) const MAX_PENDING: usize = 64;
|
||||
/// The most envelopes and warped text objects one import draws to check; more keep their drawn art.
|
||||
pub(crate) const MAX_CHECKED: usize = 256;
|
||||
/// The most comparisons with pages those checks make in one import, one for each page an object
|
||||
/// is on ([`drawn_alike`]); an object that needs more keeps its drawn art.
|
||||
pub(crate) const MAX_PAGE_COMPARISONS: usize = 4 * MAX_CHECKED;
|
||||
/// The most strokes with dashes aligned to corners one import draws to check against their drawn
|
||||
/// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks.
|
||||
pub(crate) const MAX_DASH_CHECKS: usize = 256;
|
||||
@@ -133,7 +136,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<Node>], 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 +308,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)
|
||||
}
|
||||
|
||||
@@ -664,13 +667,31 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt
|
||||
}
|
||||
|
||||
/// The differences from their drawn art that the live envelopes and warped type of one import may
|
||||
/// add up to, as shares of the page drawn as the page check draws it: half of what that check allows
|
||||
/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so they never make the file open from its PDF part
|
||||
/// instead.
|
||||
/// add up to on each page the art may be compared with, as shares of that page drawn as the page
|
||||
/// check draws it: half of what that check allows ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]),
|
||||
/// so they never make the file open from its PDF part instead. Each page has its own share.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Spent {
|
||||
pub(super) any: f64,
|
||||
pub(super) solid: f64,
|
||||
/// Each page with the shares of it spent so far: of pixels that differ at all, and of those
|
||||
/// whose neighbors all differ too.
|
||||
pub(super) pages: Vec<(Rect, f64, f64)>,
|
||||
/// How many comparisons with pages have been made ([`MAX_PAGE_COMPARISONS`]).
|
||||
pub(super) compared: usize,
|
||||
}
|
||||
|
||||
impl Spent {
|
||||
/// The shares of `page` spent so far.
|
||||
pub(super) fn on(&self, page: Rect) -> (f64, f64) {
|
||||
self.pages.iter().find(|(p, ..)| *p == page).map_or((0.0, 0.0), |&(_, any, solid)| (any, solid))
|
||||
}
|
||||
|
||||
/// Set the shares of `page` spent so far.
|
||||
fn set(&mut self, page: Rect, any: f64, solid: f64) {
|
||||
match self.pages.iter_mut().find(|(p, ..)| *p == page) {
|
||||
Some(spent) => *spent = (page, any, solid),
|
||||
None => self.pages.push((page, any, solid)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A text object read with a Warp.
|
||||
@@ -738,7 +759,8 @@ pub struct WarpedType {
|
||||
pub(super) envelopes: Vec<TypedEnvelope>,
|
||||
pub(super) checks: usize,
|
||||
pub(super) spent: Spent,
|
||||
pub(super) page: Option<Rect>,
|
||||
/// The pages the art may be compared with, each with its own share of the budget ([`Spent`]).
|
||||
pub(super) pages: Vec<Rect>,
|
||||
/// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too.
|
||||
pub(super) type_clips: HashMap<NodeId, NodeId>,
|
||||
/// The envelopes of type that may open live in layers built without a page, by their place
|
||||
@@ -884,7 +906,7 @@ impl WarpedType {
|
||||
let (id, layer) = (doc.alloc_id(), doc.alloc_id());
|
||||
let mut plain = art.clone();
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
let page = self.page.filter(|_| shown.contains(&drawn));
|
||||
let pages: Vec<Rect> = if shown.contains(&drawn) { self.pages.clone() } else { vec![] };
|
||||
let mut alike = None;
|
||||
// In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again
|
||||
// moved onto that art ([`moved_onto`]), after every other way.
|
||||
@@ -917,7 +939,7 @@ impl WarpedType {
|
||||
let shared = Shared { patterns: &doc.patterns, images: &doc.images };
|
||||
let mut live_one = envelope.clone();
|
||||
(live_one.visible, live_one.opacity) = (true, 1.0);
|
||||
if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) {
|
||||
if drawn_alike(&live_one, &plain, layer, &shared, &pages, &mut self.spent) {
|
||||
alike = Some(envelope);
|
||||
break;
|
||||
}
|
||||
@@ -942,7 +964,8 @@ impl WarpedType {
|
||||
/// budget has no check left for) with that look: `made` gives the text object a slot became. A
|
||||
/// frame in `threaded` stays type, since the frames of a thread share one story. A replaced
|
||||
/// object's box goes back into the comparisons with the page (out of `restyled`), and only what
|
||||
/// `doc` shows counts against the page's share of the budget. Returns how many were replaced.
|
||||
/// `doc` shows counts against the share of the budget of each page it is on. Returns how many
|
||||
/// were replaced.
|
||||
pub(crate) fn settle(
|
||||
self,
|
||||
doc: &mut Document,
|
||||
@@ -950,7 +973,7 @@ impl WarpedType {
|
||||
threaded: &BTreeSet<NodeId>,
|
||||
restyled: &mut Vec<Rect>,
|
||||
) -> usize {
|
||||
let Self { looks, mut checks, mut spent, page, .. } = self;
|
||||
let Self { looks, mut checks, mut spent, pages, .. } = self;
|
||||
let mut shown_ids = BTreeSet::new();
|
||||
doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids));
|
||||
let mut replaced = 0;
|
||||
@@ -965,7 +988,8 @@ impl WarpedType {
|
||||
let (mut shown, mut plain) = (text.clone(), look.clone());
|
||||
(shown.visible, shown.opacity) = (true, 1.0);
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
alike = warped_alike(&shown, &plain, layer, &shared, page.filter(|_| shown_ids.contains(&id)), &mut spent);
|
||||
let on: &[Rect] = if shown_ids.contains(&id) { &pages } else { &[] };
|
||||
alike = warped_alike(&shown, &plain, layer, &shared, on, &mut spent);
|
||||
}
|
||||
if alike {
|
||||
continue;
|
||||
@@ -1032,23 +1056,24 @@ pub(super) fn warps(appearance: &Appearance) -> bool {
|
||||
}
|
||||
|
||||
/// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the
|
||||
/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the
|
||||
/// file has one), they differ little enough that with the differences in `spent` the page check
|
||||
/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a
|
||||
/// layer id no other node has.
|
||||
pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
|
||||
alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent)
|
||||
/// pixels either inks differ and fewer still where a whole patch differs, and, on each of `pages`
|
||||
/// they are on (the pages the art may be compared with), they differ little enough that with the
|
||||
/// differences `spent` holds for that page the page check still takes the layers' art (they are
|
||||
/// added to `spent` when they do on every one). Both are drawn on `layer`, a layer id no other node
|
||||
/// has.
|
||||
pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool {
|
||||
alike_within(live, drawn, live.visual_bounds(), layer, shared, pages, spent)
|
||||
}
|
||||
|
||||
/// [`drawn_alike`] for type under a Warp, compared over all that its effects draw, which can reach
|
||||
/// past its own box.
|
||||
pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
|
||||
pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool {
|
||||
let reach = vectorcraft_render::effect_bounds(&alone(live, layer, shared).symbol_boxes(), live);
|
||||
alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, page, spent)
|
||||
alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, pages, spent)
|
||||
}
|
||||
|
||||
/// [`drawn_alike`], with `live` measured as `reach`.
|
||||
fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
|
||||
fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool {
|
||||
// Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted):
|
||||
// both draw nothing, so they draw alike and add nothing to what the page check sees. Their
|
||||
// shapes aren't compared. Art that paints, however faintly, is compared as before.
|
||||
@@ -1069,21 +1094,31 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, s
|
||||
if share(solid) > MAX_SOLID || share(any) > MAX_ANY {
|
||||
return false;
|
||||
}
|
||||
let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true };
|
||||
// Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the
|
||||
// page's longer side).
|
||||
let on_page = region.intersect(page);
|
||||
let scale = compare_scale(page);
|
||||
if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 {
|
||||
return true;
|
||||
let mut added = vec![];
|
||||
for &page in pages.iter().filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) {
|
||||
// Only what is on the page counts, drawn as the page check draws it (about 400 pixels along
|
||||
// the page's longer side).
|
||||
let on_page = region.intersect(page);
|
||||
let scale = compare_scale(page);
|
||||
if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 {
|
||||
continue;
|
||||
}
|
||||
if spent.compared >= MAX_PAGE_COMPARISONS {
|
||||
return false;
|
||||
}
|
||||
spent.compared += 1;
|
||||
let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false };
|
||||
let pixels = (page.width() * scale * page.height() * scale).max(1.0);
|
||||
let (was_any, was_solid) = spent.on(page);
|
||||
let (any, solid) = (was_any + any as f64 / pixels, was_solid + solid as f64 / pixels);
|
||||
if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 {
|
||||
return false;
|
||||
}
|
||||
added.push((page, any, solid));
|
||||
}
|
||||
let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false };
|
||||
let pixels = (page.width() * scale * page.height() * scale).max(1.0);
|
||||
let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels);
|
||||
if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 {
|
||||
return false;
|
||||
for (page, any, solid) in added {
|
||||
spent.set(page, any, solid);
|
||||
}
|
||||
*spent = Spent { any, solid };
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1161,7 +1196,7 @@ mod tests {
|
||||
#[test]
|
||||
fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() {
|
||||
let shared = Shared { patterns: &[], images: &BTreeMap::new() };
|
||||
let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default());
|
||||
let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, &[], &mut Spent::default());
|
||||
let (none, other_none) = (square_node(1, None), square_node(2, None));
|
||||
assert!(alike(&none, &other_none));
|
||||
let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02)));
|
||||
@@ -1169,6 +1204,22 @@ mod tests {
|
||||
assert!(!alike(&none, &square_node(2, Some(1.0))));
|
||||
}
|
||||
|
||||
/// Each page an object is on takes one of the import's comparisons with pages. With none left,
|
||||
/// art on a page keeps its drawn art, and art on no page needs none.
|
||||
#[test]
|
||||
fn comparisons_with_pages_stop_at_their_limit() {
|
||||
let shared = Shared { patterns: &[], images: &BTreeMap::new() };
|
||||
let (live, drawn) = (square_node(1, Some(1.0)), square_node(2, Some(1.0)));
|
||||
let (page, other) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
let mut spent = Spent { compared: MAX_PAGE_COMPARISONS - 2, ..Default::default() };
|
||||
assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[page, other], &mut spent));
|
||||
assert_eq!(spent.compared, MAX_PAGE_COMPARISONS);
|
||||
assert!(!drawn_alike(&live, &drawn, NodeId(999), &shared, &[page], &mut spent));
|
||||
let off = Rect::new(500.0, 500.0, 600.0, 600.0);
|
||||
assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[off], &mut spent));
|
||||
assert_eq!(spent.compared, MAX_PAGE_COMPARISONS);
|
||||
}
|
||||
|
||||
/// "AVA" at 40 points, at (10, 60).
|
||||
fn type_node(id: u64, style: CharStyle) -> Node {
|
||||
Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style }))))
|
||||
|
||||
@@ -57,8 +57,13 @@
|
||||
//! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and
|
||||
//! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`,
|
||||
//! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before
|
||||
//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document
|
||||
//! that doesn't end leave the placed file unread.
|
||||
//! the path. A placed EPS file whose bytes are included between `%%BeginDocument:` and
|
||||
//! `%%EndDocument` (DSC 3.0 p. 68) is a placed document that keeps those bytes and draws them,
|
||||
//! its file found or not; its box is the
|
||||
//! file's bounding box, which the matrix takes from the file's own space (y up) into art space,
|
||||
//! as in the version 7 form.
|
||||
//! Operands of any other shape, a second `` ` `` before `~` or an included document that
|
||||
//! doesn't end leave the placed file unread.
|
||||
//! - Art with an appearance the format can't write as plain art (several fills or strokes,
|
||||
//! effects, brushes) comes first as that look, drawn (a group, or an image where an effect
|
||||
//! rasterizes it), then the object itself on `%_`
|
||||
@@ -148,22 +153,27 @@ mod raster;
|
||||
mod types;
|
||||
|
||||
pub(crate) use art::join_and;
|
||||
use art::preview_png;
|
||||
use art::{included_document, preview_png};
|
||||
pub use document::{
|
||||
BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette,
|
||||
symbols, variables,
|
||||
};
|
||||
pub(crate) use document::{slot_frame, slot_of};
|
||||
use graph::Graph;
|
||||
#[cfg(test)]
|
||||
pub(crate) use on_path::on_path_measured;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ops::array_slots;
|
||||
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list};
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::with_image_limits;
|
||||
pub(crate) use types::BLEND_BUDGET;
|
||||
pub(crate) use types::LINKED_PREVIEWS;
|
||||
pub(crate) use types::MAX_NODES;
|
||||
pub use types::PlacedPage;
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, MAX_PLACED_DOCUMENT, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
#[cfg(test)]
|
||||
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
|
||||
pub use types::{PlacedEps, PlacedPage};
|
||||
pub(super) use types::{blend_mode, blend_name};
|
||||
|
||||
#[path = "legacy_text.rs"]
|
||||
@@ -212,6 +222,8 @@ pub struct Structure {
|
||||
pub placed_elsewhere: Vec<(NodeId, Affine)>,
|
||||
/// The placed files that are pages of PDF or `.ai` files.
|
||||
pub placed_pages: Vec<PlacedPage>,
|
||||
/// Included EPS files whose previews wait for variable binding before conversion.
|
||||
pub placed_eps: Vec<PlacedEps>,
|
||||
/// The live envelopes read from the editing data, by id, with the drawn art each took the place
|
||||
/// of: the importer puts that art back when the layers with the envelopes don't draw as the page.
|
||||
pub envelopes_drawn: Vec<(NodeId, Node)>,
|
||||
@@ -472,6 +484,10 @@ struct BrushesKept {
|
||||
bending: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
/// What the pages the art may be compared with are worked out from: the move into the document,
|
||||
/// the number of artboards, the first artboard and the art's bounding box.
|
||||
type PageSources = (Option<Affine>, usize, Option<Rect>, Option<Rect>);
|
||||
|
||||
struct Reader<'a> {
|
||||
lex: Lexer<'a>,
|
||||
stack: Vec<V>,
|
||||
@@ -604,6 +620,8 @@ struct Reader<'a> {
|
||||
envelope_checks: usize,
|
||||
/// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]).
|
||||
envelope_spent: super::envelope::Spent,
|
||||
/// [`Self::pages_in_doc`] as last worked out, with what it was worked out from.
|
||||
page_cache: Option<(PageSources, Arc<[Rect]>)>,
|
||||
/// How many more strokes with dashes aligned to corners this import may draw to check
|
||||
/// ([`super::MAX_DASH_CHECKS`]).
|
||||
dash_checks: usize,
|
||||
@@ -667,6 +685,8 @@ struct Reader<'a> {
|
||||
placed_elsewhere: Vec<(NodeId, Affine)>,
|
||||
/// See [`Structure::placed_pages`].
|
||||
placed_pages: Vec<PlacedPage>,
|
||||
/// See [`Structure::placed_eps`].
|
||||
placed_eps: Vec<PlacedEps>,
|
||||
unread_elsewhere: Vec<(NodeId, Rect)>,
|
||||
/// CMYK samples converted, by value.
|
||||
cmyk_cache: HashMap<[u8; 4], [u8; 3]>,
|
||||
@@ -877,6 +897,7 @@ impl<'a> Reader<'a> {
|
||||
envelopes: Vec::new(),
|
||||
envelope_checks: super::envelope::MAX_CHECKED,
|
||||
envelope_spent: super::envelope::Spent::default(),
|
||||
page_cache: None,
|
||||
dash_checks: super::MAX_DASH_CHECKS,
|
||||
defs_only: false,
|
||||
warped_type: Vec::new(),
|
||||
@@ -901,6 +922,7 @@ impl<'a> Reader<'a> {
|
||||
placeholders: vec![],
|
||||
placed_elsewhere: vec![],
|
||||
placed_pages: vec![],
|
||||
placed_eps: vec![],
|
||||
placed_tails: vec![],
|
||||
unread_elsewhere: vec![],
|
||||
mesh: None,
|
||||
@@ -939,6 +961,15 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The line end just before `doc`, an included document the lexer has just read: the one that
|
||||
/// ends its `%%BeginDocument:` line. `None` when `doc` isn't in the data read so far.
|
||||
fn line_end_before(&self, doc: &[u8]) -> Option<&'static [u8]> {
|
||||
let read = self.lex.slice(0, self.lex.offset());
|
||||
let at = doc.as_ptr().addr().checked_sub(read.as_ptr().addr())?;
|
||||
let before = read.get(..at)?;
|
||||
[&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| before.ends_with(e))
|
||||
}
|
||||
|
||||
fn run(&mut self) -> Result<(), String> {
|
||||
while let Some(t) = self.lex.next_token() {
|
||||
if self.done {
|
||||
@@ -961,11 +992,14 @@ impl<'a> Reader<'a> {
|
||||
p.preview = preview_png(d);
|
||||
}
|
||||
}
|
||||
// A placed file's document, included whole: its art isn't read here. When no
|
||||
// `%%EndDocument` ends it, the placed file isn't read.
|
||||
// A placed file's document, included whole: its art isn't read here, its bytes are
|
||||
// kept for the placed file. When no `%%EndDocument` ends it, the placed file isn't
|
||||
// read.
|
||||
Tok::Document(d) => {
|
||||
let sep = d.and_then(|d| self.line_end_before(d));
|
||||
if let Some(p) = self.place.as_mut() {
|
||||
p.broken |= d.is_none();
|
||||
p.document = d.filter(|d| d.len() <= MAX_PLACED_DOCUMENT).map(|d| included_document(d, hidden, sep));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,88 @@ use super::containers::close;
|
||||
use super::document::TEXT_SLOT;
|
||||
use super::raster::{self, Limits, Shape};
|
||||
use super::types::{
|
||||
FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS,
|
||||
MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail,
|
||||
EPS_MIME, FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE,
|
||||
MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedEps, PlacedPage, PlacedTail,
|
||||
};
|
||||
use super::{
|
||||
Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node,
|
||||
NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps,
|
||||
};
|
||||
use vectorcraft_doc::links::missing_placeholder;
|
||||
use vectorcraft_doc::PlacedDocument;
|
||||
use vectorcraft_doc::links::{hash_bytes, missing_placeholder};
|
||||
use vectorcraft_doc::placed_document::key_for;
|
||||
use vectorcraft_pdf::is_postscript;
|
||||
|
||||
/// Open-check results by content and nesting depth: the remaining depth changes their warnings.
|
||||
type EpsChecks = Vec<((String, usize), Option<Vec<String>>)>;
|
||||
|
||||
/// The most open-check results kept during one outer check; no file bytes are retained.
|
||||
const MAX_EPS_CHECKS: usize = 64;
|
||||
|
||||
std::thread_local! {
|
||||
/// How many included EPS files [`readable_eps`] is reading inside one another on this thread.
|
||||
static READING_EPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Checks completed during this thread's outer check, including files that do not read.
|
||||
static EPS_CHECKS: std::cell::RefCell<EpsChecks> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// An included EPS file being read by [`readable_eps`] ([`READING_EPS`]): the count goes down when
|
||||
/// this goes.
|
||||
struct ReadingEps;
|
||||
|
||||
impl ReadingEps {
|
||||
/// `None` when 8 are being read.
|
||||
fn enter() -> Option<Self> {
|
||||
READING_EPS.with(|d| (d.get() < 8).then(|| d.set(d.get() + 1))).map(|()| Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReadingEps {
|
||||
fn drop(&mut self) {
|
||||
READING_EPS.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
if READING_EPS.with(std::cell::Cell::get) == 0 {
|
||||
EPS_CHECKS.with_borrow_mut(Vec::clear);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The warnings of reading `bytes` as an EPS file, the way a placed document's art is read from
|
||||
/// them (art left out after an operator that isn't read, for one); `None` when they don't read.
|
||||
/// Past 8 included files read inside one another they count as readable without warnings; drawing
|
||||
/// reads a bounded number of them in turn. The check uses previews for placed documents, so
|
||||
/// drawing does not start another chain of checks inside this one. Repeated structural reads
|
||||
/// share completed checks at the same depth until the outer check ends.
|
||||
fn readable_eps(bytes: &[u8]) -> Option<Vec<String>> {
|
||||
let key = (hash_bytes(bytes), READING_EPS.with(std::cell::Cell::get));
|
||||
if let Some(warnings) = EPS_CHECKS.with_borrow(|c| c.iter().find(|(k, _)| *k == key).map(|(_, warnings)| warnings.clone())) {
|
||||
return warnings;
|
||||
}
|
||||
let Some(_reading) = ReadingEps::enter() else { return Some(vec![]) };
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
crate::INCLUDED_EPS_READS.with(|n| n.set(n.get() + 1));
|
||||
let warnings = vectorcraft_doc::placed_document::with_previews(|| {
|
||||
crate::import_names(bytes, true, false, crate::NameEncoding::default()).ok().map(|r| r.warnings)
|
||||
});
|
||||
EPS_CHECKS.with_borrow_mut(|c| {
|
||||
if c.len() >= MAX_EPS_CHECKS {
|
||||
c.remove(0);
|
||||
}
|
||||
c.push((key, warnings.clone()));
|
||||
});
|
||||
warnings
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
/// Do the bytes `eps` of an included EPS file read ([`readable_eps`])? When they do, what reading
|
||||
/// them warns of is a warning of this file's too.
|
||||
fn read_included(&mut self, eps: &[u8]) -> bool {
|
||||
let Some(warnings) = readable_eps(eps) else { return false };
|
||||
for w in warnings {
|
||||
self.warn(&format!("a placed EPS file: {w}"));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A text object (`/AI11Text`): an empty group standing for it, named after its story.
|
||||
pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> {
|
||||
if self.pattern.is_some() {
|
||||
@@ -838,8 +909,9 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that
|
||||
/// shows the preview the data keeps of it, as a linked image whose file is missing does. One
|
||||
/// without a preview, a path or a matrix isn't read.
|
||||
/// shows the preview the data keeps of it, as a linked image whose file is missing does. An EPS
|
||||
/// file whose bytes the data includes becomes a placed document of them ([`Self::placed_eps`]).
|
||||
/// One without a preview or those bytes, a path or a matrix isn't read.
|
||||
pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> {
|
||||
// Where a symbol's art puts a placed file's pixels isn't known.
|
||||
if self.symbol.is_some() {
|
||||
@@ -847,11 +919,43 @@ impl<'a> Reader<'a> {
|
||||
self.left_out_of_symbol();
|
||||
return Ok(());
|
||||
}
|
||||
let mut deferred = None;
|
||||
let (m, b, path, png, w, h, folder) = match self.place.take() {
|
||||
Some(Place { broken: true, .. }) => {
|
||||
self.unreadable("placed files", hidden);
|
||||
return Ok(());
|
||||
}
|
||||
Some(Place { matrix: Some(m), bounds: Some(b), path, document: Some(eps), preview, folder, .. })
|
||||
// A file without a bounding box of its own has its art read on a page of another
|
||||
// size, which the placed box can't be matched to.
|
||||
// One named `.ai` or `.ait` is read with the artboard its header gives rather than
|
||||
// its bounding box, so it isn't read either. Bytes that don't read as an EPS file
|
||||
// leave it as a placed file without them: its preview, or an unread one.
|
||||
if !path.is_empty()
|
||||
&& !ai_named(&path)
|
||||
&& is_postscript(&eps)
|
||||
// A native document's artboard, rather than its bounding box, frames what the loader reads.
|
||||
&& !native_eps(&eps)
|
||||
&& crate::dcs::read(&eps).is_none()
|
||||
&& sane(b)
|
||||
&& b.width() > 0.0
|
||||
&& b.height() > 0.0
|
||||
&& eps_box(&eps).is_some()
|
||||
&& self.read_included(&eps) =>
|
||||
{
|
||||
let Some((placed, blob)) = self.placed_eps(m, path.clone(), eps, folder.clone(), hidden) else { return Ok(()) };
|
||||
if let Some((png, w, h)) = preview {
|
||||
// No image variable binds pattern or brush art, which a reader of its own
|
||||
// reads: there the placed document goes in at once.
|
||||
if self.pattern.is_some() {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
deferred = Some((placed, blob));
|
||||
(m, b, path, png, w, h, folder)
|
||||
} else {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
}
|
||||
Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => {
|
||||
(m, b, path, png, w, h, folder)
|
||||
}
|
||||
@@ -902,6 +1006,10 @@ impl<'a> Reader<'a> {
|
||||
.filter(|a| a.as_coeffs().iter().all(|v| v.is_finite()));
|
||||
let xf = self.space() * m * over_file;
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
// An included EPS file is still read when its preview can't be placed.
|
||||
if let Some((placed, blob)) = deferred {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
self.unreadable("placed files", hidden);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -911,7 +1019,11 @@ impl<'a> Reader<'a> {
|
||||
let key = linked_key(&blob, &path);
|
||||
let fresh = !self.doc.images.contains_key(&key);
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
self.warn(LINKED_PREVIEWS);
|
||||
// An included EPS file shows its preview only when an image variable binds it, which the
|
||||
// importer notes then.
|
||||
if deferred.is_none() {
|
||||
self.warn(LINKED_PREVIEWS);
|
||||
}
|
||||
let id = NodeId(self.doc.peek_next_id());
|
||||
if let Some(shift) = elsewhere
|
||||
&& self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE
|
||||
@@ -928,7 +1040,11 @@ impl<'a> Reader<'a> {
|
||||
self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth });
|
||||
let mut link = LinkInfo::new(path);
|
||||
link.relative = folder.and_then(|f| relative_path(&f, link.name()));
|
||||
self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)
|
||||
self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)?;
|
||||
if let Some((placed, blob)) = deferred {
|
||||
self.placed_eps.push(PlacedEps { id, placed, blob });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The dictionary `o` after the placed file just read: with a page or a box in it, that file is
|
||||
@@ -962,6 +1078,54 @@ impl<'a> Reader<'a> {
|
||||
self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size });
|
||||
}
|
||||
|
||||
/// The placed EPS file at `path` whose bytes `eps` the data includes, its box (in its own space,
|
||||
/// y up: the bounding box its comments give, [`eps_box`], which its art is read in) taken into
|
||||
/// art space by `m`: a placed document showing that box, which keeps the bytes and draws them
|
||||
/// whether or not its file is found. Its link has the size and hash of those bytes, so a file
|
||||
/// found unchanged isn't reported as modified. The placed document has no preview, so a save
|
||||
/// keeps the bytes. Not read without that box.
|
||||
fn placed_eps(&mut self, m: Affine, path: String, eps: Vec<u8>, folder: Option<String>, hidden: bool) -> Option<(PlacedDocument, ImageBlob)> {
|
||||
let Some(b) = eps_box(&eps) else {
|
||||
self.unreadable("placed files", hidden);
|
||||
return None;
|
||||
};
|
||||
// The placed document's box runs down from the file's top left corner.
|
||||
let xf = self.space() * m * Affine::new([1.0, 0.0, 0.0, -1.0, b.x0, b.y1]);
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
self.unreadable("placed files", hidden);
|
||||
return None;
|
||||
}
|
||||
let hash = hash_bytes(&eps);
|
||||
let key = key_for(&hash, 1, false, PageBox::Crop);
|
||||
let mut link = LinkInfo::new(path);
|
||||
link.relative = folder.and_then(|f| relative_path(&f, link.name()));
|
||||
(link.page, link.size, link.hash) = (Some(1), u64::try_from(eps.len()).ok(), Some(hash));
|
||||
let blob = ImageBlob { mime: EPS_MIME.into(), bytes: Arc::new(eps), proxy: None, file_font: Default::default() };
|
||||
let placed = PlacedDocument {
|
||||
link,
|
||||
key,
|
||||
bounding: false,
|
||||
page_box: PageBox::Crop,
|
||||
width: b.width(),
|
||||
height: b.height(),
|
||||
xf,
|
||||
placement: Default::default(),
|
||||
};
|
||||
Some((placed, blob))
|
||||
}
|
||||
|
||||
/// `placed` ([`Self::placed_eps`]) added as an object, its bytes `blob` kept under its key.
|
||||
/// Placements of the same bytes share one blob.
|
||||
fn add_placed_eps(&mut self, placed: PlacedDocument, blob: ImageBlob, hidden: bool) -> Result<(), String> {
|
||||
self.doc.images.entry(placed.key.clone()).or_insert(blob);
|
||||
let gs = self.gs.clone();
|
||||
let mut node = self.new_node(NodeKind::PlacedDocument(Box::new(placed)), &gs);
|
||||
node.opacity = gs.opacity;
|
||||
node.blend = gs.blend;
|
||||
node.knockout_shape = gs.knockout_shape;
|
||||
self.add(node, hidden)
|
||||
}
|
||||
|
||||
pub(super) fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) && self.warnings.len() < 64 {
|
||||
self.warnings.push(w.to_string());
|
||||
@@ -1083,6 +1247,65 @@ fn placed_crop(v: f64) -> Option<(bool, PageBox)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of a placed file the data includes (`doc`: between the `%%BeginDocument:` line and
|
||||
/// the `%%EndDocument` one), as the file has them: on `%_` lines (`hidden`) without the `%_` that
|
||||
/// starts each line, then without a line end the data adds before `%%EndDocument` after the file's
|
||||
/// own last one. A single line end at the end is the file's own. The line end added is `sep`, the
|
||||
/// one the data ends its `%%BeginDocument:` line with, when the bytes end with it; otherwise the
|
||||
/// last line end they end with. An LF `sep` after a CR isn't taken apart from it when the file's
|
||||
/// first line ends with CRLF: that CRLF is one line end of the file's.
|
||||
pub(super) fn included_document(doc: &[u8], hidden: bool, sep: Option<&[u8]>) -> Vec<u8> {
|
||||
let mut out = if hidden { unhidden(doc) } else { doc.to_vec() };
|
||||
let eol = |b: &[u8]| b.ends_with(b"\r") || b.ends_with(b"\n");
|
||||
let first_eol = out.iter().position(|&b| b == b'\r' || b == b'\n').and_then(|i| out.get(i..i + 2));
|
||||
let crlf_file = first_eol == Some(b"\r\n") && out.ends_with(b"\r\n");
|
||||
let added = sep
|
||||
.filter(|s| out.ends_with(s) && !(crlf_file && *s == b"\n"))
|
||||
.or_else(|| [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| out.ends_with(e)))
|
||||
.map(|e| out.len() - e.len());
|
||||
if let Some(n) = added.filter(|&n| out.get(..n).is_some_and(eol)) {
|
||||
out.truncate(n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bounding box an EPS file's comments give (`%%HiResBoundingBox` when it has one), in its
|
||||
/// own space; `None` without one, or when it is empty or out of range.
|
||||
fn eps_box(eps: &[u8]) -> Option<Rect> {
|
||||
let [x0, y0, x1, y1] = crate::import::bounding_box(eps)?;
|
||||
Some(Rect::new(x0, y0, x1, y1)).filter(|r| sane(*r) && r.width() > 0.0 && r.height() > 0.0)
|
||||
}
|
||||
|
||||
/// Does `eps` have a native document's begin comment line, without reading that document?
|
||||
fn native_eps(eps: &[u8]) -> bool {
|
||||
eps.split(|b| *b == b'\r' || *b == b'\n')
|
||||
.any(|line| line.strip_prefix(crate::BEGIN_DATA.as_bytes()).is_some_and(|name| name.trim_ascii() == crate::NATIVE.as_bytes()))
|
||||
}
|
||||
|
||||
/// Does the file name at the end of `path` (`/` or `\` separators) end in `.ai` or `.ait`, any case?
|
||||
fn ai_named(path: &str) -> bool {
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("ai") || ext.eq_ignore_ascii_case("ait"))
|
||||
}
|
||||
|
||||
/// `doc` without the `%_` that starts each of its lines.
|
||||
fn unhidden(doc: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(doc.len());
|
||||
let mut line_start = true;
|
||||
let mut i = 0;
|
||||
while let Some(&b) = doc.get(i) {
|
||||
if line_start && doc.get(i..i + 2) == Some(b"%_") {
|
||||
i += 2;
|
||||
line_start = false;
|
||||
continue;
|
||||
}
|
||||
out.push(b);
|
||||
line_start = b == b'\r' || b == b'\n';
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A placed file's path relative to the document's folder (`/` separators): its relative `folder`
|
||||
/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the
|
||||
/// document's own folder). `None` when the folder is absolute or holds control characters, or
|
||||
@@ -1155,3 +1378,36 @@ pub(crate) fn join_and(items: &[&str]) -> String {
|
||||
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ReadingEps, readable_eps};
|
||||
|
||||
/// Check results keep their warnings and failures, respect depth, and expire with the outer check.
|
||||
#[test]
|
||||
fn included_eps_checks_keep_the_depth_limit_and_expire() {
|
||||
let eps = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor 0 0 60 60 rectfill nosuchoperator\n%%EOF\n";
|
||||
{
|
||||
let _outer = ReadingEps::enter().unwrap();
|
||||
let warnings = readable_eps(eps).unwrap();
|
||||
assert!(!warnings.is_empty(), "a partly read file still passes, with warnings");
|
||||
let reads = crate::included_eps_reads();
|
||||
assert_eq!(readable_eps(eps).unwrap(), warnings);
|
||||
assert_eq!(crate::included_eps_reads(), reads, "the repeated check did not parse again");
|
||||
let limits: Vec<_> = std::iter::from_fn(ReadingEps::enter).collect();
|
||||
assert!(!limits.is_empty());
|
||||
assert!(readable_eps(eps).unwrap().is_empty(), "past the depth limit, warnings are not read");
|
||||
drop(limits);
|
||||
assert_eq!(readable_eps(eps).unwrap(), warnings, "the deeper check did not replace the cached warnings");
|
||||
let broken = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
assert!(readable_eps(broken).is_none());
|
||||
let reads = crate::included_eps_reads();
|
||||
assert!(readable_eps(broken).is_none());
|
||||
assert_eq!(crate::included_eps_reads(), reads, "a repeated failed check did not parse again");
|
||||
}
|
||||
let _outer = ReadingEps::enter().unwrap();
|
||||
let reads = crate::included_eps_reads();
|
||||
assert!(readable_eps(eps).is_some());
|
||||
assert!(crate::included_eps_reads() > reads, "the outer check's results were discarded");
|
||||
}
|
||||
}
|
||||
@@ -917,6 +917,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let Some(p) = self.envelopes.pop() else { return };
|
||||
let scale = self.space_scale();
|
||||
let pages = self.pages_in_doc();
|
||||
let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last());
|
||||
let Some(drawn) = drawn else {
|
||||
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
|
||||
@@ -959,8 +960,7 @@ impl<'a> Reader<'a> {
|
||||
(shown.visible, shown.opacity) = (true, 1.0);
|
||||
let mut plain = drawn.clone();
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
let page = self.page_in_doc();
|
||||
let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent);
|
||||
let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent);
|
||||
// In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked
|
||||
// again moved onto that art.
|
||||
if !alike
|
||||
@@ -969,7 +969,7 @@ impl<'a> Reader<'a> {
|
||||
{
|
||||
self.envelope_checks -= 1;
|
||||
(envelope.kind, shown.kind) = (kind.clone(), kind);
|
||||
alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent);
|
||||
alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent);
|
||||
}
|
||||
if !alike {
|
||||
self.warn(crate::import::ai::envelope::DRAWN);
|
||||
|
||||
@@ -55,6 +55,22 @@ impl AiArtboard {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pages the art may be compared with in the document's space, art space being moved there by
|
||||
/// `to_doc` (none before the art starts): each of `artboards` (else `first`, the first artboard),
|
||||
/// then `art_box`, the art's bounding box. A page that is an earlier one to half a point is left out.
|
||||
fn pages_of(to_doc: Option<Affine>, artboards: &[AiArtboard], first: Option<Rect>, art_box: Option<Rect>) -> Vec<Rect> {
|
||||
let Some(to_doc) = to_doc else { return vec![] };
|
||||
let boards: Vec<Rect> = if artboards.is_empty() { first.into_iter().collect() } else { artboards.iter().map(|b| b.rect).collect() };
|
||||
let mut pages: Vec<Rect> = vec![];
|
||||
for page in boards.into_iter().chain(art_box).map(|r| to_doc.transform_rect_bbox(r)) {
|
||||
let same = |p: &Rect| [p.x0 - page.x0, p.y0 - page.y0, p.x1 - page.x1, p.y1 - page.y1].iter().all(|d| d.abs() <= 0.5);
|
||||
if !pages.iter().any(same) {
|
||||
pages.push(page);
|
||||
}
|
||||
}
|
||||
pages
|
||||
}
|
||||
|
||||
/// The number of entry `key` in `o` when it is written as one finite number of the type `ty`
|
||||
/// (`/Int`, `/Real`, `/Bool`; a whole number unless `/Real`), else `None`.
|
||||
fn typed(o: &Obj, key: &str, ty: &str) -> Option<f64> {
|
||||
@@ -923,10 +939,21 @@ impl<'a> Reader<'a> {
|
||||
self.artboards.first().map(|b| b.rect).or(self.cropmarks).or_else(|| self.sized_board())
|
||||
}
|
||||
|
||||
/// The page the art is compared with in the document's space, once the art has started.
|
||||
pub(super) fn page_in_doc(&self) -> Option<Rect> {
|
||||
let board = self.first_board().or_else(|| self.bbox_board())?;
|
||||
Some(self.to_doc?.transform_rect_bbox(board))
|
||||
/// Every page the art may be compared with, in the document's space, once the art has started:
|
||||
/// each artboard (else the first artboard [`Self::first_board`] gives), since a page of a file's
|
||||
/// PDF part can show any of them, and the art's bounding box ([`Self::bbox_board`]), which a page
|
||||
/// cropped to the art and the page of the legacy format show ([`pages_of`]). Worked out again
|
||||
/// only when the artboards, the art's box or the move into the document have changed.
|
||||
pub(super) fn pages_in_doc(&mut self) -> Arc<[Rect]> {
|
||||
let sources = (self.to_doc, self.artboards.len(), self.first_board(), self.bbox_board());
|
||||
if let Some((from, pages)) = &self.page_cache
|
||||
&& *from == sources
|
||||
{
|
||||
return pages.clone();
|
||||
}
|
||||
let pages: Arc<[Rect]> = pages_of(sources.0, &self.artboards, sources.2, sources.3).into();
|
||||
self.page_cache = Some((sources, pages.clone()));
|
||||
pages
|
||||
}
|
||||
|
||||
/// The page of a file that says nothing of its artboard (the legacy format as other apps write
|
||||
@@ -1239,8 +1266,8 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let to_doc = self.ensure_space();
|
||||
let artboard = self.first_board();
|
||||
// Before the artboards are taken below: the page is the first artboard's.
|
||||
let page = self.page_in_doc();
|
||||
// Before the artboards are taken below: the pages are the artboards' and the art's box.
|
||||
let pages = self.pages_in_doc();
|
||||
self.check_symbols();
|
||||
self.order_symbols();
|
||||
drop_commented_copies(&mut self.doc.layers, &self.hidden_ids);
|
||||
@@ -1441,13 +1468,14 @@ impl<'a> Reader<'a> {
|
||||
placeholders: self.placeholders,
|
||||
placed_elsewhere: self.placed_elsewhere,
|
||||
placed_pages: self.placed_pages,
|
||||
placed_eps: self.placed_eps,
|
||||
envelopes_drawn: self.envelopes_drawn,
|
||||
warped_type: super::super::envelope::WarpedType {
|
||||
looks: self.warped_type,
|
||||
envelopes: self.typed_envelopes,
|
||||
checks: self.envelope_checks,
|
||||
spent: self.envelope_spent,
|
||||
page,
|
||||
pages: pages.to_vec(),
|
||||
alone: None,
|
||||
type_clips: self.type_clips,
|
||||
},
|
||||
|
||||
@@ -123,6 +123,18 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many paths and objects the records on this thread have measured.
|
||||
static MEASURED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// [`MEASURED`] of this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn on_path_measured() -> u64 {
|
||||
MEASURED.get()
|
||||
}
|
||||
|
||||
/// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record.
|
||||
pub(super) fn apply(doc: &mut Document, found: &OnPath) {
|
||||
if found.records.is_empty() {
|
||||
@@ -174,11 +186,15 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap<NodeId, Vec<usize>
|
||||
if !tried.insert(g.id) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
MEASURED.set(MEASURED.get() + 1);
|
||||
attachable_path(children.iter().find(|c| c.id == path)?)?;
|
||||
let mut members = Vec::with_capacity(placed.len());
|
||||
for (id, place, angle) in placed {
|
||||
// The frame the object is drawn in: turned by its angle (the document's y points down)
|
||||
// about the center of its bounds.
|
||||
#[cfg(test)]
|
||||
MEASURED.set(MEASURED.get() + 1);
|
||||
let center = doc.node_at(place)?.geometric_bounds()?.center();
|
||||
members.push(Member { id, frame: Affine::rotate_about(angle, center), angle });
|
||||
}
|
||||
|
||||
@@ -9,6 +9,29 @@ use super::{
|
||||
use vectorcraft_doc::{ArrowAlign, Arrowhead};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The operand stack slots that `[` and `]` have looked at on this thread, to find the open
|
||||
/// `[` or to take an array's items: their work.
|
||||
static ARRAY_SLOTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// The point-to-segment distances [`draws_look_outline`] has worked out on this thread.
|
||||
static OUTLINE_PAIRS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// [`ARRAY_SLOTS`] of this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn array_slots() -> u64 {
|
||||
ARRAY_SLOTS.get()
|
||||
}
|
||||
|
||||
/// Count `slots` that `[` or `]` looked at in [`ARRAY_SLOTS`]; nothing outside tests.
|
||||
fn array_slots_looked_at(slots: usize) {
|
||||
#[cfg(test)]
|
||||
ARRAY_SLOTS.set(ARRAY_SLOTS.get().saturating_add(u64::try_from(slots).unwrap_or(u64::MAX)));
|
||||
#[cfg(not(test))]
|
||||
let _ = slots;
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
// ---- operators -------------------------------------------------------------------------
|
||||
|
||||
@@ -16,11 +39,13 @@ impl<'a> Reader<'a> {
|
||||
// The innermost `[` still on the stack (the stack is cut back by operators).
|
||||
let mut at = self.stack.len();
|
||||
while let Some(m) = self.marks.pop() {
|
||||
array_slots_looked_at(1);
|
||||
if matches!(self.stack.get(m), Some(V::Mark)) {
|
||||
at = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
array_slots_looked_at(self.stack.len() - at);
|
||||
let items: Vec<V> = self.stack.split_off(at).into_iter().skip(1).collect();
|
||||
self.push(V::Arr(items))
|
||||
}
|
||||
@@ -172,6 +197,7 @@ impl<'a> Reader<'a> {
|
||||
"[" => {
|
||||
// Drop marks that operators have taken off, so `marks` is the open nesting.
|
||||
while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) {
|
||||
array_slots_looked_at(1);
|
||||
self.marks.pop();
|
||||
}
|
||||
// Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack.
|
||||
@@ -787,7 +813,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let space = self.space();
|
||||
self.note_brushes_kept();
|
||||
let page = self.page_in_doc();
|
||||
let pages = self.pages_in_doc();
|
||||
let Some(f) = self.frames.last_mut() else { return };
|
||||
let n = f.children.len();
|
||||
let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else {
|
||||
@@ -873,7 +899,8 @@ impl<'a> Reader<'a> {
|
||||
let layer = self.doc.alloc_id();
|
||||
let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images };
|
||||
let shown = !hidden && object.visible && look.visible;
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent)
|
||||
let on: &[Rect] = if shown { &pages } else { &[] };
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, on, &mut self.envelope_spent)
|
||||
};
|
||||
alike.then_some(ap)
|
||||
}
|
||||
@@ -885,7 +912,7 @@ impl<'a> Reader<'a> {
|
||||
let layer = self.doc.alloc_id();
|
||||
let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images };
|
||||
let mut spent = crate::import::ai::envelope::Spent::default();
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent)
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, &[], &mut spent)
|
||||
};
|
||||
alike.then_some(ap)
|
||||
}
|
||||
@@ -1314,7 +1341,7 @@ fn look_alike(
|
||||
hidden: bool,
|
||||
layer: NodeId,
|
||||
shared: &crate::import::ai::envelope::Shared<'_>,
|
||||
page: Option<Rect>,
|
||||
pages: &[Rect],
|
||||
spent: &mut crate::import::ai::envelope::Spent,
|
||||
) -> bool {
|
||||
let mut live = object.clone();
|
||||
@@ -1329,7 +1356,7 @@ fn look_alike(
|
||||
for n in [&mut live, &mut plain] {
|
||||
(n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal);
|
||||
}
|
||||
crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent)
|
||||
crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, pages, spent)
|
||||
}
|
||||
|
||||
/// Does `appearance` stroke with dashes aligned to corners and path ends?
|
||||
@@ -1635,7 +1662,13 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo
|
||||
/// projection onto it) is taken from `budget`: `false` once that runs out.
|
||||
fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
|
||||
let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT);
|
||||
let close = |p: kurbo::Point| {
|
||||
b.iter().any(|t| {
|
||||
#[cfg(test)]
|
||||
OUTLINE_PAIRS.set(OUTLINE_PAIRS.get() + 1);
|
||||
t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT
|
||||
})
|
||||
};
|
||||
for s in a {
|
||||
let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil();
|
||||
let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 };
|
||||
@@ -1658,7 +1691,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();
|
||||
@@ -2019,7 +2052,8 @@ mod tests {
|
||||
|
||||
/// The outline check works from one budget for the object: a look of the outline drawn twice
|
||||
/// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn
|
||||
/// look instead of comparing every copy.
|
||||
/// look instead of comparing every copy, having worked out no more distances than the budget
|
||||
/// holds.
|
||||
#[test]
|
||||
fn the_outline_check_has_one_budget_for_the_object() {
|
||||
let zig = vectorcraft_doc::Effect {
|
||||
@@ -2035,10 +2069,40 @@ mod tests {
|
||||
let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect();
|
||||
Node::group(NodeId(2), drawn)
|
||||
};
|
||||
assert!(draws_look_outline(&object, &appearance, &look(2)));
|
||||
let started = std::time::Instant::now();
|
||||
assert!(!draws_look_outline(&object, &appearance, &look(5_000)));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
// Whether the object draws `look`, and how many distances the check worked out.
|
||||
let check = |look: &Node| {
|
||||
let before = OUTLINE_PAIRS.get();
|
||||
let drawn = draws_look_outline(&object, &appearance, look);
|
||||
(drawn, OUTLINE_PAIRS.get() - before)
|
||||
};
|
||||
let (drawn, two) = check(&look(2));
|
||||
assert!(drawn);
|
||||
let (drawn, many) = check(&look(5_000));
|
||||
assert!(many <= u64::try_from(MAX_OUTLINE_PAIRS).unwrap(), "5,000 copies: {many} distances; 2 copies: {two}");
|
||||
assert!(!drawn);
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -312,6 +312,9 @@ pub(super) struct Place {
|
||||
pub(super) folder: Option<String>,
|
||||
/// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end.
|
||||
pub(super) folder_at: Option<usize>,
|
||||
/// The file's bytes, when the data includes them between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]).
|
||||
pub(super) document: Option<Vec<u8>>,
|
||||
/// Its `` ` `` was read.
|
||||
pub(super) ticked: bool,
|
||||
/// It began on a `%_` line, in a hidden object or on a layer that doesn't show.
|
||||
@@ -361,8 +364,26 @@ pub struct PlacedPage {
|
||||
pub size: (f64, f64),
|
||||
}
|
||||
|
||||
/// An included EPS whose linked preview becomes a placed document after variable binding.
|
||||
#[derive(Debug)]
|
||||
pub struct PlacedEps {
|
||||
/// The linked image.
|
||||
pub id: NodeId,
|
||||
/// The document that replaces the image unless an image variable binds it.
|
||||
pub placed: vectorcraft_doc::PlacedDocument,
|
||||
/// The EPS bytes stored under the placed document's key only when it replaces the image.
|
||||
pub blob: vectorcraft_doc::ImageBlob,
|
||||
}
|
||||
|
||||
/// The largest placed file kept from the bytes the data includes (the largest file File › Place
|
||||
/// reads).
|
||||
pub(super) const MAX_PLACED_DOCUMENT: usize = 256 << 20;
|
||||
|
||||
/// The type a placed EPS file's bytes are stored with.
|
||||
pub(super) const EPS_MIME: &str = "application/postscript";
|
||||
|
||||
/// What the open result says of placed files: they show the preview the file keeps of them.
|
||||
pub(super) const LINKED_PREVIEWS: &str =
|
||||
pub(crate) const LINKED_PREVIEWS: &str =
|
||||
"linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel";
|
||||
|
||||
/// What the open result says of linked images the data keeps no pixels of (`XF`): they show a
|
||||
|
||||
@@ -12,7 +12,9 @@ use super::*;
|
||||
|
||||
/// [`super::read`] as an EPS reads it.
|
||||
fn read(data: &[u8]) -> Result<Structure, String> {
|
||||
super::read(data, true)
|
||||
let mut r = super::read(data, true)?;
|
||||
super::super::native::placed_documents(&mut r.doc, &[], &r.placed_eps);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Editing data: header comments (crop marks 0 0 200 100), then `body`.
|
||||
@@ -3495,6 +3497,178 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() {
|
||||
assert_eq!(relative_of(&cut), None);
|
||||
}
|
||||
|
||||
/// An EPS file of `w` × `h` points filled red, its lines ended by `eol`.
|
||||
fn red_eps(w: u32, h: u32, eol: &str) -> Vec<u8> {
|
||||
format!("%!PS-Adobe-3.0 EPSF-3.0{eol}%%BoundingBox: 0 0 {w} {h}{eol}%%EndComments{eol}1 0 0 setrgbcolor{eol}0 0 {w} {h} rectfill{eol}%%EOF{eol}")
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// `data` with the first `from` in it replaced by `to`.
|
||||
fn splice(data: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
|
||||
let at = data.windows(from.len()).position(|w| w == from).unwrap();
|
||||
[&data[..at], to, &data[at + from.len()..]].concat()
|
||||
}
|
||||
|
||||
/// [`placed`]'s file with the placed file `/old/place/src/shape.eps` in the box 0 0 80 50, in the
|
||||
/// folder `src/`, without a preview, and `doc` included between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` in place of `%%IncludeFile:` (`%%FileType: 0`).
|
||||
fn placed_eps_file(doc: &[u8]) -> Vec<u8> {
|
||||
let data = placed(true, "[5 0 0 -5 0 200]", "/old/place/src/shape.eps", None, "");
|
||||
let data = splice(&data, b"10 20 14 22 4 4 0", b"0 0 80 50 4 4 0");
|
||||
let data = splice(&data, b"\r()\r", b"\r(src/)\r");
|
||||
let data = splice(&data, b"%%FileType: 1", b"%%FileType: 0");
|
||||
let included = [&b"%%BeginDocument: /old/place/src/shape.eps\r"[..], doc, b"\r%%EndDocument\r"].concat();
|
||||
splice(&data, b"%%IncludeFile:/old/place/src/shape.eps\r", &included)
|
||||
}
|
||||
|
||||
/// The one placed document of `data`, with the blob its key names.
|
||||
fn one_placed(data: &[u8]) -> (Node, vectorcraft_doc::PlacedDocument, vectorcraft_doc::ImageBlob, Structure) {
|
||||
let r = read(data).unwrap();
|
||||
let a = art(&r.doc);
|
||||
let [n] = &a[..] else { panic!("one object: {a:?}") };
|
||||
let NodeKind::PlacedDocument(p) = &n.kind else { panic!("a placed document: {:?}", n.kind) };
|
||||
let blob = r.doc.images[&p.key].clone();
|
||||
((**n).clone(), (**p).clone(), blob, r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_whose_bytes_the_data_includes_is_a_placed_document_of_them() {
|
||||
let eps = red_eps(80, 50, "\n");
|
||||
let (_, p, blob, r) = one_placed(&placed_eps_file(&eps));
|
||||
assert_eq!(*blob.bytes, eps, "the file's own bytes, without the line end the data adds");
|
||||
assert_eq!((blob.mime.as_str(), blob.proxy.is_none()), ("application/postscript", true));
|
||||
assert_eq!((p.link.path.as_str(), p.link.relative.as_deref()), ("/old/place/src/shape.eps", Some("src/shape.eps")));
|
||||
assert_eq!((p.link.page, p.link.size, p.link.hash.clone()), (Some(1), Some(eps.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&eps))));
|
||||
assert_eq!((p.width, p.height, p.bounding, p.page_box), (80.0, 50.0, false, vectorcraft_doc::PageBox::Crop));
|
||||
assert!(r.unread.is_empty() && r.hidden_unread.is_empty() && r.unread_elsewhere.is_empty(), "{:?}", r.unread);
|
||||
assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{:?}", r.warnings);
|
||||
// The matrix takes the file's own space (y up) into art space; the box's top left corner is the
|
||||
// file's (0, 50).
|
||||
let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]);
|
||||
for (corner, file) in [((0.0, 0.0), (0.0, 50.0)), ((80.0, 50.0), (80.0, 0.0)), ((80.0, 0.0), (80.0, 50.0))] {
|
||||
let (got, want) = (p.xf * Point::from(corner), r.to_doc * m * Point::from(file));
|
||||
assert!((got - want).hypot() < 1e-9, "{corner:?}: {got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_with_included_bytes_and_a_preview_keeps_only_the_bytes() {
|
||||
let eps = red_eps(80, 50, "\n");
|
||||
let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat();
|
||||
let section =
|
||||
[&b"%AI17_Begin_Content_if_version_gt:24 5\r%AI26_BeginPlacedObjectPreview\r"[..], &preview, b"\r%AI26_EndPlacedObjectPreview\r"].concat();
|
||||
let data = splice(&placed_eps_file(&eps), b"%AI17_Begin_Content_if_version_gt:24 5\r", §ion);
|
||||
// The placed document has no preview, so a save keeps its bytes.
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!((&*blob.bytes, blob.proxy.is_none()), (&eps, true));
|
||||
// The same bytes placed twice share the blob.
|
||||
let one = placed_eps_file(&eps);
|
||||
let (from, to) = (|d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(), b"%AI5_EndPlace\r");
|
||||
let first = &one[from(&one, b"%AI5_BeginPlace")..from(&one, to) + to.len()];
|
||||
let twice = splice(&data, b"%AI5_BeginPlace", &[first, b"%AI5_BeginPlace"].concat());
|
||||
let r = read(&twice).unwrap();
|
||||
let a = art(&r.doc);
|
||||
let keys: Vec<_> = a.iter().filter_map(|n| if let NodeKind::PlacedDocument(p) = &n.kind { Some(p.key.clone()) } else { None }).collect();
|
||||
assert!(keys.len() == 2 && keys[0] == keys[1], "{keys:?}");
|
||||
assert!(r.doc.images[&keys[0]].proxy.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_files_box_is_its_high_resolution_bounding_box() {
|
||||
let eps = splice(&red_eps(80, 50, "\n"), b"%%EndComments", b"%%HiResBoundingBox: 0.5 0.5 79.5 49.5\n%%EndComments");
|
||||
let (_, p, _, r) = one_placed(&placed_eps_file(&eps));
|
||||
assert_eq!((p.width, p.height), (79.0, 49.0));
|
||||
// The box's top left corner is the file's (0.5, 49.5), where the matrix puts it.
|
||||
let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]);
|
||||
let (got, want) = (p.xf * Point::ZERO, r.to_doc * m * Point::new(0.5, 49.5));
|
||||
assert!((got - want).hypot() < 1e-9, "{got:?} {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_files_box_with_its_corners_reversed_leaves_it_unread() {
|
||||
let data = splice(&placed_eps_file(&red_eps(80, 50, "\n")), b"0 0 80 50 4 4 0", b"80 50 0 0 4 4 0");
|
||||
let r = read(&data).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_included_eps_files_own_last_line_end_is_kept() {
|
||||
// The data's line end after the file's own is taken off; a single one is the file's.
|
||||
let (lf, crlf) = ("%!PS\n%%BoundingBox: 0 0 80 50\n%%EOF\n", "%!PS\r\n%%BoundingBox: 0 0 80 50\r\n%%EOF\r\n");
|
||||
for (eps, written) in [(lf, format!("{lf}\r")), (lf, lf.to_string()), (crlf, format!("{crlf}\r\n"))] {
|
||||
let data = splice(&placed_eps_file(b"%!@@"), b"%!@@\r%%EndDocument", format!("{written}%%EndDocument").as_bytes());
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), eps, "{written:?}");
|
||||
}
|
||||
// The line end added is the one the `%%BeginDocument:` line ends with: an LF after a file whose
|
||||
// lines end with CR isn't read as a CRLF of the file's.
|
||||
let data =
|
||||
splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", b"shape.eps\n%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r\n%%EndDocument");
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), "%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r");
|
||||
// A file whose lines end with CRLF, included as it is after an LF: its last CRLF is its own.
|
||||
let data = splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", format!("shape.eps\n{crlf}%%EndDocument").as_bytes());
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), crlf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_on_commented_lines_keeps_its_bytes() {
|
||||
let eps = red_eps(80, 50, "\r");
|
||||
let hidden = hide_placed(&placed_eps_file(&eps));
|
||||
let (_, _, blob, _) = one_placed(&hidden);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the `%_` that starts each line taken off");
|
||||
// The line end added before `%%EndDocument` on a `%_` line of its own.
|
||||
let (_, _, blob, _) = one_placed(&splice(&hidden, b"%%EOF\r\r%_%%EndDocument", b"%%EOF\r%_\r%_%%EndDocument"));
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the added line end taken off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_included_postscript_file_named_as_an_ai_file_stays_unread() {
|
||||
// Read through its name with the artboard its header gives, not the box the placed one shows.
|
||||
for name in ["shape.ai", "SHAPE.AIT"] {
|
||||
let mut data = placed_eps_file(&red_eps(80, 50, "\n"));
|
||||
while data.windows(9).any(|w| w == b"shape.eps") {
|
||||
data = splice(&data, b"shape.eps", name.as_bytes());
|
||||
}
|
||||
let r = read(&data).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{name}: {:?}", art(&r.doc));
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{name}: {:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_eps_with_a_native_document_leaves_the_placed_file_unread() {
|
||||
// Even unreadable native data leaves the file unread: the loader can read an artboard
|
||||
// larger than the EPS bounding box, which would shrink and offset the art when placed.
|
||||
for eol in ["\n", "\r", "\r\n"] {
|
||||
let section = format!("%VectorCraft_BeginData: native \t{eol}%unreadable native data{eol}%VectorCraft_EndData{eol}%%EOF");
|
||||
let eps = splice(&red_eps(80, 50, eol), b"%%EOF", section.as_bytes());
|
||||
let r = read(&placed_eps_file(&eps)).unwrap();
|
||||
assert!(
|
||||
!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))),
|
||||
"included EPS with a native document must stay on the fallback path"
|
||||
);
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_bytes_that_arent_an_eps_file_leave_the_placed_file_unread() {
|
||||
// A DCS file, which the placed document reader doesn't read (File › Place makes it a linked
|
||||
// image), stays unread too.
|
||||
let dcs = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%PlateFile: (Black) EPS Local pic.K\n%%EndComments\n%%EOF\n";
|
||||
// An EPS file without a bounding box, whose art is read on a page of another size, stays unread.
|
||||
let boxless = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n1 0 0 setrgbcolor\n0 0 80 50 rectfill\n%%EOF\n";
|
||||
// An EPS file whose program doesn't read draws nothing, so it stays unread too.
|
||||
let broken = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 80 50\n%%EndComments\n0 0 80 50 nosuchoperator\n%%EOF\n";
|
||||
for bytes in [&b"hello\rworld"[..], dcs, boxless, broken] {
|
||||
let r = read(&placed_eps_file(bytes)).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc));
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_placed_file_ended_by_comment_stays_hidden() {
|
||||
let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, ""));
|
||||
@@ -3588,6 +3762,7 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> {
|
||||
NodeKind::Group { .. } => "group",
|
||||
NodeKind::Path { .. } => "path",
|
||||
NodeKind::Image(_) => "image",
|
||||
NodeKind::PlacedDocument(_) => "placed",
|
||||
_ => "other",
|
||||
})
|
||||
.collect()
|
||||
@@ -3596,13 +3771,16 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> {
|
||||
#[test]
|
||||
fn version7_placed_file_included_whole_is_read() {
|
||||
// The included document's operators, a `~`, a nested document and counted data in it aren't
|
||||
// the editing data's.
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\
|
||||
// the editing data's (the file defines them, so its program reads).
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n/frobnicate {} def /~ {} def\n1 0 0 setrgbcolor frobnicate ~\n\
|
||||
%%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n";
|
||||
let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n");
|
||||
let r = placed_read7(true, &body).unwrap();
|
||||
assert_eq!(art_kinds(&r.doc), ["path"]);
|
||||
assert_unread(&r, "placed files");
|
||||
// A placed document of the file's bytes.
|
||||
assert_eq!(art_kinds(&r.doc), ["placed"]);
|
||||
let NodeKind::PlacedDocument(p) = &art(&r.doc)[0].kind else { panic!() };
|
||||
assert_eq!(r.doc.images[&p.key].bytes.as_slice(), eps.as_bytes());
|
||||
assert!(r.unread.is_empty(), "{:?}", r.unread);
|
||||
// One that doesn't end leaves the layer without its end.
|
||||
let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n");
|
||||
assert!(placed_read7(true, &cut).is_err());
|
||||
@@ -6440,13 +6618,16 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds
|
||||
/// of thousands of them look at no more than four slots each.
|
||||
#[test]
|
||||
fn closing_brackets_without_their_opening_dont_rescan_the_stack() {
|
||||
let n = 200_000;
|
||||
let body = format!("{}\n{}\n", "1 ".repeat(n), "] ".repeat(n));
|
||||
let started = std::time::Instant::now();
|
||||
let before = read::array_slots();
|
||||
let _ = read(stream(&layer(&body)).as_bytes());
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
|
||||
let slots = read::array_slots() - before;
|
||||
assert!(slots <= 4 * u64::try_from(n).unwrap(), "{n} brackets looked at {slots} slots");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9042,7 +9223,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 +9264,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:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9356,24 +9576,35 @@ fn warped_type_gets_what_the_envelopes_left_of_the_budget() {
|
||||
let exact = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat))));
|
||||
let beside = format!("{RED}{}f\n", rect_path(40.5, 20.0, 160.5, 80.0));
|
||||
let shifted = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &beside)));
|
||||
let page = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
for r in [&exact, &shifted] {
|
||||
assert_eq!(r.warped_type.checks, super::envelope::MAX_CHECKED - 1);
|
||||
assert!(r.warped_type.page.is_some());
|
||||
assert_eq!(r.warped_type.pages, [page]);
|
||||
}
|
||||
live_envelope(&art(&shifted.doc)[0]);
|
||||
assert!(shifted.warped_type.spent.any > exact.warped_type.spent.any);
|
||||
assert!(shifted.warped_type.spent.on(page).0 > exact.warped_type.spent.on(page).0);
|
||||
}
|
||||
|
||||
/// In a file with an artboard list, warped type is held to the first artboard, not to the crop marks.
|
||||
/// In a file with an artboard list, warped type is held to every artboard, not to the crop marks.
|
||||
#[test]
|
||||
fn warped_type_is_held_to_the_first_artboard() {
|
||||
fn warped_type_is_held_to_every_artboard() {
|
||||
let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\
|
||||
%_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\
|
||||
%_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_; ,\n\
|
||||
%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n";
|
||||
let r = read_ok(&format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0)))));
|
||||
assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 300.0, 200.0));
|
||||
assert_eq!(r.warped_type.page, Some(Rect::new(0.0, 0.0, 300.0, 200.0)));
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 300.0, 200.0), Rect::new(400.0, 200.0, 600.0, 350.0)]);
|
||||
}
|
||||
|
||||
/// Artboards that are an earlier one to half a point, and an art box that is one of them, add no
|
||||
/// page of their own.
|
||||
#[test]
|
||||
fn pages_that_repeat_an_artboard_are_held_once() {
|
||||
let boards = boards_at(&[[0.0, 0.0, 200.0, 100.0], [0.2, 0.0, 200.0, 100.3], [0.0, 0.0, 200.0, 100.0], [300.0, 0.0, 400.0, 100.0]]);
|
||||
let data = format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0))));
|
||||
let r = read(stream_with_header("%%HiResBoundingBox: 300 0 400 100.4\n", &data).as_bytes()).unwrap();
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 200.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0)]);
|
||||
}
|
||||
|
||||
/// Type whose Warp is hidden draws no warp, so it stays type even with no check left.
|
||||
@@ -9415,17 +9646,39 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() {
|
||||
w.look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10 - i as u64), vec![Arc::new(w.look.clone()), mark.clone()]);
|
||||
}
|
||||
let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None };
|
||||
let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0));
|
||||
let page = Rect::new(0.0, 60.0, 60.0, 100.0);
|
||||
let settle = |w: &super::envelope::WarpedLook, spent| {
|
||||
let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() };
|
||||
let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, pages: vec![page], ..Default::default() };
|
||||
warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![])
|
||||
};
|
||||
let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 };
|
||||
let spent = || super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() };
|
||||
assert_eq!(settle(&looks[1], Default::default()), 0);
|
||||
assert_eq!(settle(&looks[1], spent()), 1);
|
||||
assert_eq!(settle(&looks[0], spent()), 0);
|
||||
}
|
||||
|
||||
/// Each page the art may be compared with has its own share of the budget: warped type on the
|
||||
/// second page spends that page's share, whatever is left of the first page's.
|
||||
#[test]
|
||||
fn warped_type_on_a_later_page_spends_that_pages_share_of_the_budget() {
|
||||
use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE};
|
||||
let (doc, mut looks) = warped_type_doc(2);
|
||||
// The second object shows. Its look draws a little more than it.
|
||||
let mark = read_ok(&layer(&format!("{RED}{}f\n", rect_path(2.0, 2.0, 2.6, 2.6))));
|
||||
let mark = art(&mark.doc)[0].clone();
|
||||
let w = looks.remove(1);
|
||||
let look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10), vec![Arc::new(w.look.clone()), mark]);
|
||||
let (first, second) = (Rect::new(200.0, 0.0, 260.0, 40.0), Rect::new(0.0, 60.0, 60.0, 100.0));
|
||||
let settle = |spent| {
|
||||
let looks = vec![super::envelope::WarpedLook { slot: w.slot, look: look.clone(), left_out: None }];
|
||||
let warped = super::envelope::WarpedType { looks, checks: 1, spent, pages: vec![first, second], ..Default::default() };
|
||||
warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![])
|
||||
};
|
||||
let full = |page| super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() };
|
||||
assert_eq!(settle(full(first)), 0);
|
||||
assert_eq!(settle(full(second)), 1);
|
||||
}
|
||||
|
||||
/// An envelope that comes out close to its drawn art, but with more of the page differing than the
|
||||
/// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100
|
||||
/// page), keeps the drawn art, so the file still opens from its layers.
|
||||
@@ -9440,6 +9693,58 @@ fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() {
|
||||
assert_eq!(r.warnings, [super::envelope::DRAWN]);
|
||||
}
|
||||
|
||||
/// The document data of artboards in art space, each `[x0, y0, x1, y1]`.
|
||||
fn boards_at(boards: &[[f64; 4]]) -> String {
|
||||
let boards: String = boards
|
||||
.iter()
|
||||
.map(|[x0, y0, x1, y1]| {
|
||||
format!("%_/Dictionary :\n%_{x0} {y1} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{x1} {y0} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n")
|
||||
})
|
||||
.collect();
|
||||
format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n")
|
||||
}
|
||||
|
||||
/// The envelope of [`an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it`] on the
|
||||
/// second artboard, the first a strip along the top that it doesn't reach: a page of the second
|
||||
/// artboard can be compared with the layers, so it is held to that page and keeps its drawn art.
|
||||
/// One that draws as its drawn art opens live there.
|
||||
#[test]
|
||||
fn an_envelope_on_a_later_artboard_that_differs_over_its_page_keeps_its_drawn_art() {
|
||||
let boards = boards_at(&[[0.0, 98.0, 20.0, 100.0], [0.0, 0.0, 200.0, 100.0]]);
|
||||
let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0));
|
||||
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted);
|
||||
let r = read_ok(&format!("{boards}{}", layer(&body)));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}");
|
||||
assert_eq!(r.warnings, [super::envelope::DRAWN]);
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]);
|
||||
let flat = vectorcraft_doc::live::EnvelopeKind::Mesh {
|
||||
rows: 1,
|
||||
cols: 1,
|
||||
points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)],
|
||||
handles: vec![],
|
||||
};
|
||||
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat));
|
||||
let r = read_ok(&format!("{boards}{}", layer(&body)));
|
||||
live_envelope(&art(&r.doc)[0]);
|
||||
}
|
||||
|
||||
/// The same envelope on no artboard, inside the art's bounding box: a page cropped to the art
|
||||
/// shows it, so it is held to that page too.
|
||||
#[test]
|
||||
fn an_envelope_off_the_artboards_that_differs_over_the_arts_box_keeps_its_drawn_art() {
|
||||
let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0));
|
||||
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted);
|
||||
let data = format!("{}{}", boards_at(&[[0.0, 98.0, 20.0, 100.0]]), layer(&body));
|
||||
let r = read(stream_with_header("%%HiResBoundingBox: 0 0 200 100\n", &data).as_bytes()).unwrap();
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}");
|
||||
assert_eq!(r.warnings, [super::envelope::DRAWN]);
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]);
|
||||
}
|
||||
|
||||
/// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which
|
||||
/// the page's art replaces.
|
||||
#[test]
|
||||
@@ -10794,9 +11099,9 @@ fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() {
|
||||
}
|
||||
|
||||
/// The path and objects of a group are measured once however many records name it: a thousand
|
||||
/// copies of a record open about as fast as one copy followed by 999 records whose path id is
|
||||
/// missing, when the group opens live, when its long path has no length, and when its first object
|
||||
/// is a group of many paths and its last object has no bounds.
|
||||
/// copies of a record measure as many paths and objects as one copy followed by 999 records whose
|
||||
/// path id is missing, when the group opens live, when its long path has no length, and when its
|
||||
/// first object is a group of many paths and its last object has no bounds.
|
||||
#[test]
|
||||
fn repeated_objects_on_path_records_dont_measure_the_objects_again() {
|
||||
use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record};
|
||||
@@ -10821,23 +11126,18 @@ fn repeated_objects_on_path_records_dont_measure_the_objects_again() {
|
||||
let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000");
|
||||
let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]);
|
||||
let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]);
|
||||
let time = |data: &str| {
|
||||
let started = std::time::Instant::now();
|
||||
let measure = |data: &str| {
|
||||
let before = read::on_path_measured();
|
||||
let doc = read_ok(&format!("{data}{}", layer(&group))).doc;
|
||||
let elapsed = started.elapsed();
|
||||
let measured = read::on_path_measured() - before;
|
||||
let g = art(&doc)[0].clone();
|
||||
assert_eq!(g.children().unwrap().len(), n, "{why}");
|
||||
assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}");
|
||||
elapsed
|
||||
measured
|
||||
};
|
||||
// The fastest of three runs each, taken in turn, so that other tests running at the same
|
||||
// time weigh on both.
|
||||
let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX);
|
||||
for _ in 0..3 {
|
||||
fastest_one = fastest_one.min(time(&one));
|
||||
fastest_many = fastest_many.min(time(&many));
|
||||
}
|
||||
assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}");
|
||||
let (measured_one, measured_many) = (measure(&one), measure(&many));
|
||||
assert!(measured_one > 0, "{why}");
|
||||
assert_eq!(measured_many, measured_one, "{why}: 1000 copies measured {measured_many} times, one copy {measured_one}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,12 @@ struct Gathered {
|
||||
chars: HashMap<char, usize>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread.
|
||||
static COMPARED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl FileFontGlyphs {
|
||||
/// The font of `family` and `style` (made with `info` the first time): its index.
|
||||
pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize {
|
||||
@@ -59,6 +65,10 @@ impl FileFontGlyphs {
|
||||
let mut new: HashMap<char, &FileGlyph> = HashMap::new();
|
||||
for g in glyphs {
|
||||
let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied());
|
||||
#[cfg(test)]
|
||||
if kept.is_some() {
|
||||
COMPARED.set(COMPARED.get() + 1);
|
||||
}
|
||||
match kept {
|
||||
Some(k) if k.outline != g.outline || k.advance != g.advance => return false,
|
||||
Some(_) => {}
|
||||
@@ -178,15 +188,16 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A long string of one character compares each glyph with that character's once, not with
|
||||
/// every one before it: a quarter of a million of them fit at once.
|
||||
/// every one before it: a quarter of a million of them fit at once, with fewer comparisons
|
||||
/// than glyphs.
|
||||
#[test]
|
||||
fn a_long_string_of_one_character_fits_in_linear_time() {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut g = FileFontGlyphs::default();
|
||||
let f = g.font("F", "Regular", FileFontInfo::default);
|
||||
tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok();
|
||||
});
|
||||
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true));
|
||||
let n = 250_000;
|
||||
let mut g = FileFontGlyphs::default();
|
||||
let f = g.font("F", "Regular", FileFontInfo::default);
|
||||
let before = COMPARED.get();
|
||||
assert!(g.fits(f, &vec![glyph('A'); n]));
|
||||
let compared = COMPARED.get() - before;
|
||||
assert!(compared < u64::try_from(n).unwrap(), "{n} glyphs: {compared} comparisons");
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ mod slots;
|
||||
#[cfg(test)]
|
||||
pub(crate) use build::READ_AFRESH;
|
||||
#[cfg(test)]
|
||||
pub(super) use build::placed_documents;
|
||||
#[cfg(test)]
|
||||
use build::{Frame, MADE, prune_unseen};
|
||||
pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -334,6 +334,7 @@ pub(super) fn build_weighing(
|
||||
placeholders,
|
||||
placed_elsewhere,
|
||||
placed_pages,
|
||||
placed_eps,
|
||||
envelopes_drawn,
|
||||
styles_read,
|
||||
text_paints,
|
||||
@@ -644,33 +645,50 @@ pub(super) fn build_weighing(
|
||||
}
|
||||
doc.limit_depth_noting(&mut notes);
|
||||
bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes);
|
||||
placed_documents(&mut doc, &placed_pages);
|
||||
if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) {
|
||||
notes.push(ai::LINKED_PREVIEWS.to_string());
|
||||
}
|
||||
if small.is_some() {
|
||||
scale_read_document(&mut doc, unit, styles_read, symbols_own_size);
|
||||
}
|
||||
Ok((doc, notes))
|
||||
}
|
||||
|
||||
/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed
|
||||
/// documents of their page and box, over the same place, each showing the same preview until its
|
||||
/// file is read. An image bound to an image variable stays a linked image, the object an image
|
||||
/// variable binds.
|
||||
fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) {
|
||||
if pages.is_empty() {
|
||||
return;
|
||||
/// The linked images of `pages` and included `eps` still in `doc`, opacity-mask art included, as placed
|
||||
/// documents of their page and box. PDF pages keep their previews, and EPS files keep their included
|
||||
/// bytes. An image bound to an image variable stays a linked image, the object an image variable binds.
|
||||
/// Returns whether an included EPS file stays a linked image that way, showing its preview.
|
||||
pub(in crate::import) fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage], eps: &[ai::PlacedEps]) -> bool {
|
||||
if pages.is_empty() && eps.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let vars = &doc.variables;
|
||||
let image_bound = |id: &NodeId| {
|
||||
vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image)))
|
||||
};
|
||||
let pages: std::collections::HashMap<NodeId, ai::PlacedPage> = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect();
|
||||
let previews = eps.iter().any(|p| image_bound(&p.id));
|
||||
let eps: std::collections::HashMap<NodeId, &ai::PlacedEps> = eps.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, p)).collect();
|
||||
for layer in &mut doc.layers {
|
||||
to_placed_documents(Arc::make_mut(layer), &pages);
|
||||
to_placed_documents(Arc::make_mut(layer), &pages, &eps, &mut doc.images);
|
||||
}
|
||||
previews
|
||||
}
|
||||
|
||||
/// [`placed_documents`] in `n` and everything in it.
|
||||
fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap<NodeId, ai::PlacedPage>) {
|
||||
fn to_placed_documents(
|
||||
n: &mut Node,
|
||||
pages: &std::collections::HashMap<NodeId, ai::PlacedPage>,
|
||||
eps: &std::collections::HashMap<NodeId, &ai::PlacedEps>,
|
||||
images: &mut std::collections::BTreeMap<String, vectorcraft_doc::ImageBlob>,
|
||||
) {
|
||||
if let Some(eps) = eps.get(&n.id)
|
||||
&& let NodeKind::Image(im) = &n.kind
|
||||
&& im.link.is_some()
|
||||
{
|
||||
images.entry(eps.placed.key.clone()).or_insert_with(|| eps.blob.clone());
|
||||
n.kind = NodeKind::PlacedDocument(Box::new(eps.placed.clone()));
|
||||
}
|
||||
// A box too small to take the image's pixels to (its transform not finite) keeps the linked image.
|
||||
if let Some(page) = pages.get(&n.id)
|
||||
&& let NodeKind::Image(im) = &n.kind
|
||||
@@ -694,10 +712,10 @@ fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap<NodeId, a
|
||||
n.kind = NodeKind::PlacedDocument(Box::new(placed));
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
to_placed_documents(Arc::make_mut(&mut m.art), pages);
|
||||
to_placed_documents(Arc::make_mut(&mut m.art), pages, eps, images);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
to_placed_documents(Arc::make_mut(c), pages);
|
||||
to_placed_documents(Arc::make_mut(c), pages, eps, images);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1905,11 +1923,12 @@ fn outside_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(N
|
||||
}
|
||||
|
||||
/// Where the placed files that show in `nodes` are: the linked images the editing data's reader
|
||||
/// makes of them.
|
||||
/// makes of them, and the placed documents it makes of the EPS files whose bytes it includes.
|
||||
fn placed_files(nodes: &[Arc<Node>], out: &mut Vec<Rect>) {
|
||||
for n in nodes.iter().filter(|n| n.visible) {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()),
|
||||
NodeKind::PlacedDocument(_) => out.extend(n.visual_bounds()),
|
||||
_ => {
|
||||
if let Some(c) = n.children() {
|
||||
placed_files(c, out);
|
||||
|
||||
@@ -56,6 +56,19 @@ fn tree(nodes: &[Arc<Node>]) -> String {
|
||||
nodes.iter().map(one).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Placed EPS files drawn as the app draws them: the art of the file read as it opens, in its
|
||||
/// bounding box (the engine registers the app's own loader).
|
||||
fn draw_placed_eps() {
|
||||
fn load(_: &vectorcraft_doc::PlacedDocument, bytes: &[u8]) -> Option<(vectorcraft_doc::Document, Node, Rect)> {
|
||||
let mut doc = import(bytes).ok()?.document;
|
||||
let frame = doc.artboards.first()?.rect;
|
||||
let layers = std::mem::take(&mut doc.layers);
|
||||
let children = layers.iter().flat_map(|l| l.children().map(|c| c.to_vec()).unwrap_or_default()).collect();
|
||||
Some((doc, Node::new(vectorcraft_doc::NodeId(0), NodeKind::Group { children, clip: false }), frame))
|
||||
}
|
||||
vectorcraft_doc::placed_document::set_loader(load);
|
||||
}
|
||||
|
||||
fn read(header: &str, ugroup: &str, body: &str) -> (String, Vec<String>) {
|
||||
let r = import(&ai(header, ugroup, body)).unwrap();
|
||||
(tree(r.document.layers[0].children().unwrap()), r.warnings)
|
||||
@@ -424,9 +437,10 @@ fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboar
|
||||
}
|
||||
|
||||
/// A placed EPS in the legacy format (version 7 specification §16, no `%AI5_BeginPlace`), its file
|
||||
/// included whole: the layers come in, the placed file as the art the page draws in its box.
|
||||
/// included whole: the layers come in, the placed file as a placed document of its bytes in its box.
|
||||
#[test]
|
||||
fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
|
||||
draw_placed_eps();
|
||||
// `` ` `` takes the file's user space into the page's (`concat`); `~` restores it.
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\
|
||||
/` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
@@ -440,14 +454,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
|
||||
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Back"], "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert_eq!(tree(art), "p g[p]", "{:?}", r.warnings);
|
||||
let NodeKind::PlacedDocument(p) = &art[1].kind else { panic!("{}: {:?}", tree(art), r.warnings) };
|
||||
assert_eq!(r.document.images[&p.key].bytes.as_slice(), eps.as_bytes(), "the file's bytes");
|
||||
assert_eq!(p.link.path, "art.eps");
|
||||
// The file's box, moved by the matrix: 20 40 60 70 on the page, y up.
|
||||
let bounds = art[1].geometric_bounds().unwrap();
|
||||
assert!(
|
||||
(bounds.x0 - 20.0).abs() < 0.01 && (bounds.y0 - 30.0).abs() < 0.01 && (bounds.x1 - 60.0).abs() < 0.01 && (bounds.y1 - 60.0).abs() < 0.01,
|
||||
"{bounds:?}"
|
||||
);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A legacy file whose placed EPS file, included whole, has type: the page's type is the placed
|
||||
/// file's, so the layers come in with it as a placed document.
|
||||
#[test]
|
||||
fn a_legacy_file_with_a_placed_eps_with_type_comes_in_through_its_layers() {
|
||||
draw_placed_eps();
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\
|
||||
/` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\
|
||||
/Helvetica findfont 12 scalefont setfont 15 30 moveto (Hi) show\n%%EOF\n";
|
||||
let placed = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n");
|
||||
let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} {placed}LB\n%AI5_EndLayer--\n", tri(10));
|
||||
let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog"));
|
||||
let r = import(file.as_bytes()).unwrap();
|
||||
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Back"], "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert!(matches!(art[1].kind, NodeKind::PlacedDocument(_)), "{}: {:?}", tree(art), r.warnings);
|
||||
}
|
||||
|
||||
/// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then
|
||||
|
||||
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user