mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/parser-var-scope-budget
This commit is contained in:
commit
9e03c309cf
126 files changed
+7878
-878
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
+10
@@ -8876,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")]
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -1563,6 +1563,15 @@ fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64)
|
||||
let decoration_sq = decoration_reach * decoration_reach;
|
||||
let mut near_decoration = false;
|
||||
for sp in &path.subpaths {
|
||||
// A closed lone anchor has no segment, and a cap can draw a dot on it: the full check
|
||||
// decides a click near it.
|
||||
if sp.closed
|
||||
&& sp.segment_count() == 0
|
||||
&& let Some(a) = sp.anchors.first()
|
||||
&& (a.p - p).hypot2() <= radius_sq.max(decoration_sq)
|
||||
{
|
||||
near_decoration = true;
|
||||
}
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
|
||||
|
||||
+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]);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
+192
-39
@@ -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);
|
||||
@@ -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];
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
)]
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
+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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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>,
|
||||
|
||||
+351
-95
@@ -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,7 +71,9 @@ 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};
|
||||
@@ -132,8 +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, the settings of each `DocumentPreset` the run made, and the `Variable` and `Dataset`
|
||||
/// objects it gave out.
|
||||
/// 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>,
|
||||
@@ -141,10 +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()
|
||||
@@ -153,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
|
||||
}
|
||||
@@ -251,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>| {
|
||||
@@ -271,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 {
|
||||
@@ -603,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})
|
||||
@@ -1181,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;
|
||||
|
||||
@@ -1298,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)
|
||||
@@ -1447,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],
|
||||
@@ -1471,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);
|
||||
}
|
||||
@@ -1809,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)? {
|
||||
@@ -2204,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.
|
||||
@@ -2247,16 +2357,29 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
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 = {
|
||||
@@ -2266,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),
|
||||
@@ -2277,31 +2403,54 @@ 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"]
|
||||
@@ -2309,47 +2458,53 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags)));
|
||||
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(
|
||||
[
|
||||
@@ -2380,17 +2535,15 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
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)]
|
||||
@@ -2430,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)]
|
||||
}
|
||||
@@ -40,11 +40,11 @@ use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostItem, MemberInfo, Realm, RunError, file_ref_path, host_ref};
|
||||
|
||||
use super::{
|
||||
Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get,
|
||||
handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc,
|
||||
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;
|
||||
@@ -723,26 +723,28 @@ fn item_set_content(h: &Host, a: &[Data]) -> Answer {
|
||||
// ---- Registration ----
|
||||
|
||||
/// The members this module adds to `Document`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> {
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("variables", get(l, doc_variables)),
|
||||
("dataSets", get(l, doc_datasets)),
|
||||
("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)),
|
||||
("variablesLocked", property(l, doc_locked, doc_set_locked)),
|
||||
("importVariables", method(l, doc_import)),
|
||||
("exportVariables", method(l, doc_export)),
|
||||
("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<(String, HostMember)> {
|
||||
named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))])
|
||||
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<(String, HostMember)> {
|
||||
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))]),
|
||||
"TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => {
|
||||
named(vec![("contentVariable", property(l, item_content, item_set_content), typed("Variable"))])
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -754,13 +756,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
"Variables",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, vars_typename)),
|
||||
("length", get(l, vars_length)),
|
||||
("parent", get(l, vars_parent)),
|
||||
("index", method(l, vars_index)),
|
||||
("getByName", method(l, vars_by_name)),
|
||||
("add", method(l, vars_add)),
|
||||
("removeAll", method(l, vars_remove_all)),
|
||||
("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)),
|
||||
),
|
||||
@@ -768,12 +770,12 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
"Variable",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, var_typename)),
|
||||
("parent", get(l, var_parent)),
|
||||
("name", property(l, var_name, var_set_name)),
|
||||
("kind", property(l, var_kind, var_set_kind)),
|
||||
("pageItems", get(l, var_page_items)),
|
||||
("remove", method(l, var_remove)),
|
||||
("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,
|
||||
),
|
||||
@@ -781,13 +783,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
"Datasets",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, sets_typename)),
|
||||
("length", get(l, sets_length)),
|
||||
("parent", get(l, sets_parent)),
|
||||
("index", method(l, sets_index)),
|
||||
("getByName", method(l, sets_by_name)),
|
||||
("add", method(l, sets_add)),
|
||||
("removeAll", method(l, sets_remove_all)),
|
||||
("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)),
|
||||
),
|
||||
@@ -795,12 +797,12 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
"Dataset",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, set_typename)),
|
||||
("parent", get(l, set_parent)),
|
||||
("name", property(l, set_name, set_set_name)),
|
||||
("display", method(l, set_display)),
|
||||
("update", method(l, set_update)),
|
||||
("remove", method(l, set_remove)),
|
||||
("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,
|
||||
),
|
||||
|
||||
@@ -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,17 +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 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));
|
||||
@@ -1373,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() {
|
||||
@@ -2136,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.
|
||||
|
||||
@@ -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,6 +1388,32 @@ 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();
|
||||
@@ -1291,16 +1440,23 @@ fn wrappers_go_stale_after_revert() {
|
||||
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);");
|
||||
@@ -1920,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();
|
||||
@@ -1947,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"));
|
||||
|
||||
@@ -47,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"),
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global
|
||||
//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind
|
||||
//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of
|
||||
//! `localize`, the global `toSource` and `Object.prototype.toSource`, `Object.prototype.reflect`
|
||||
//! ([`crate::reflect`]), and the getters behind [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of
|
||||
//! [`Localization`].
|
||||
//!
|
||||
//! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression
|
||||
@@ -96,7 +96,8 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
method(interp, global, "localize", localize, 1)?;
|
||||
method(interp, global, "toSource", to_source, 1)?;
|
||||
let object_proto = interp.intrinsics.object_proto;
|
||||
method(interp, object_proto, "toSource", to_source_method, 0)
|
||||
method(interp, object_proto, "toSource", to_source_method, 0)?;
|
||||
crate::reflect::install(interp)
|
||||
}
|
||||
|
||||
/// The text of the localization object `id` for the current locale: the string value of the first
|
||||
|
||||
@@ -502,6 +502,18 @@ fn tagged_templates_get_one_frozen_strings_object_for_each_site() {
|
||||
truth("function tag(s) { return s.raw.join('|'); } tag`a\r\nb${0}\\\r\nc` === 'a\\nb|\\\\\\nc'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_closures_release_their_template_objects_in_one_collection() {
|
||||
let mut realm = es();
|
||||
assert_eq!(
|
||||
realm.run("function tag(value) { return value; } var site = function () { return tag`gone`; }; site(); site = null; 0"),
|
||||
Ok(JsValue::Number(0.0)),
|
||||
);
|
||||
assert_eq!(realm.interp().template_objects.len(), 1);
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.interp().template_objects.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_objects_go_once_their_code_cannot_run() {
|
||||
// Each eval makes code with two template sites; once it has run, nothing can run that code.
|
||||
|
||||
+13
-3
@@ -818,7 +818,7 @@ impl Heap {
|
||||
/// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so
|
||||
/// a value that refers back to its own key does not keep it alive. Values waiting for their
|
||||
/// key are kept by key, so the marking stays linear in the number of entries.
|
||||
pub(crate) fn collect(&mut self, roots: &Roots<'_>) {
|
||||
pub(crate) fn collect(&mut self, roots: &Roots<'_>) -> HashSet<usize> {
|
||||
let mut marks = vec![false; self.cells.len()];
|
||||
let mut work: Vec<u32> = Vec::new();
|
||||
let mut strings = StringSizes::default();
|
||||
@@ -833,7 +833,13 @@ impl Heap {
|
||||
for code in &roots.codes {
|
||||
mark_code(code, &mut strings);
|
||||
}
|
||||
while let Some(i) = work.pop() {
|
||||
let mut reached_codes = 0;
|
||||
loop {
|
||||
while let Some(&code) = strings.codes.get(reached_codes) {
|
||||
reached_codes += 1;
|
||||
work.extend(roots.template_objects.get(&code).into_iter().flatten().map(|id| id.0));
|
||||
}
|
||||
let Some(i) = work.pop() else { break };
|
||||
let Some(mark) = marks.get_mut(i as usize) else { continue };
|
||||
if *mark {
|
||||
continue;
|
||||
@@ -888,6 +894,7 @@ impl Heap {
|
||||
live = live.saturating_sub(self.compact_collections());
|
||||
self.bytes = live + strings.bytes;
|
||||
self.collections += 1;
|
||||
strings.codes.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Removes the holes of the Maps and Sets that have more holes than entries, and moves the
|
||||
@@ -927,6 +934,7 @@ pub(crate) struct Roots<'a> {
|
||||
pub(crate) objects: Vec<ObjId>,
|
||||
pub(crate) envs: Vec<EnvId>,
|
||||
pub(crate) codes: Vec<&'a Code>,
|
||||
pub(crate) template_objects: HashMap<usize, Vec<ObjId>>,
|
||||
}
|
||||
|
||||
/// Sums the sizes of the strings and property names reached, counting each node and each
|
||||
@@ -934,6 +942,7 @@ pub(crate) struct Roots<'a> {
|
||||
#[derive(Default)]
|
||||
struct StringSizes {
|
||||
seen: HashSet<usize>,
|
||||
codes: Vec<usize>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
@@ -1009,6 +1018,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
if !strings.seen.insert(code as *const Code as usize) {
|
||||
continue;
|
||||
}
|
||||
strings.codes.push(code as *const Code as usize);
|
||||
if strings.seen.insert(Rc::as_ptr(&code.source) as usize) {
|
||||
strings.bytes += code.source.lines.heap_bytes();
|
||||
// The text can share its buffer with the string eval was given.
|
||||
@@ -1236,7 +1246,7 @@ mod tests {
|
||||
object.props.insert(name.clone(), Prop::Data { value: Value::String(Str::from_rc(name.clone())), flags: 0 });
|
||||
object.props.insert(key("other"), Prop::Data { value: Value::Undefined, flags: 0 });
|
||||
let id = heap.alloc_object(object);
|
||||
heap.collect(&Roots { objects: vec![id], ..Roots::default() });
|
||||
let _ = heap.collect(&Roots { objects: vec![id], ..Roots::default() });
|
||||
assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5));
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,11 @@
|
||||
//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members,
|
||||
//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and
|
||||
//! `Object.getOwnPropertyDescriptor` do not report the members.
|
||||
//!
|
||||
//! A script's `reflect` ([`crate::reflect`]) describes an object of a host class, and the class's
|
||||
//! constructor, from the members installed here and their [`HostClass::info`], so what a script is
|
||||
//! told always matches what the class has. A class that names a member twice, or describes a member
|
||||
//! it does not have, is refused.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::rc::Rc;
|
||||
@@ -55,6 +60,39 @@ pub enum HostMember {
|
||||
Unavailable(HostFunction),
|
||||
}
|
||||
|
||||
/// What a script's `reflect` tells of a member of a host class ([`HostClass::info`]). The member's
|
||||
/// name and whether it is read-only, read-write or a method come from the [`HostMember`] itself.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MemberInfo {
|
||||
/// The type of the member's value, or of a method's result: `boolean`, `number`, `string`, a
|
||||
/// class name, `*` for any type, `null` or `undefined`. Empty reads as `unknown`.
|
||||
pub data_type: String,
|
||||
pub description: Option<String>,
|
||||
pub help: Option<String>,
|
||||
/// The value an omitted value means.
|
||||
pub default: Option<Data>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
/// The value, or a method's result, is a collection.
|
||||
pub collection: bool,
|
||||
/// A method's arguments, in order.
|
||||
pub arguments: Vec<ArgInfo>,
|
||||
/// The member is installed but throws when used: `reflect` leaves it out.
|
||||
pub unavailable: bool,
|
||||
}
|
||||
|
||||
/// What a script's `reflect` tells of an argument of a host class's method ([`MemberInfo::arguments`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ArgInfo {
|
||||
pub name: String,
|
||||
/// As [`MemberInfo::data_type`].
|
||||
pub data_type: String,
|
||||
pub description: Option<String>,
|
||||
pub default: Option<Data>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
}
|
||||
|
||||
/// A class [`crate::Realm::define_host_classes`] adds.
|
||||
#[derive(Clone)]
|
||||
pub struct HostClass {
|
||||
@@ -63,6 +101,9 @@ pub struct HostClass {
|
||||
/// class's prototype inherits from.
|
||||
pub parent: Option<String>,
|
||||
pub members: Vec<(String, HostMember)>,
|
||||
/// What `reflect` tells of the members, each under the name of one of `members`. A member
|
||||
/// without an entry has the type `unknown` and nothing else.
|
||||
pub info: Vec<(String, MemberInfo)>,
|
||||
/// What `object[i]` gives for an array index `i`.
|
||||
pub index: Option<HostFunction>,
|
||||
/// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`.
|
||||
@@ -93,6 +134,24 @@ pub(crate) struct Entry {
|
||||
own: Rc<HashSet<Key>>,
|
||||
/// The names of the members this class declares as unavailable.
|
||||
unavailable: Rc<HashSet<Key>>,
|
||||
/// The class's own members as `reflect` lists them.
|
||||
members: Rc<[Reflected]>,
|
||||
}
|
||||
|
||||
/// How a script may use a member of a host class.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Access {
|
||||
ReadOnly,
|
||||
ReadWrite,
|
||||
Method,
|
||||
}
|
||||
|
||||
/// A member of a host class as `reflect` lists it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Reflected {
|
||||
pub(crate) name: Rc<str>,
|
||||
pub(crate) access: Access,
|
||||
pub(crate) info: MemberInfo,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
@@ -228,6 +287,41 @@ impl Interp {
|
||||
self.host_classes.iter().any(|e| e.ctor == id)
|
||||
}
|
||||
|
||||
/// The name of the host class of `id`, when it is an object of a host class.
|
||||
pub(crate) fn host_class_name(&self, id: ObjId) -> JsResult<Option<Rc<str>>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
Ok(self.host_classes.get(h.class as usize).map(|e| e.name.clone()))
|
||||
}
|
||||
|
||||
/// The name and members of the host class of `id`, an object of the class or its constructor:
|
||||
/// the members of its parents first, then its own, a member a class declares again in the place
|
||||
/// of its parent's. Members marked [`MemberInfo::unavailable`] are left out. `None` when `id` is
|
||||
/// neither.
|
||||
pub(crate) fn host_class_members(&self, id: ObjId) -> JsResult<Option<(Rc<str>, Vec<Reflected>)>> {
|
||||
let class = match &self.object(id)?.class {
|
||||
Class::Host(h) => Some(h.class as usize),
|
||||
_ => self.host_classes.iter().position(|e| e.ctor == id),
|
||||
};
|
||||
let Some(class) = class else { return Ok(None) };
|
||||
let Some(entry) = self.host_classes.get(class) else { return Err(Abrupt::Internal("host class out of range".into())) };
|
||||
let mut chain = vec![entry];
|
||||
while let Some(p) = chain.last().and_then(|e| e.parent) {
|
||||
let Some(parent) = self.host_classes.get(p as usize) else { return Err(Abrupt::Internal("host class out of range".into())) };
|
||||
chain.push(parent);
|
||||
}
|
||||
let mut out: Vec<Reflected> = Vec::new();
|
||||
for e in chain.iter().rev() {
|
||||
for m in e.members.iter() {
|
||||
match out.iter_mut().find(|r| r.name == m.name) {
|
||||
Some(slot) => *slot = m.clone(),
|
||||
None => out.push(m.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
out.retain(|m| !m.info.unavailable);
|
||||
Ok(Some((entry.name.clone(), out)))
|
||||
}
|
||||
|
||||
/// The indexer of the host class of `id`, when it is an object of a host class that has one.
|
||||
pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult<Option<HostFunction>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
@@ -326,13 +420,17 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))),
|
||||
},
|
||||
};
|
||||
let members = match reflected_members(&class) {
|
||||
Ok(m) => m,
|
||||
Err(message) => return Err(i.throw(ErrorType::Type, &message)),
|
||||
};
|
||||
let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent)));
|
||||
let mark = i.temp_roots.len();
|
||||
i.temp_roots.push(Value::Object(proto));
|
||||
let r = fill_class(i, proto, &class);
|
||||
i.temp_roots.truncate(mark);
|
||||
let ctor = r?;
|
||||
let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
|
||||
let (unavailable, own_members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
|
||||
let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::<HashSet<Key>>();
|
||||
i.host_classes.push(Entry {
|
||||
name: class.name.as_str().into(),
|
||||
@@ -341,13 +439,49 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
index: class.index,
|
||||
family,
|
||||
parent: parent_class,
|
||||
own: Rc::new(names(members)),
|
||||
own: Rc::new(names(own_members)),
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
members,
|
||||
});
|
||||
let global = i.global;
|
||||
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
}
|
||||
|
||||
/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the
|
||||
/// error's message when a member is named twice, or an entry names no member or is given twice.
|
||||
fn reflected_members(class: &HostClass) -> Result<Rc<[Reflected]>, String> {
|
||||
let mut out: Vec<Reflected> = Vec::with_capacity(class.members.len());
|
||||
for (name, member) in &class.members {
|
||||
if out.iter().any(|r| *r.name == **name) {
|
||||
return Err(format!("the host class {} names the member {name} twice", class.name));
|
||||
}
|
||||
// The prototype's `constructor` is the class's own constructor.
|
||||
if name == "constructor" {
|
||||
return Err(format!("the host class {} names a member constructor, which is the name of its constructor", class.name));
|
||||
}
|
||||
let access = match member {
|
||||
HostMember::Get(_) => Access::ReadOnly,
|
||||
HostMember::Property { .. } | HostMember::Unavailable(_) => Access::ReadWrite,
|
||||
HostMember::Method(_) => Access::Method,
|
||||
};
|
||||
let unavailable = matches!(member, HostMember::Unavailable(_));
|
||||
out.push(Reflected { name: name.as_str().into(), access, info: MemberInfo { unavailable, ..MemberInfo::default() } });
|
||||
}
|
||||
let mut seen: Vec<&str> = Vec::with_capacity(class.info.len());
|
||||
for (name, info) in &class.info {
|
||||
if seen.contains(&name.as_str()) {
|
||||
return Err(format!("the host class {} describes the member {name} twice", class.name));
|
||||
}
|
||||
seen.push(name);
|
||||
let Some(slot) = out.iter_mut().find(|r| *r.name == **name) else {
|
||||
return Err(format!("the host class {} describes {name}, which is not one of its members", class.name));
|
||||
};
|
||||
let unavailable = slot.info.unavailable || info.unavailable;
|
||||
slot.info = MemberInfo { unavailable, ..info.clone() };
|
||||
}
|
||||
Ok(out.into())
|
||||
}
|
||||
|
||||
/// Puts the members of `class` on `proto` and makes its constructor. → the constructor.
|
||||
fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId> {
|
||||
let path = &class.name;
|
||||
|
||||
@@ -18,7 +18,7 @@ fn non_finite_indexer_keys_reach_the_host_unchanged() {
|
||||
assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}");
|
||||
Ok(Data::Bool(true))
|
||||
});
|
||||
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None };
|
||||
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], info: Vec::new(), index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
|
||||
let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
|
||||
@@ -39,6 +39,7 @@ fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
|
||||
name: "Indexed".into(),
|
||||
parent: None,
|
||||
members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))],
|
||||
info: Vec::new(),
|
||||
index: Some(function),
|
||||
construct: None,
|
||||
};
|
||||
@@ -54,7 +55,14 @@ fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
|
||||
#[test]
|
||||
fn index_keys_share_the_receivers_data_budget() {
|
||||
let mut r = realm(1_000_000);
|
||||
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None };
|
||||
let class = HostClass {
|
||||
name: "Indexed".into(),
|
||||
parent: None,
|
||||
members: vec![],
|
||||
info: Vec::new(),
|
||||
index: Some(Rc::new(|_| Ok(Data::Bool(true)))),
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
|
||||
r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 });
|
||||
assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true));
|
||||
@@ -824,7 +832,7 @@ fn with_thing(r: &mut Realm, make: Option<HostFunction>) {
|
||||
let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) });
|
||||
let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number)));
|
||||
let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))];
|
||||
let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make };
|
||||
let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: make };
|
||||
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap();
|
||||
}
|
||||
|
||||
@@ -870,6 +878,7 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
("grow".to_string(), HostMember::Method(value.clone())),
|
||||
("later".to_string(), HostMember::Unavailable(missing)),
|
||||
],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
@@ -877,6 +886,7 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
name: "Leaf".into(),
|
||||
parent: Some("Base".into()),
|
||||
members: vec![("leaf".to_string(), HostMember::Get(value))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
@@ -906,6 +916,7 @@ fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it()
|
||||
name: "Base".into(),
|
||||
parent: None,
|
||||
members: vec![("size".to_string(), HostMember::Get(value.clone())), ("grow".to_string(), HostMember::Method(value))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
@@ -913,6 +924,7 @@ fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it()
|
||||
name: "Leaf".into(),
|
||||
parent: Some("Base".into()),
|
||||
members: vec![("size".to_string(), HostMember::Unavailable(missing))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
@@ -933,7 +945,7 @@ fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
|
||||
_ => Err(HostError::Error("no such member".into())),
|
||||
}
|
||||
});
|
||||
let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), index: Some(index), construct: None };
|
||||
let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), info: Vec::new(), index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("List", &[1.0]))]).unwrap();
|
||||
r.start("Object.prototype.extra = 1; it.extra = 2; it.extra").unwrap();
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::Number(1.0));
|
||||
|
||||
@@ -930,16 +930,12 @@ impl Interp {
|
||||
roots.envs.push(self.global_env);
|
||||
roots.envs.push(self.global_lex);
|
||||
roots.envs.extend(self.temp_envs.iter().copied());
|
||||
// A template object stays while its code can still run: while the code has an owner other
|
||||
// than the entries of its own sites.
|
||||
let mut sites: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
|
||||
for &(code, _) in self.template_objects.keys() {
|
||||
*sites.entry(code).or_default() += 1;
|
||||
for (&(code, _), &(_, object)) in &self.template_objects {
|
||||
roots.template_objects.entry(code).or_default().push(object);
|
||||
}
|
||||
self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0));
|
||||
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
|
||||
self.promises.add_roots(&mut roots);
|
||||
self.heap.collect(&roots);
|
||||
let live_codes = self.heap.collect(&roots);
|
||||
self.template_objects.retain(|(code, _), _| live_codes.contains(code));
|
||||
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
|
||||
// The collection counts the live total again, so bytes already released are not in it.
|
||||
self.held.released.set(0);
|
||||
|
||||
@@ -128,6 +128,7 @@ mod number;
|
||||
mod number_builtins;
|
||||
mod parser;
|
||||
mod realm;
|
||||
mod reflect;
|
||||
mod regexp;
|
||||
mod regexp_builtins;
|
||||
mod regexp_vm;
|
||||
@@ -150,12 +151,13 @@ pub use ast::{
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{
|
||||
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
|
||||
};
|
||||
pub use reflect::MAX_REFLECTED_MEMBERS;
|
||||
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
|
||||
pub use xmp::{MAX_BYTES as XMP_MAX_BYTES, PacketSpan, find_packet as find_xmp_packet};
|
||||
|
||||
@@ -309,6 +311,8 @@ mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod reflect_tests;
|
||||
#[cfg(test)]
|
||||
mod symbol_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -672,7 +672,9 @@ impl Realm {
|
||||
/// Adds the script extensions: the global `localize(object, ...values)`, which gives a
|
||||
/// localization object's text for the locale of [`Realm::localization`], the global
|
||||
/// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text,
|
||||
/// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`].
|
||||
/// `Object.prototype.reflect`, which describes an object's properties and methods (a host
|
||||
/// class's from its [`crate::HostClass`]), and the localized `Object.prototype.toString` while
|
||||
/// [`crate::Localization::enabled`].
|
||||
pub fn add_script_extensions(&mut self) -> Result<(), RunError> {
|
||||
match crate::builtins::extensions::install(&mut self.interp) {
|
||||
Ok(()) => Ok(()),
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
//! The script extension `reflect` ([`crate::Realm::add_script_extensions`]): a read-only property
|
||||
//! of `Object.prototype` that gives, on each read, a new reflection object describing the object it
|
||||
//! is read on.
|
||||
//!
|
||||
//! A reflection object has `name` (the object's class), `description` and `help` (`undefined`),
|
||||
//! `properties` and `methods` (arrays of ReflectionInfo objects), and `find(name)`, which gives the
|
||||
//! ReflectionInfo of the property or method with that name, or `null`. A ReflectionInfo has `name`
|
||||
//! (a string, or a number for an array index), `description`, `help`, `type` (`readonly`,
|
||||
//! `readwrite`, `method`, or `parameter` for a method's argument), `dataType`, `defaultValue`,
|
||||
//! `min`, `max`, `isCollection` and `arguments` (an array of ReflectionInfo objects, empty for a
|
||||
//! property). Each entry of `properties`, `methods` and `arguments` is also under its name when
|
||||
//! that name is not an array index or `length`.
|
||||
//!
|
||||
//! An object of a host class and the class's constructor are described by the class's members
|
||||
//! ([`crate::HostClass::members`] and [`crate::HostClass::info`]), its parents' included. Any other
|
||||
//! object is described by its own properties: a property whose value is a function is a method,
|
||||
//! with the parameters of a function written in JavaScript as its arguments (the rest parameter
|
||||
//! last, and a destructured parameter with `name` `undefined`); a data property
|
||||
//! is read-write when it is writable and gives the type of its value; an accessor is read-write
|
||||
//! when it has a setter and its type is `unknown`. A string, number or boolean is described by its
|
||||
//! prototype's own properties. No getter or other script code runs.
|
||||
//!
|
||||
//! Every object made is frozen, so a script cannot change one; `reflect` itself has no setter.
|
||||
//! Each member described takes fuel, and an object with more than [`MAX_REFLECTED_MEMBERS`]
|
||||
//! members and arguments throws a `RangeError`.
|
||||
|
||||
use crate::builtins::native;
|
||||
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, key};
|
||||
use crate::host::Data;
|
||||
use crate::host_classes::{Access, Reflected};
|
||||
use crate::interp::{ErrorType, Interp, JsResult};
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::value::{Str, Value, array_index, index_key, number_to_str};
|
||||
|
||||
/// The most members and arguments `reflect` describes for one object.
|
||||
pub const MAX_REFLECTED_MEMBERS: usize = 10_000;
|
||||
|
||||
/// The properties of a ReflectionInfo object.
|
||||
const INFO_PROPS: usize = 10;
|
||||
|
||||
/// A member or argument as a ReflectionInfo object describes it.
|
||||
struct Info {
|
||||
name: Value,
|
||||
kind: &'static str,
|
||||
data_type: String,
|
||||
description: Option<String>,
|
||||
help: Option<String>,
|
||||
default: Option<Data>,
|
||||
min: Option<f64>,
|
||||
max: Option<f64>,
|
||||
collection: bool,
|
||||
arguments: Vec<Info>,
|
||||
}
|
||||
|
||||
impl Info {
|
||||
fn new(name: Value, kind: &'static str, data_type: &str) -> Self {
|
||||
Self {
|
||||
name,
|
||||
kind,
|
||||
data_type: data_type.to_string(),
|
||||
description: None,
|
||||
help: None,
|
||||
default: None,
|
||||
min: None,
|
||||
max: None,
|
||||
collection: false,
|
||||
arguments: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The type a [`crate::MemberInfo`] gives, `unknown` when it gives none.
|
||||
fn declared(data_type: &str) -> &str {
|
||||
if data_type.is_empty() { "unknown" } else { data_type }
|
||||
}
|
||||
|
||||
pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
let get = native(interp, "reflect", reflect, 0, NativeKind::Plain, false)?;
|
||||
let object_proto = interp.intrinsics.object_proto;
|
||||
interp.define(object_proto, key("reflect"), Prop::Accessor { get: Some(get), set: None, flags: 0 })
|
||||
}
|
||||
|
||||
/// Counts one more member or argument against [`MAX_REFLECTED_MEMBERS`], with a unit of fuel.
|
||||
fn count(interp: &mut Interp, total: &mut usize) -> JsResult<()> {
|
||||
interp.use_fuel()?;
|
||||
*total += 1;
|
||||
if *total > MAX_REFLECTED_MEMBERS {
|
||||
return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The getter of `Object.prototype.reflect`.
|
||||
fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (id, primitive) = match &this {
|
||||
Value::Undefined | Value::Null => return Err(interp.type_error("reflect needs an object")),
|
||||
Value::String(_) => (interp.intrinsics.string_proto, Some("String")),
|
||||
Value::Number(_) => (interp.intrinsics.number_proto, Some("Number")),
|
||||
Value::Bool(_) => (interp.intrinsics.boolean_proto, Some("Boolean")),
|
||||
Value::Symbol(_) => (interp.symbols.objects.map_or(interp.intrinsics.object_proto, |o| o.symbol_proto), Some("Symbol")),
|
||||
Value::Object(o) => (*o, None),
|
||||
};
|
||||
let (name, properties, methods) = match interp.host_class_members(id)? {
|
||||
Some((name, members)) if primitive.is_none() => {
|
||||
let (properties, methods) = host_infos(interp, &members)?;
|
||||
(name.to_string(), properties, methods)
|
||||
}
|
||||
_ => {
|
||||
let name = primitive.unwrap_or(interp.object(id)?.class.name()).to_string();
|
||||
let (properties, methods) = own_infos(interp, id)?;
|
||||
(name, properties, methods)
|
||||
}
|
||||
};
|
||||
interp.rooted(&[this], |i| {
|
||||
let mark = i.temp_roots.len();
|
||||
let r = reflection(i, &name, &properties, &methods);
|
||||
i.temp_roots.truncate(mark);
|
||||
r
|
||||
})
|
||||
}
|
||||
|
||||
/// The properties and methods of a host class's `members`.
|
||||
fn host_infos(interp: &mut Interp, members: &[Reflected]) -> JsResult<(Vec<Info>, Vec<Info>)> {
|
||||
let (mut properties, mut methods) = (Vec::new(), Vec::new());
|
||||
let mut total = 0;
|
||||
for m in members {
|
||||
count(interp, &mut total)?;
|
||||
let kind = match m.access {
|
||||
Access::ReadOnly => "readonly",
|
||||
Access::ReadWrite => "readwrite",
|
||||
Access::Method => "method",
|
||||
};
|
||||
let mut info = Info::new(Value::str(&m.name), kind, declared(&m.info.data_type));
|
||||
info.description = m.info.description.clone();
|
||||
info.help = m.info.help.clone();
|
||||
info.default = m.info.default.clone();
|
||||
info.min = m.info.min;
|
||||
info.max = m.info.max;
|
||||
info.collection = m.info.collection;
|
||||
for a in &m.info.arguments {
|
||||
count(interp, &mut total)?;
|
||||
let mut arg = Info::new(Value::str(&a.name), "parameter", declared(&a.data_type));
|
||||
arg.description = a.description.clone();
|
||||
arg.default = a.default.clone();
|
||||
arg.min = a.min;
|
||||
arg.max = a.max;
|
||||
info.arguments.push(arg);
|
||||
}
|
||||
if m.access == Access::Method { methods.push(info) } else { properties.push(info) }
|
||||
}
|
||||
Ok((properties, methods))
|
||||
}
|
||||
|
||||
/// The properties and methods of the own properties of `id`. No getter runs.
|
||||
fn own_infos(interp: &mut Interp, id: ObjId) -> JsResult<(Vec<Info>, Vec<Info>)> {
|
||||
let o = interp.object(id)?;
|
||||
let extra = match &o.class {
|
||||
Class::String(s) => s.len().saturating_add(1),
|
||||
Class::Array { .. } => 1,
|
||||
_ => 0,
|
||||
};
|
||||
// Checked before the names are listed, so a huge object costs no more than a small one.
|
||||
if o.props.len().saturating_add(extra) > MAX_REFLECTED_MEMBERS {
|
||||
return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members")));
|
||||
}
|
||||
let keys = interp.own_keys(id)?;
|
||||
let (mut properties, mut methods) = (Vec::new(), Vec::new());
|
||||
let mut total = 0;
|
||||
for k in keys {
|
||||
count(interp, &mut total)?;
|
||||
let Some(prop) = interp.get_own_property(id, &k)? else { continue };
|
||||
let name = member_name(&k);
|
||||
match prop {
|
||||
Prop::Data { value, .. } if interp.is_callable(&value) => {
|
||||
let mut info = Info::new(name, "method", "unknown");
|
||||
if let Some(params) = parameters(interp, &value)? {
|
||||
for p in params {
|
||||
count(interp, &mut total)?;
|
||||
// A destructured parameter has a compiler key that starts with U+0000.
|
||||
let name = if p.first() == Some(&0) { Value::Undefined } else { Value::String(Str::from_rc(p)) };
|
||||
info.arguments.push(Info::new(name, "parameter", "*"));
|
||||
}
|
||||
}
|
||||
methods.push(info);
|
||||
}
|
||||
Prop::Data { value, flags } => {
|
||||
let kind = if flags & WRITABLE != 0 { "readwrite" } else { "readonly" };
|
||||
let data_type = value_type(interp, &value)?;
|
||||
properties.push(Info::new(name, kind, &data_type));
|
||||
}
|
||||
Prop::Accessor { set, .. } => properties.push(Info::new(name, if set.is_some() { "readwrite" } else { "readonly" }, "unknown")),
|
||||
}
|
||||
}
|
||||
Ok((properties, methods))
|
||||
}
|
||||
|
||||
/// A property name as a ReflectionInfo's `name`: a number for an array index.
|
||||
fn member_name(k: &Key) -> Value {
|
||||
match array_index(k) {
|
||||
Some(i) => Value::Number(f64::from(i)),
|
||||
None => Value::String(Str::from_rc(k.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameter names of the function `f` when it is written in JavaScript, its rest parameter
|
||||
/// last.
|
||||
fn parameters(interp: &Interp, f: &Value) -> JsResult<Option<Vec<Key>>> {
|
||||
let Some(id) = f.as_object() else { return Ok(None) };
|
||||
Ok(match &interp.object(id)?.class {
|
||||
Class::Function(Func::Closure { code, .. }) => Some(code.params.iter().chain(&code.rest).cloned().collect()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `dataType` of a data property holding `v`.
|
||||
fn value_type(interp: &Interp, v: &Value) -> JsResult<String> {
|
||||
Ok(match v {
|
||||
Value::Undefined => "undefined".into(),
|
||||
Value::Null => "null".into(),
|
||||
Value::Bool(_) => "boolean".into(),
|
||||
Value::Number(_) => "number".into(),
|
||||
Value::String(_) => "string".into(),
|
||||
Value::Symbol(_) => "symbol".into(),
|
||||
Value::Object(o) => match interp.host_class_name(*o)? {
|
||||
Some(name) => name.to_string(),
|
||||
None => interp.object(*o)?.class.name().into(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The reflection object. Every object it makes is kept in `interp.temp_roots`.
|
||||
fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[Info]) -> JsResult<Value> {
|
||||
let properties = info_array(interp, properties)?;
|
||||
let methods = info_array(interp, methods)?;
|
||||
interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?;
|
||||
let find = native(interp, "find", find, 1, NativeKind::Plain, false)?;
|
||||
// `find` is frozen: in an ES2015 realm its `length` and `name` are made configurable, and
|
||||
// they are fixed again here.
|
||||
let o = interp.object_mut(find)?;
|
||||
for k in ["length", "name"] {
|
||||
if let Some(Prop::Data { flags, .. }) = o.props.get_mut(&key(k)) {
|
||||
*flags &= !(CONFIGURABLE | WRITABLE);
|
||||
}
|
||||
}
|
||||
o.extensible = false;
|
||||
interp.temp_roots.push(Value::Object(find));
|
||||
let r = interp.new_object();
|
||||
interp.temp_roots.push(Value::Object(r));
|
||||
for (k, v) in [
|
||||
("name", Value::str(name)),
|
||||
("description", Value::Undefined),
|
||||
("help", Value::Undefined),
|
||||
("properties", Value::Object(properties)),
|
||||
("methods", Value::Object(methods)),
|
||||
] {
|
||||
interp.define(r, key(k), Prop::Data { value: v, flags: ENUMERABLE })?;
|
||||
}
|
||||
interp.define(r, key("find"), Prop::Data { value: Value::Object(find), flags: 0 })?;
|
||||
interp.object_mut(r)?.extensible = false;
|
||||
Ok(Value::Object(r))
|
||||
}
|
||||
|
||||
/// A frozen array of ReflectionInfo objects for `infos`, each also under its name when that name
|
||||
/// is not an array index or `length`.
|
||||
fn info_array(interp: &mut Interp, infos: &[Info]) -> JsResult<ObjId> {
|
||||
interp.reserve_heap(OBJECT_BYTES.saturating_add(infos.len().saturating_mul(2 * PROP_BYTES)))?;
|
||||
let proto = interp.intrinsics.array_proto;
|
||||
let a = interp.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: false }, Some(proto)));
|
||||
interp.temp_roots.push(Value::Object(a));
|
||||
for (n, info) in infos.iter().enumerate() {
|
||||
let o = info_object(interp, info)?;
|
||||
interp.define(a, index_key(u32::try_from(n).unwrap_or(u32::MAX)), Prop::Data { value: Value::Object(o), flags: ENUMERABLE })?;
|
||||
}
|
||||
for (n, info) in infos.iter().enumerate() {
|
||||
let Value::String(s) = &info.name else { continue };
|
||||
let k = s.flat();
|
||||
if array_index(&k).is_some() || *k == *key("length") || interp.object(a)?.props.contains(&k) {
|
||||
continue;
|
||||
}
|
||||
let Some(Prop::Data { value, .. }) = interp.get_own_property(a, &index_key(u32::try_from(n).unwrap_or(u32::MAX)))? else { continue };
|
||||
interp.define(a, k, Prop::Data { value, flags: 0 })?;
|
||||
}
|
||||
interp.object_mut(a)?.extensible = false;
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// A frozen ReflectionInfo object for `info`.
|
||||
fn info_object(interp: &mut Interp, info: &Info) -> JsResult<ObjId> {
|
||||
let arguments = info_array(interp, &info.arguments)?;
|
||||
interp.reserve_heap(OBJECT_BYTES + INFO_PROPS * PROP_BYTES)?;
|
||||
let o = interp.new_object();
|
||||
interp.temp_roots.push(Value::Object(o));
|
||||
let text = |s: &Option<String>| s.as_deref().map_or(Value::Undefined, Value::str);
|
||||
let number = |n: Option<f64>| n.map_or(Value::Undefined, Value::Number);
|
||||
let default = match &info.default {
|
||||
Some(d) => interp.write_data(d.clone(), 0, true)?,
|
||||
None => Value::Undefined,
|
||||
};
|
||||
let fields = [
|
||||
("name", info.name.clone()),
|
||||
("description", text(&info.description)),
|
||||
("help", text(&info.help)),
|
||||
("type", Value::str(info.kind)),
|
||||
("dataType", Value::str(&info.data_type)),
|
||||
("defaultValue", default),
|
||||
("min", number(info.min)),
|
||||
("max", number(info.max)),
|
||||
("isCollection", Value::Bool(info.collection)),
|
||||
("arguments", Value::Object(arguments)),
|
||||
];
|
||||
for (k, v) in fields {
|
||||
interp.define(o, key(k), Prop::Data { value: v, flags: ENUMERABLE })?;
|
||||
}
|
||||
interp.object_mut(o)?.extensible = false;
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// `reflect.find(name)`: the ReflectionInfo of the property, or else the method, named `name` (a
|
||||
/// string, or a number for an array index), or `null`.
|
||||
fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let wanted = match args.first() {
|
||||
Some(Value::String(s)) => flat_charged(interp, s)?,
|
||||
Some(Value::Number(n)) => flat_charged(interp, &number_to_str(*n))?,
|
||||
_ => return Err(interp.type_error("reflect.find: give the member's name, as a string or a number")),
|
||||
};
|
||||
let not_reflection = "reflect.find must be called on a reflection object";
|
||||
let Value::Object(r) = this else { return Err(interp.type_error(not_reflection)) };
|
||||
for list in ["properties", "methods"] {
|
||||
let Some(Prop::Data { value: Value::Object(a), .. }) = interp.get_own_property(r, &key(list))? else {
|
||||
return Err(interp.type_error(not_reflection));
|
||||
};
|
||||
let Class::Array { length, .. } = interp.object(a)?.class else { return Err(interp.type_error(not_reflection)) };
|
||||
for i in 0..length {
|
||||
interp.use_fuel()?;
|
||||
let Some(Prop::Data { value: Value::Object(e), .. }) = interp.get_own_property(a, &index_key(i))? else { continue };
|
||||
let name = match interp.get_own_property(e, &key("name"))? {
|
||||
Some(Prop::Data { value: Value::String(s), .. }) => flat_charged(interp, &s)?,
|
||||
Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?,
|
||||
_ => continue,
|
||||
};
|
||||
if *name == *wanted {
|
||||
return Ok(Value::Object(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! `reflect`: the description of an object's properties and methods, from a host class's members
|
||||
//! or from an object's own properties.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn realm() -> Realm {
|
||||
let mut r = Realm::new();
|
||||
r.add_script_extensions().unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn text(r: &mut Realm, source: &str) -> String {
|
||||
match r.run(source) {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn thrown(r: &mut Realm, source: &str) -> String {
|
||||
match r.run(source) {
|
||||
Err(e) if e.kind == RunErrorKind::Thrown => e.message,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name:type:dataType` of each entry of a list, joined with spaces.
|
||||
const LIST: &str = "function list(a) { var s = []; for (var i = 0; i < a.length; i++) s.push(a[i].name + ':' + a[i].type + ':' + a[i].dataType); \
|
||||
return s.join(' '); }";
|
||||
|
||||
#[test]
|
||||
fn a_script_object_lists_its_own_properties_and_methods_without_running_getters() {
|
||||
let mut r = realm();
|
||||
let setup = "var o = {a: 1, b: 'x', c: null, d: [1], f: function (p, q) {}, get g() { throw new Error('ran'); }, set h(v) {}};\
|
||||
Object.defineProperty(o, 'k', {value: true, writable: false});";
|
||||
r.run(setup).unwrap();
|
||||
r.run(LIST).unwrap();
|
||||
assert_eq!(text(&mut r, "o.reflect.name"), "Object");
|
||||
assert_eq!(
|
||||
text(&mut r, "list(o.reflect.properties)"),
|
||||
"a:readwrite:number b:readwrite:string c:readwrite:null d:readwrite:Array g:readonly:unknown h:readwrite:unknown k:readonly:boolean"
|
||||
);
|
||||
assert_eq!(text(&mut r, "list(o.reflect.methods)"), "f:method:unknown");
|
||||
assert_eq!(text(&mut r, "list(o.reflect.methods[0].arguments)"), "p:parameter:* q:parameter:*");
|
||||
assert_eq!(text(&mut r, "list(o.reflect.properties[0].arguments) + '|' + o.reflect.description + '|' + o.reflect.help"), "|undefined|undefined");
|
||||
// A value replaced by a function becomes a method on the next read; each read is a new snapshot.
|
||||
assert_eq!(
|
||||
text(&mut r, "var before = o.reflect; o.a = function () {}; delete o.b; list(before.methods) + '|' + list(o.reflect.methods)"),
|
||||
"f:method:unknown|a:method:unknown f:method:unknown"
|
||||
);
|
||||
assert_eq!(text(&mut r, "String(o.reflect.find('b'))"), "null");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_and_names_look_up_properties_then_methods() {
|
||||
let mut r = realm();
|
||||
r.run("var o = {width: 2, draw: function () {}};").unwrap();
|
||||
assert_eq!(text(&mut r, "o.reflect.find('width').dataType + ' ' + o.reflect.find('draw').type"), "number method");
|
||||
assert_eq!(text(&mut r, "String(o.reflect.find('nothing'))"), "null");
|
||||
assert_eq!(text(&mut r, "o.reflect.properties.width.name + ' ' + o.reflect.methods.draw.name"), "width draw");
|
||||
// Array indexes are numbers, found by number or by their text.
|
||||
assert_eq!(
|
||||
text(
|
||||
&mut r,
|
||||
"var a = [5, 'x']; a[3] = true; var f = a.reflect.find(1); typeof f.name + ' ' + f.dataType + ' ' + a.reflect.find('3').dataType"
|
||||
),
|
||||
"number string boolean"
|
||||
);
|
||||
assert_eq!(text(&mut r, "[5].reflect.properties.length + ' ' + [5].reflect.find('length').type"), "2 readwrite");
|
||||
// A name that is missing or of another type is refused.
|
||||
assert!(thrown(&mut r, "o.reflect.find();").starts_with("TypeError"));
|
||||
assert!(thrown(&mut r, "o.reflect.find({});").starts_with("TypeError"));
|
||||
assert!(thrown(&mut r, "o.reflect.find.call({}, 'width');").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_charges_the_flattening_of_a_rope_name() {
|
||||
// Three ropes of about 524,288 units, each 1 MiB once flat, with a 3 MiB heap.
|
||||
let build = "var o = {a: 1}; var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z';";
|
||||
let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() };
|
||||
let mut r = Realm::with_options(Options::default(), limits);
|
||||
r.add_script_extensions().unwrap();
|
||||
match r.run(&format!("{build} o.reflect.find(s); o.reflect.find(t); o.reflect.find(u); 0")) {
|
||||
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rest_parameter_is_listed_with_the_arguments() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
r.add_script_extensions().unwrap();
|
||||
r.run(LIST).unwrap();
|
||||
assert_eq!(text(&mut r, "var o = {f: function (first, ...rest) {}}; list(o.reflect.methods[0].arguments)"), "first:parameter:* rest:parameter:*");
|
||||
assert_eq!(text(&mut r, "var g = {f: function (...all) {}}; list(g.reflect.find('f').arguments)"), "all:parameter:*");
|
||||
// A destructured parameter has no name of its own.
|
||||
assert_eq!(
|
||||
text(
|
||||
&mut r,
|
||||
"var d = {f: function (a, [b, c], ...[e]) {}}; list(d.reflect.methods[0].arguments) + '|' + d.reflect.methods[0].arguments.length"
|
||||
),
|
||||
"a:parameter:* undefined:parameter:* undefined:parameter:*|3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_is_described_by_its_prototype() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
r.add_script_extensions().unwrap();
|
||||
r.run(LIST).unwrap();
|
||||
assert_eq!(text(&mut r, "Symbol('s').reflect.name"), "Symbol");
|
||||
assert_eq!(text(&mut r, "Symbol('s').reflect.find('toString').type"), "method");
|
||||
assert_eq!(text(&mut r, "var o = {s: Symbol('s')}; o.reflect.find('s').dataType"), "symbol");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reflection_info_has_every_field() {
|
||||
let mut r = realm();
|
||||
let fields = "var i = ({a: 1}).reflect.properties[0]; var k = []; for (var n in i) k.push(n); k.join(' ')";
|
||||
assert_eq!(text(&mut r, fields), "name description help type dataType defaultValue min max isCollection arguments");
|
||||
let values =
|
||||
"var i = ({a: 1}).reflect.properties[0]; [i.description, i.help, i.defaultValue, i.min, i.max, i.isCollection, i.arguments.length].join()";
|
||||
assert_eq!(text(&mut r, values), ",,,,,false,0");
|
||||
assert_eq!(text(&mut r, "var k = []; for (var n in ({}).reflect) k.push(n); k.join(' ')"), "name description help properties methods");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_primitives_and_built_ins_are_described() {
|
||||
let mut r = realm();
|
||||
r.run(LIST).unwrap();
|
||||
assert_eq!(
|
||||
text(&mut r, "function f(a, b) {} f.reflect.name + ' ' + list(f.reflect.properties)"),
|
||||
"Function length:readonly:number prototype:readwrite:Object"
|
||||
);
|
||||
assert_eq!(text(&mut r, "Math.reflect.name + ' ' + Math.reflect.find('PI').type + ' ' + Math.reflect.find('max').type"), "Math readonly method");
|
||||
assert_eq!(text(&mut r, "'abc'.reflect.name + ' ' + 'abc'.reflect.find('charAt').type"), "String method");
|
||||
assert_eq!(text(&mut r, "(5).reflect.name + ' ' + true.reflect.name"), "Number Boolean");
|
||||
assert!(thrown(&mut r, "var n = null; n.reflect;").starts_with("TypeError"));
|
||||
let getter = "Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get";
|
||||
assert!(thrown(&mut r, &format!("{getter}.call(undefined);")).starts_with("TypeError"));
|
||||
// Neither a getter nor `toString` runs, so a cyclic object is described as it is.
|
||||
assert_eq!(text(&mut r, "var c = {}; c.self = c; c.toString = function () { throw 1; }; c.reflect.find('self').dataType"), "Object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reflection_cannot_be_changed() {
|
||||
let mut r = realm();
|
||||
r.run("var o = {a: 1}; var x = o.reflect;").unwrap();
|
||||
// Outside strict mode the writes are ignored.
|
||||
let tries = "o.reflect = 5; x.name = 'y'; x.properties[0].dataType = 'y'; x.properties[1] = 2; x.extra = 1; delete x.methods;\
|
||||
[typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()";
|
||||
assert_eq!(text(&mut r, tries), "object,Object,number,1,,object");
|
||||
// In strict mode each one throws a TypeError.
|
||||
for write in
|
||||
["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find", "x.find.extra = 1"]
|
||||
{
|
||||
assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}");
|
||||
}
|
||||
assert_eq!(
|
||||
text(
|
||||
&mut r,
|
||||
"Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments) + ' ' + Object.isFrozen(x.find)"
|
||||
),
|
||||
"true true true true"
|
||||
);
|
||||
// The frozen `find` still finds.
|
||||
assert_eq!(text(&mut r, "x.find('a').name"), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reflections_find_is_frozen_in_an_es2015_realm() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
r.add_script_extensions().unwrap();
|
||||
r.run("var f = ({a: 1}).reflect.find;").unwrap();
|
||||
assert_eq!(text(&mut r, "Object.isFrozen(f) + ' ' + f.name + ' ' + f.length"), "true find 1");
|
||||
for write in ["delete f.name", "delete f.length", "f.name = 'x'", "Object.defineProperty(f, 'name', {value: 'x'})"] {
|
||||
assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}");
|
||||
}
|
||||
assert_eq!(text(&mut r, "f.name"), "find");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_very_wide_object_is_refused() {
|
||||
let mut r = realm();
|
||||
let wide = |n: usize| format!("var w = {{}}; for (var i = 0; i < {n}; i++) w['p' + i] = i;");
|
||||
r.run(&wide(MAX_REFLECTED_MEMBERS)).unwrap();
|
||||
assert_eq!(text(&mut r, "String(w.reflect.properties.length)"), MAX_REFLECTED_MEMBERS.to_string());
|
||||
r.run(&wide(MAX_REFLECTED_MEMBERS + 1)).unwrap();
|
||||
assert!(thrown(&mut r, "w.reflect;").starts_with("RangeError"));
|
||||
// A function with too many parameters is counted with the members.
|
||||
let params = (0..MAX_REFLECTED_MEMBERS).map(|i| format!("a{i}")).collect::<Vec<_>>().join(",");
|
||||
assert!(thrown(&mut r, &format!("({{f: function ({params}) {{}}}}).reflect;")).starts_with("RangeError"));
|
||||
}
|
||||
|
||||
fn constant(value: f64) -> HostFunction {
|
||||
Rc::new(move |_| Ok(Data::Number(value)))
|
||||
}
|
||||
|
||||
/// `Item` with `size` (read-write, 1 to 10, default 5), `kind` and the method `fit(target,
|
||||
/// margin?)`; and `Box`, a child that declares `kind` again as a method and adds `cut`, which is
|
||||
/// not available.
|
||||
fn classes() -> Vec<HostClass> {
|
||||
let item = HostClass {
|
||||
name: "Item".into(),
|
||||
parent: None,
|
||||
members: vec![
|
||||
("size".into(), HostMember::Property { get: constant(5.0), set: constant(0.0) }),
|
||||
("kind".into(), HostMember::Get(constant(1.0))),
|
||||
("fit".into(), HostMember::Method(constant(2.0))),
|
||||
],
|
||||
info: vec![
|
||||
(
|
||||
"size".into(),
|
||||
MemberInfo {
|
||||
data_type: "number".into(),
|
||||
description: Some("The size.".into()),
|
||||
help: Some("How large the item is.".into()),
|
||||
default: Some(Data::Number(5.0)),
|
||||
min: Some(1.0),
|
||||
max: Some(10.0),
|
||||
..MemberInfo::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"fit".into(),
|
||||
MemberInfo {
|
||||
data_type: "boolean".into(),
|
||||
collection: true,
|
||||
arguments: vec![
|
||||
ArgInfo { name: "target".into(), data_type: "Item".into(), ..ArgInfo::default() },
|
||||
ArgInfo {
|
||||
name: "margin".into(),
|
||||
data_type: "number".into(),
|
||||
default: Some(Data::Number(0.0)),
|
||||
min: Some(0.0),
|
||||
..ArgInfo::default()
|
||||
},
|
||||
],
|
||||
..MemberInfo::default()
|
||||
},
|
||||
),
|
||||
],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let child = HostClass {
|
||||
name: "Box".into(),
|
||||
parent: Some("Item".into()),
|
||||
members: vec![("kind".into(), HostMember::Method(constant(3.0))), ("cut".into(), HostMember::Method(constant(4.0)))],
|
||||
info: vec![("cut".into(), MemberInfo { unavailable: true, ..MemberInfo::default() })],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
vec![item, child]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_is_described_by_its_members_and_their_info() {
|
||||
let mut r = realm();
|
||||
r.define_host_classes(classes(), vec![("item".into(), host_ref("Item", &[1.0])), ("box".into(), host_ref("Box", &[2.0]))]).unwrap();
|
||||
r.run(LIST).unwrap();
|
||||
for target in ["item", "Item"] {
|
||||
assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Item");
|
||||
assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number kind:readonly:unknown");
|
||||
assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "fit:method:boolean");
|
||||
}
|
||||
let size = "var s = item.reflect.find('size'); [s.description, s.help, s.defaultValue, s.min, s.max, s.isCollection].join('|')";
|
||||
assert_eq!(text(&mut r, size), "The size.|How large the item is.|5|1|10|false");
|
||||
let fit = "var f = item.reflect.find('fit'); f.isCollection + ' ' + list(f.arguments) + ' ' + f.arguments.margin.defaultValue + ' ' + f.arguments[1].min";
|
||||
assert_eq!(text(&mut r, fit), "true target:parameter:Item margin:parameter:number 0 0");
|
||||
// The child lists its parent's members first, its own declaration of one in its place, and
|
||||
// leaves out the member that is not available.
|
||||
for target in ["box", "Box"] {
|
||||
assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Box");
|
||||
assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number");
|
||||
assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "kind:method:unknown fit:method:boolean");
|
||||
assert_eq!(text(&mut r, &format!("String({target}.reflect.find('cut'))")), "null");
|
||||
}
|
||||
// No member's function ran: a data property of the class's type names it.
|
||||
assert_eq!(text(&mut r, "({b: box}).reflect.find('b').dataType"), "Box");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_for_a_member_a_class_does_not_have_is_refused() {
|
||||
for (info, message) in [
|
||||
(vec![("nothing".to_string(), MemberInfo::default())], "not one of its members"),
|
||||
(vec![("size".to_string(), MemberInfo::default()), ("size".to_string(), MemberInfo::default())], "twice"),
|
||||
] {
|
||||
let mut r = realm();
|
||||
let mut class = classes().remove(0);
|
||||
class.info = info;
|
||||
let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
|
||||
assert!(e.message.contains(message), "{}", e.message);
|
||||
}
|
||||
let mut r = realm();
|
||||
let mut class = classes().remove(0);
|
||||
class.members.push(("size".into(), HostMember::Get(constant(1.0))));
|
||||
let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
|
||||
assert!(e.message.contains("names the member size twice"), "{}", e.message);
|
||||
// `constructor` is the class's own constructor, so no member may take its name.
|
||||
let mut r = realm();
|
||||
let mut class = classes().remove(0);
|
||||
class.members.push(("constructor".into(), HostMember::Get(constant(1.0))));
|
||||
let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
|
||||
assert!(e.message.contains("names a member constructor"), "{}", e.message);
|
||||
assert_eq!(text(&mut r, "typeof Item"), "undefined");
|
||||
}
|
||||
@@ -612,6 +612,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots",
|
||||
),
|
||||
(
|
||||
"toolbar.addCommand",
|
||||
"Toolbar: Add Command",
|
||||
"",
|
||||
"{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:<id>`, `effect:<id>` or `panel:<id>`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands",
|
||||
),
|
||||
(
|
||||
"toolbar.removeCommand",
|
||||
"Toolbar: Remove Command",
|
||||
"",
|
||||
"{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands",
|
||||
),
|
||||
(
|
||||
"toolbar.reset",
|
||||
"Toolbar: Reset",
|
||||
@@ -670,7 +682,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.toolbar.list",
|
||||
"List Toolbars",
|
||||
"",
|
||||
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
|
||||
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
|
||||
),
|
||||
("window.taskBar", "Contextual Task Bar", "", "{}"),
|
||||
(
|
||||
@@ -1986,7 +1998,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"plugin.dialog",
|
||||
"Plug-in…",
|
||||
"",
|
||||
"{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)",
|
||||
"{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns). On the web the dialog has no live preview, and every filter it runs, at once or on OK, runs in a Web Worker → {background: true, status}",
|
||||
),
|
||||
(
|
||||
"plugin.applyLastFilter",
|
||||
@@ -2004,7 +2016,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.installPlugin",
|
||||
"Install Plug-in…",
|
||||
"",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
|
||||
),
|
||||
(
|
||||
"ui.failedPlugins",
|
||||
|
||||
@@ -503,7 +503,8 @@ fn run(
|
||||
tests::RUNS_STARTED.with(|n| n.set(n.get() + 1));
|
||||
let output = plugin.run_limited(&input, ¶ms, &limits)?;
|
||||
if plugin.manifest().paint_output {
|
||||
return Ok(Out::Pieces(Arc::new(painted::decode(&output, scope, rule)?)));
|
||||
let looks = plugin.manifest().appearance_output.then(painted::effect_check);
|
||||
return Ok(Out::Pieces(Arc::new(painted::decode_with(&output, scope, rule, looks)?)));
|
||||
}
|
||||
Ok(Out::Path(output_geometry(decode(&output)?)))
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ impl LogLevel {
|
||||
}
|
||||
}
|
||||
|
||||
fn log_level(self) -> log::Level {
|
||||
pub(crate) fn log_level(self) -> log::Level {
|
||||
match self {
|
||||
LogLevel::Error => log::Level::Error,
|
||||
LogLevel::Warn => log::Level::Warn,
|
||||
|
||||
@@ -31,7 +31,8 @@
|
||||
//! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is
|
||||
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
|
||||
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
|
||||
//! runs through `vc_run` with the command's id in `_context`.
|
||||
//! runs through `vc_run` with the command's id in `_context`. The web build checks modules and
|
||||
//! runs filters in a worker of its own ([`worker`]).
|
||||
//!
|
||||
//! An object filter may also be written in JavaScript ([`js`]): its manifest gives
|
||||
//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each
|
||||
@@ -55,11 +56,12 @@ mod runtime;
|
||||
pub mod safe_mode;
|
||||
pub mod storage;
|
||||
pub mod wat;
|
||||
pub mod worker;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, RunJob, Step, heavy_terms, keep_modules};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -512,6 +512,11 @@ pub struct Manifest {
|
||||
/// manifest has `"paintOutput": true`, the only value the key may hold.
|
||||
#[serde(default, rename = "paintOutput", skip_serializing_if = "std::ops::Not::not")]
|
||||
pub paint_output: bool,
|
||||
/// A live effect at `api` 3 that declares `paintOutput` and whose pieces, and their fills and
|
||||
/// strokes, may also carry opacity, a blending mode and effects ([`crate::painted`]): `true`
|
||||
/// when the manifest has `"appearanceOutput": true`, the only value the key may hold.
|
||||
#[serde(default, rename = "appearanceOutput", skip_serializing_if = "std::ops::Not::not")]
|
||||
pub appearance_output: bool,
|
||||
/// The menu commands it adds, in menu order (a filter or a live effect only).
|
||||
#[serde(default, deserialize_with = "ordered_commands", skip_serializing_if = "Vec::is_empty")]
|
||||
pub commands: Vec<Command>,
|
||||
@@ -539,9 +544,14 @@ impl Manifest {
|
||||
/// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys
|
||||
/// the manifest doesn't declare are ignored, and `params` keep the order the text gives them.
|
||||
pub(crate) fn parse_text(text: &str) -> Result<Manifest> {
|
||||
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
|
||||
let value = serde_json::from_str::<Value>(text).ok();
|
||||
let not_true = |key: &str| value.as_ref().is_some_and(|v| v.get(key).is_some_and(|p| *p != Value::Bool(true)));
|
||||
if not_true("paintOutput") {
|
||||
return Err(Error::Manifest("`paintOutput` may only be true".into()));
|
||||
}
|
||||
if not_true("appearanceOutput") {
|
||||
return Err(Error::Manifest("`appearanceOutput` may only be true".into()));
|
||||
}
|
||||
let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
|
||||
man.validate()?;
|
||||
man.read_places()?;
|
||||
@@ -567,6 +577,7 @@ impl Manifest {
|
||||
place: false,
|
||||
budget: Budget::Light,
|
||||
paint_output: false,
|
||||
appearance_output: false,
|
||||
commands: Vec::new(),
|
||||
command_allowlist: Vec::new(),
|
||||
runtime: Runtime::Wasm,
|
||||
@@ -639,6 +650,9 @@ impl Manifest {
|
||||
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
|
||||
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
|
||||
}
|
||||
if self.appearance_output && (!self.paint_output || self.api < APPEARANCE_API) {
|
||||
return Err(Error::Manifest("`appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3".into()));
|
||||
}
|
||||
self.validate_extensions()?;
|
||||
if self.place && self.kind != Kind::Importer {
|
||||
return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into()));
|
||||
@@ -1668,6 +1682,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A live effect at `api` 3 that declares `paintOutput` may also declare
|
||||
/// `"appearanceOutput": true`, and only that value, with no permission beyond `doc.read` and `effect.render`;
|
||||
/// without `paintOutput`, below `api` 3, on another kind, or with `false`, `null` or another
|
||||
/// type, it is refused naming the key. Without the key, at `api` 3, the effect paints as at 2.
|
||||
#[test]
|
||||
fn manifest_accepts_api3_appearance_output_only_for_painted_effects() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"org.example.tone","name":"Tone","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"permissions":["doc.read","effect.render"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(m.paint_output && m.appearance_output);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["appearanceOutput"], json!(true));
|
||||
let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true}"#).unwrap();
|
||||
assert!(plain.paint_output && !plain.appearance_output);
|
||||
assert!(serde_json::to_value(&plain).unwrap().get("appearanceOutput").is_none());
|
||||
for bad in [
|
||||
r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":false}"#,
|
||||
r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":null}"#,
|
||||
r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":1}"#,
|
||||
r#"{"id":"a","name":"x","kind":"effect","api":3,"appearanceOutput":true}"#,
|
||||
r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"appearanceOutput":true}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"appearanceOutput":true}"#,
|
||||
r#"{"id":"a","name":"x","kind":"exporter","api":3,"extensions":["plt"],"appearanceOutput":true}"#,
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains("appearanceOutput"), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_and_paint_output_may_both_be_declared_on_a_live_effect() {
|
||||
let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"commands":[{"id":"c","label":"C"}]}"#).unwrap();
|
||||
|
||||
@@ -781,7 +781,7 @@ fn decode_stroke(v: &Value, at: &str) -> Result<OutStroke> {
|
||||
/// An effect record from plug-in output: `{id, params?, visible?}`, in form only (the host says
|
||||
/// whether the effect exists and takes the parameters). `params` stays as given, so a record
|
||||
/// handed back unchanged equals the object's own.
|
||||
fn decode_effect(v: &Value, at: &str) -> Result<Effect> {
|
||||
pub(crate) fn decode_effect(v: &Value, at: &str) -> Result<Effect> {
|
||||
let e = v.as_object().ok_or_else(|| out_err(at, "an effect must be {\"id\", \"params\"?, \"visible\"?}"))?;
|
||||
let id = e.get("id").and_then(Value::as_str).filter(|id| (1..=MAX_EFFECT_ID).contains(&id.len()) && !id.chars().any(char::is_control));
|
||||
let id = id.ok_or_else(|| out_err(at, format!("`id` must be an effect id of 1-{MAX_EFFECT_ID} bytes")))?;
|
||||
|
||||
+263
-25
@@ -6,14 +6,21 @@
|
||||
//! A piece without `fills` (or `strokes`) keeps the ones it was given; an empty list paints none.
|
||||
//! An effect on a fill may return only `fills`, one on a stroke only `strokes`.
|
||||
//!
|
||||
//! An effect that also declares `"appearanceOutput": true` (at `api` 3) may give a piece, and each
|
||||
//! fill or stroke it returns, an `opacity` (0–1), a `blend` (a [`BlendMode`] by its identifier) and
|
||||
//! `effects` ([`Look`]): built-in effects only, which the host checks ([`CheckEffect`]), at most
|
||||
//! [`MAX_LOOK_EFFECTS`] in one list and [`MAX_RESULT_EFFECTS`] in one result. A fill that carries
|
||||
//! them is `{"paint", "opacity"?, "blend"?, "effects"?}`. The fills and strokes an effect on a fill
|
||||
//! or a stroke returns take no `effects`.
|
||||
//!
|
||||
//! The result is checked whole before any of it is used ([`decode`]): every number finite and in
|
||||
//! range (nothing is clamped), every key known, a gradient stop's `plates` only on a stop linked to
|
||||
//! a spot swatch, and every swatch and pattern a paint names in the document ([`check_references`]).
|
||||
//! One fault refuses the whole result, naming the field.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, LineCap, LineJoin};
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, LineCap, LineJoin};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use crate::objects::{MAX_COORD, MAX_ITEMS, MAX_OBJECTS, MAX_STROKE_WIDTH, MITER_LIMIT, OutStroke, check_point, out_err};
|
||||
@@ -24,15 +31,88 @@ use crate::{Error, Result};
|
||||
const PIECE_KEYS: [&str; 6] = ["type", "path", "fillRule", "bounds", "fills", "strokes"];
|
||||
/// The keys a stroke of a piece may have.
|
||||
const STROKE_KEYS: [&str; 5] = ["paint", "width", "join", "cap", "miterLimit"];
|
||||
/// The keys a piece, a stroke or a fill also may have when the effect declares `appearanceOutput`.
|
||||
const LOOK_KEYS: [&str; 3] = ["opacity", "blend", "effects"];
|
||||
/// The look keys a fill or stroke has that an effect on a fill or a stroke returns.
|
||||
const ROW_LOOK_KEYS: [&str; 2] = ["opacity", "blend"];
|
||||
/// The keys an effect record has.
|
||||
const EFFECT_KEYS: [&str; 3] = ["id", "params", "visible"];
|
||||
|
||||
/// Most effect records one piece, fill or stroke may carry.
|
||||
pub const MAX_LOOK_EFFECTS: usize = 16;
|
||||
/// Most effect records one result may carry, over all its pieces, fills and strokes.
|
||||
pub const MAX_RESULT_EFFECTS: usize = 4_096;
|
||||
|
||||
/// How the host checks an effect record a piece (`false`) or one of its fills or strokes (`true`)
|
||||
/// carries: `Err` with the reason when the record names no built-in effect that may be there or has
|
||||
/// parameters that effect does not take. The plug-in crate checks the record's form; which effects
|
||||
/// exist and what they take is the host's to say.
|
||||
pub type CheckEffect = fn(&Effect, bool) -> std::result::Result<(), String>;
|
||||
|
||||
/// The [`CheckEffect`] of a host that lets no effect record in.
|
||||
pub fn no_effects(_: &Effect, _: bool) -> std::result::Result<(), String> {
|
||||
Err("this host takes no effects here".into())
|
||||
}
|
||||
|
||||
/// The host's [`CheckEffect`], set once ([`set_effect_check`]).
|
||||
static CHECK: std::sync::OnceLock<CheckEffect> = std::sync::OnceLock::new();
|
||||
|
||||
/// Makes `check` how the effect records of painted results are checked in this process, unless
|
||||
/// one was set before. Until one is set, every effect record is refused ([`no_effects`]).
|
||||
pub fn set_effect_check(check: CheckEffect) {
|
||||
let _ = CHECK.set(check);
|
||||
}
|
||||
|
||||
/// How the effect records of painted results are checked ([`set_effect_check`]).
|
||||
pub(crate) fn effect_check() -> CheckEffect {
|
||||
CHECK.get().copied().unwrap_or(no_effects)
|
||||
}
|
||||
|
||||
/// The opacity, blending mode and effects a piece, or one of its fills or strokes, is given: each
|
||||
/// `None` (or empty) keeps what it would have without.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Look {
|
||||
pub opacity: Option<f32>,
|
||||
pub blend: Option<BlendMode>,
|
||||
/// Drawn after the effects it already has.
|
||||
pub effects: Vec<Effect>,
|
||||
}
|
||||
|
||||
impl Look {
|
||||
/// Does it keep everything as it is?
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.opacity.is_none() && self.blend.is_none() && self.effects.is_empty()
|
||||
}
|
||||
|
||||
/// Gives fill or stroke `item` this opacity and blending mode where given, and these effects
|
||||
/// after its own.
|
||||
fn dress(&self, item: &mut AppearanceItem) {
|
||||
let (opacity, blend, effects) = match item {
|
||||
AppearanceItem::Fill(f) => (&mut f.opacity, &mut f.blend, &mut f.effects),
|
||||
AppearanceItem::Stroke(s) => (&mut s.opacity, &mut s.blend, &mut s.effects),
|
||||
};
|
||||
if let Some(o) = self.opacity {
|
||||
*opacity = o;
|
||||
}
|
||||
if let Some(b) = self.blend {
|
||||
*blend = b;
|
||||
}
|
||||
effects.extend(self.effects.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
/// One piece a live effect returned: its geometry and fill rule, and its fills and strokes in paint
|
||||
/// order (`None`: the ones it was given).
|
||||
/// order (`None`: the ones it was given), with the look of the piece and of each fill and stroke it
|
||||
/// gives (`fill_looks[k]` for `fills[k]`; a missing one keeps everything).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Piece {
|
||||
pub path: PathData,
|
||||
pub rule: FillRule,
|
||||
pub fills: Option<Vec<Paint>>,
|
||||
pub strokes: Option<Vec<OutStroke>>,
|
||||
pub look: Look,
|
||||
pub fill_looks: Vec<Look>,
|
||||
pub stroke_looks: Vec<Look>,
|
||||
}
|
||||
|
||||
/// Where in an appearance the effect sits, which says what its pieces may paint.
|
||||
@@ -51,6 +131,13 @@ pub enum Scope {
|
||||
/// is ignored. Any other top-level key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of
|
||||
/// range or a paint of the wrong form refuses the whole result, naming the field.
|
||||
pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result<Vec<Piece>> {
|
||||
decode_with(bytes, scope, rule, None)
|
||||
}
|
||||
|
||||
/// [`decode`] for an effect that declares `appearanceOutput` when `looks` is `Some`: its pieces,
|
||||
/// fills and strokes may then carry opacity, a blending mode and effects, each effect record
|
||||
/// checked by it.
|
||||
pub fn decode_with(bytes: &[u8], scope: Scope, rule: FillRule, looks: Option<CheckEffect>) -> Result<Vec<Piece>> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?;
|
||||
if let Some(e) = crate::objects::declined(&v) {
|
||||
return Err(e);
|
||||
@@ -63,13 +150,38 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result<Vec<Piece>>
|
||||
if objects.len() > MAX_OBJECTS {
|
||||
return Err(out_err("objects", format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
|
||||
}
|
||||
let mut anchors = 0;
|
||||
objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut anchors)).collect()
|
||||
let mut counts = Counts { anchors: 0, effects: 0, looks, row_effects: scope == Scope::Object };
|
||||
objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut counts)).collect()
|
||||
}
|
||||
|
||||
fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) -> Result<Piece> {
|
||||
/// What a result holds so far, which its limits count: anchors and effect records, and how its
|
||||
/// effect records are checked (`None`: the result carries no look), and whether its fills and
|
||||
/// strokes may carry `effects` (only those of an object's effect: one on a fill or a stroke sits
|
||||
/// among that fill's or stroke's own effects).
|
||||
struct Counts {
|
||||
anchors: usize,
|
||||
effects: usize,
|
||||
looks: Option<CheckEffect>,
|
||||
row_effects: bool,
|
||||
}
|
||||
|
||||
impl Counts {
|
||||
/// The look keys a fill or stroke may have.
|
||||
fn row_look_keys(&self) -> &'static [&'static str] {
|
||||
if self.row_effects { &LOOK_KEYS } else { &ROW_LOOK_KEYS }
|
||||
}
|
||||
}
|
||||
|
||||
fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, counts: &mut Counts) -> Result<Piece> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?;
|
||||
if let Some(k) = o.keys().find(|k| !PIECE_KEYS.contains(&k.as_str())) {
|
||||
let known = |k: &str| PIECE_KEYS.contains(&k) || (counts.looks.is_some() && LOOK_KEYS.contains(&k));
|
||||
if let Some(k) = o.keys().find(|k| !known(k)) {
|
||||
if counts.looks.is_some() {
|
||||
return Err(out_err(
|
||||
&format!("{at}.{k}"),
|
||||
"a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects`",
|
||||
));
|
||||
}
|
||||
return Err(out_err(&format!("{at}.{k}"), "a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes`"));
|
||||
}
|
||||
if let Some(t) = o.get("type")
|
||||
@@ -79,7 +191,7 @@ fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize)
|
||||
}
|
||||
let path = o.get("path").ok_or_else(|| out_err(&format!("{at}.path"), "each piece needs a `path`"))?;
|
||||
// At most MAX_ANCHORS over all pieces.
|
||||
let path = crate::objects::decode_path(path, &format!("{at}.path"), anchors)?;
|
||||
let path = crate::objects::decode_path(path, &format!("{at}.path"), &mut counts.anchors)?;
|
||||
let rule = match o.get("fillRule") {
|
||||
None => rule,
|
||||
Some(r) => match r.as_str() {
|
||||
@@ -101,17 +213,112 @@ fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize)
|
||||
Scope::Stroke if fills.is_some() => return Err(out_err(&format!("{at}.fills"), "an effect on a stroke returns only `strokes`")),
|
||||
_ => {}
|
||||
}
|
||||
let fills = fills.map(|f| f.iter().enumerate().map(|(i, p)| paint(p, &format!("{at}.fills[{i}]"))).collect::<Result<Vec<_>>>()).transpose()?;
|
||||
let strokes =
|
||||
strokes.map(|s| s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"))).collect::<Result<Vec<_>>>()).transpose()?;
|
||||
Ok(Piece { path, rule, fills, strokes })
|
||||
let look = look(o, at, false, counts)?;
|
||||
let mut fill_looks = vec![];
|
||||
let fills = match fills {
|
||||
None => None,
|
||||
Some(f) => {
|
||||
let rows = f.iter().enumerate().map(|(i, p)| fill_row(p, &format!("{at}.fills[{i}]"), counts)).collect::<Result<Vec<_>>>()?;
|
||||
let (paints, looks): (Vec<Paint>, Vec<Look>) = rows.into_iter().unzip();
|
||||
fill_looks = looks;
|
||||
Some(paints)
|
||||
}
|
||||
};
|
||||
let mut stroke_looks = vec![];
|
||||
let strokes = match strokes {
|
||||
None => None,
|
||||
Some(s) => {
|
||||
let rows = s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"), counts)).collect::<Result<Vec<_>>>()?;
|
||||
let (strokes, looks): (Vec<OutStroke>, Vec<Look>) = rows.into_iter().unzip();
|
||||
stroke_looks = looks;
|
||||
Some(strokes)
|
||||
}
|
||||
};
|
||||
// A look that keeps everything is left out, so a result without any compares as one.
|
||||
for looks in [&mut fill_looks, &mut stroke_looks] {
|
||||
if looks.iter().all(Look::is_empty) {
|
||||
looks.clear();
|
||||
}
|
||||
}
|
||||
Ok(Piece { path, rule, fills, strokes, look, fill_looks, stroke_looks })
|
||||
}
|
||||
|
||||
/// A fill of a piece: a paint, or with `appearanceOutput` also `{"paint", "opacity"?, "blend"?,
|
||||
/// "effects"?}` (an object with `paint` and no `type`), with its look.
|
||||
fn fill_row(v: &Value, at: &str, counts: &mut Counts) -> Result<(Paint, Look)> {
|
||||
match v.as_object() {
|
||||
Some(o) if counts.looks.is_some() && o.contains_key("paint") && !o.contains_key("type") => {
|
||||
let keys: Vec<&str> = std::iter::once("paint").chain(counts.row_look_keys().iter().copied()).collect();
|
||||
only_keys(v, at, &keys)?;
|
||||
let look = look(o, at, true, counts)?;
|
||||
Ok((paint(o.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?, look))
|
||||
}
|
||||
_ => Ok((paint(v, at)?, Look::default())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifiers `blend` takes, in Transparency-panel order.
|
||||
fn blend_names() -> String {
|
||||
BlendMode::ALL.iter().map(|m| format!("{m:?}")).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// The opacity, blending mode and effects object `o` of a piece (`row` off) or of one of its fills
|
||||
/// or strokes gives, checked: an `opacity` from 0 to 1, a `blend` that is one of [`BlendMode`]'s
|
||||
/// identifiers exactly, and at most [`MAX_LOOK_EFFECTS`] effect records, each `{id, params?,
|
||||
/// visible?}` that the host's [`CheckEffect`] lets in, within [`MAX_RESULT_EFFECTS`] for the whole
|
||||
/// result. Without `appearanceOutput` the keys are refused before this is reached.
|
||||
fn look(o: &Map<String, Value>, at: &str, row: bool, counts: &mut Counts) -> Result<Look> {
|
||||
let Some(check) = counts.looks else { return Ok(Look::default()) };
|
||||
let opacity = match o.get("opacity") {
|
||||
None => None,
|
||||
Some(v) => match v.as_f64().filter(|x| within(*x, 0.0, 1.0)) {
|
||||
Some(x) => Some(x as f32),
|
||||
None => return Err(out_err(&format!("{at}.opacity"), "`opacity` must be a number from 0 to 1")),
|
||||
},
|
||||
};
|
||||
let blend = match o.get("blend") {
|
||||
None => None,
|
||||
Some(v) => match v.as_str().and_then(|s| BlendMode::ALL.into_iter().find(|m| format!("{m:?}") == s)) {
|
||||
Some(b) => Some(b),
|
||||
None => return Err(out_err(&format!("{at}.blend"), format!("unknown blending mode; `blend` is one of {}", blend_names()))),
|
||||
},
|
||||
};
|
||||
let records = match o.get("effects") {
|
||||
None => &[][..],
|
||||
Some(Value::Array(a)) if a.len() <= MAX_LOOK_EFFECTS => a.as_slice(),
|
||||
Some(_) => return Err(out_err(&format!("{at}.effects"), format!("`effects` must be an array of at most {MAX_LOOK_EFFECTS} records"))),
|
||||
};
|
||||
let mut effects = Vec::with_capacity(records.len());
|
||||
for (j, r) in records.iter().enumerate() {
|
||||
let at = format!("{at}.effects[{j}]");
|
||||
counts.effects += 1;
|
||||
if counts.effects > MAX_RESULT_EFFECTS {
|
||||
return Err(out_err(&at, format!("a result carries at most {MAX_RESULT_EFFECTS} effect records")));
|
||||
}
|
||||
only_keys(r, &at, &EFFECT_KEYS)?;
|
||||
let e = crate::objects::decode_effect(r, &at)?;
|
||||
check(&e, row).map_err(|why| out_err(&at, why))?;
|
||||
effects.push(e);
|
||||
}
|
||||
Ok(Look { opacity, blend, effects })
|
||||
}
|
||||
|
||||
/// A stroke `{paint, width?, join?, cap?, miterLimit?}`: a width of 0–[`MAX_STROKE_WIDTH`] and a
|
||||
/// miter limit in [`MITER_LIMIT`].
|
||||
fn stroke(v: &Value, at: &str) -> Result<OutStroke> {
|
||||
/// miter limit in [`MITER_LIMIT`]; with `appearanceOutput` also its look.
|
||||
fn stroke(v: &Value, at: &str, counts: &mut Counts) -> Result<(OutStroke, Look)> {
|
||||
let s = v.as_object().ok_or_else(|| out_err(at, "a stroke must be {\"paint\", \"width\"?, \"join\"?, \"cap\"?, \"miterLimit\"?}"))?;
|
||||
if let Some(k) = s.keys().find(|k| !STROKE_KEYS.contains(&k.as_str())) {
|
||||
if counts.looks.is_some() && !counts.row_effects {
|
||||
let keys: Vec<&str> = STROKE_KEYS.iter().chain(&ROW_LOOK_KEYS).copied().collect();
|
||||
only_keys(v, at, &keys)?;
|
||||
}
|
||||
let known = |k: &str| STROKE_KEYS.contains(&k) || (counts.looks.is_some() && LOOK_KEYS.contains(&k));
|
||||
if let Some(k) = s.keys().find(|k| !known(k)) {
|
||||
if counts.looks.is_some() {
|
||||
return Err(out_err(
|
||||
&format!("{at}.{k}"),
|
||||
"a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects`",
|
||||
));
|
||||
}
|
||||
return Err(out_err(&format!("{at}.{k}"), "a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit`"));
|
||||
}
|
||||
let number = |key: &str, range: std::ops::RangeInclusive<f64>| -> Result<Option<f64>> {
|
||||
@@ -136,7 +343,8 @@ fn stroke(v: &Value, at: &str) -> Result<OutStroke> {
|
||||
Some(_) => return Err(out_err(&format!("{at}.cap"), "`cap` must be \"butt\", \"round\" or \"square\"")),
|
||||
};
|
||||
let paint = paint(s.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?;
|
||||
Ok(OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? })
|
||||
let out = OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? };
|
||||
Ok((out, look(s, at, true, counts)?))
|
||||
}
|
||||
|
||||
/// Is `x` finite and in `lo..=hi`?
|
||||
@@ -407,48 +615,78 @@ pub(crate) fn with_swatch_colors(mut pieces: std::sync::Arc<Vec<Piece>>, doc: &D
|
||||
pieces
|
||||
}
|
||||
|
||||
/// How many paints, gradient stops and freeform points `pieces` hold: what a cache counts them as
|
||||
/// besides their anchors.
|
||||
/// How many paints, gradient stops and freeform points `pieces` hold, and one for each effect
|
||||
/// record they carry and for each 50 bytes of its parameters: what a cache counts them as besides
|
||||
/// their anchors.
|
||||
pub(crate) fn paint_count(pieces: &[Piece]) -> usize {
|
||||
let one = |p: &Paint| match p {
|
||||
Paint::Gradient(g) => 1 + g.gradient.stops.len() + g.freeform.as_ref().map_or(0, |f| f.points.len()),
|
||||
_ => 1,
|
||||
};
|
||||
pieces.iter().map(|p| p.fills.iter().flatten().map(one).sum::<usize>() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::<usize>()).sum()
|
||||
let effects = |l: &Look| l.effects.iter().map(|e| 1 + e.params.to_string().len() / 50).sum::<usize>();
|
||||
let looks = |p: &Piece| effects(&p.look) + p.fill_looks.iter().chain(&p.stroke_looks).map(effects).sum::<usize>();
|
||||
pieces
|
||||
.iter()
|
||||
.map(|p| p.fills.iter().flatten().map(one).sum::<usize>() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::<usize>() + looks(p))
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The appearance piece `p` of an object-level effect is drawn with: `base` (the object's) with
|
||||
/// its fills, then its strokes, replaced by the piece's where it has them, as a filter's output
|
||||
/// sets them (an existing item keeps everything but what the piece gives; new ones take the
|
||||
/// defaults).
|
||||
/// defaults), each given its look ([`Look`]). The piece's own look is not part of it: the art the
|
||||
/// piece becomes carries it.
|
||||
pub fn appearance(base: &Appearance, p: &Piece) -> Appearance {
|
||||
let mut ap = base.clone();
|
||||
if let Some(fills) = &p.fills {
|
||||
crate::objects::set_items(&mut ap, true, fills.iter().cloned().map(OutStroke::paint).collect());
|
||||
dress_items(&mut ap, true, &p.fill_looks);
|
||||
}
|
||||
if let Some(strokes) = &p.strokes {
|
||||
crate::objects::set_items(&mut ap, false, strokes.clone());
|
||||
dress_items(&mut ap, false, &p.stroke_looks);
|
||||
}
|
||||
ap
|
||||
}
|
||||
|
||||
/// Gives the fills (`fill`) or strokes of `ap`, in paint order, the looks in `looks`.
|
||||
fn dress_items(ap: &mut Appearance, fill: bool, looks: &[Look]) {
|
||||
for (item, look) in ap.items.iter_mut().filter(|i| i.is_fill() == fill).zip(looks) {
|
||||
look.dress(item);
|
||||
}
|
||||
}
|
||||
|
||||
/// The items piece `p` of an effect on `item` (a fill or a stroke) is drawn with, in paint order:
|
||||
/// `item` itself when the piece keeps it, else one copy of it for each paint or stroke the piece
|
||||
/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given).
|
||||
/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given) and
|
||||
/// that fill's or stroke's look.
|
||||
pub fn items(item: &AppearanceItem, p: &Piece) -> Vec<AppearanceItem> {
|
||||
let dressed = |mut it: AppearanceItem, look: Option<&Look>| {
|
||||
if let Some(look) = look {
|
||||
look.dress(&mut it);
|
||||
}
|
||||
it
|
||||
};
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => match &p.fills {
|
||||
None => vec![item.clone()],
|
||||
Some(fills) => fills.iter().map(|paint| AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() })).collect(),
|
||||
Some(fills) => fills
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, paint)| {
|
||||
dressed(AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() }), p.fill_looks.get(k))
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
AppearanceItem::Stroke(s) => match &p.strokes {
|
||||
None => vec![item.clone()],
|
||||
Some(strokes) => strokes
|
||||
.iter()
|
||||
.map(|o| {
|
||||
.enumerate()
|
||||
.map(|(k, o)| {
|
||||
let mut s = s.clone();
|
||||
crate::objects::style(&mut s, o.clone());
|
||||
AppearanceItem::Stroke(s)
|
||||
dressed(AppearanceItem::Stroke(s), p.stroke_looks.get(k))
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
|
||||
@@ -84,8 +84,15 @@ fn a_piece_s_appearance_inherits_or_replaces() {
|
||||
..Appearance::default()
|
||||
};
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let piece =
|
||||
|fills: Option<Vec<Paint>>, strokes: Option<Vec<OutStroke>>| Piece { path: PathData::default(), rule: FillRule::NonZero, fills, strokes };
|
||||
let piece = |fills: Option<Vec<Paint>>, strokes: Option<Vec<OutStroke>>| Piece {
|
||||
path: PathData::default(),
|
||||
rule: FillRule::NonZero,
|
||||
fills,
|
||||
strokes,
|
||||
look: Look::default(),
|
||||
fill_looks: vec![],
|
||||
stroke_looks: vec![],
|
||||
};
|
||||
assert_eq!(appearance(&base, &piece(None, None)), base, "inherited");
|
||||
let ap = appearance(&base, &piece(Some(vec![red.clone()]), Some(vec![])));
|
||||
assert_eq!(ap.items.len(), 1);
|
||||
@@ -348,3 +355,147 @@ fn linked_spot_stop_plates_are_kept() {
|
||||
assert_eq!(plates(&pieces[0].fills.as_ref().unwrap()[0]), [Some([0.0; 4]), Some([0.1, 0.2, 0.3, 0.4])]);
|
||||
assert_eq!(plates(&pieces[0].strokes.as_ref().unwrap()[0].paint), [None, Some([0.1, 0.2, 0.3, 0.4])]);
|
||||
}
|
||||
|
||||
/// A host check for these tests: Drop Shadow anywhere, Roughen on a piece only, nothing else.
|
||||
fn shadows_only(e: &Effect, row: bool) -> std::result::Result<(), String> {
|
||||
match e.id.as_str() {
|
||||
"stylize.dropShadow" => Ok(()),
|
||||
"distort.roughen" if !row => Ok(()),
|
||||
id => Err(format!("not taken: {id}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_looks(pieces: Value) -> Result<Vec<Piece>> {
|
||||
decode_with(&out(pieces), Scope::Object, FillRule::NonZero, Some(shadows_only))
|
||||
}
|
||||
|
||||
/// Without `appearanceOutput`, a piece, a fill and a stroke still have no opacity, blending mode
|
||||
/// or effects: each refuses the result, naming the field.
|
||||
#[test]
|
||||
fn api2_and_undeclared_effects_still_refuse_piece_appearance() {
|
||||
for (piece, at) in [
|
||||
(json!({"path": square(), "opacity": 0.5}), "objects[0].opacity"),
|
||||
(json!({"path": square(), "blend": "Multiply"}), "objects[0].blend"),
|
||||
(json!({"path": square(), "effects": []}), "objects[0].effects"),
|
||||
(json!({"path": square(), "fills": [{"paint": red(), "opacity": 0.5}]}), "objects[0].fills[0]"),
|
||||
(json!({"path": square(), "strokes": [{"paint": red(), "blend": "Screen"}]}), "objects[0].strokes[0].blend"),
|
||||
] {
|
||||
let e = decode(&out(json!([piece])), Scope::Object, FillRule::NonZero).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("{at}:")), "{at}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With `appearanceOutput`, a piece and each fill and stroke it returns take an opacity, a blending
|
||||
/// mode by its identifier and effect records the host lets in; a fill carrying them is
|
||||
/// `{"paint", …}`. The fills and strokes are dressed with them, with the effects after their own;
|
||||
/// a piece without any compares as one from an effect that declares nothing.
|
||||
#[test]
|
||||
fn piece_and_row_opacity_blend_and_effects_decode_in_order() {
|
||||
let shadow = json!({"id": "stylize.dropShadow", "params": {"x": 2}});
|
||||
let pieces = with_looks(json!([
|
||||
{"path": square(), "opacity": 0.5, "blend": "Multiply", "effects": [{"id": "distort.roughen"}, shadow],
|
||||
"fills": [red(), {"paint": red(), "opacity": 0.25, "blend": "ColorBurn", "effects": [shadow]}],
|
||||
"strokes": [{"paint": red(), "width": 2, "opacity": 0, "effects": [{"id": "stylize.dropShadow", "visible": false}]}]},
|
||||
{"path": square(), "fills": [red()]},
|
||||
]))
|
||||
.unwrap();
|
||||
let look = &pieces[0].look;
|
||||
assert_eq!((look.opacity, look.blend), (Some(0.5), Some(BlendMode::Multiply)));
|
||||
assert_eq!(look.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["distort.roughen", "stylize.dropShadow"]);
|
||||
assert_eq!(look.effects[1].params, json!({"x": 2}));
|
||||
assert_eq!(pieces[0].fill_looks.len(), 2);
|
||||
assert!(pieces[0].fill_looks[0].is_empty());
|
||||
assert_eq!((pieces[0].fill_looks[1].opacity, pieces[0].fill_looks[1].blend), (Some(0.25), Some(BlendMode::ColorBurn)));
|
||||
assert_eq!(pieces[0].stroke_looks[0].opacity, Some(0.0));
|
||||
assert!(!pieces[0].stroke_looks[0].effects[0].visible);
|
||||
let plain = decode(&out(json!([{"path": square(), "fills": [red()]}])), Scope::Object, FillRule::NonZero).unwrap();
|
||||
assert_eq!(pieces[1], plain[0], "no look");
|
||||
// Dressed: the second fill and the stroke take their looks, the stroke's effect after its own.
|
||||
let mut own = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
|
||||
own.effects.push(Effect { id: "stylize.outerGlow".into(), params: Value::Null, visible: true });
|
||||
let base = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE))), AppearanceItem::Stroke(own)],
|
||||
..Default::default()
|
||||
};
|
||||
let ap = appearance(&base, &pieces[0]);
|
||||
let fills: Vec<&FillLayer> = ap.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect();
|
||||
assert_eq!((fills[0].opacity, fills[0].blend), (1.0, BlendMode::Normal));
|
||||
assert_eq!((fills[1].opacity, fills[1].blend, fills[1].effects.len()), (0.25, BlendMode::ColorBurn, 1));
|
||||
let Some(AppearanceItem::Stroke(s)) = ap.items.iter().find(|i| !i.is_fill()) else { panic!("a stroke") };
|
||||
assert_eq!(s.opacity, 0.0);
|
||||
assert_eq!(s.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.outerGlow", "stylize.dropShadow"]);
|
||||
// On one fill: each copy takes its own fill's look.
|
||||
let copies = items(&base.items[0], &pieces[0]);
|
||||
let opacity: Vec<f32> = copies.iter().map(|i| if let AppearanceItem::Fill(f) = i { f.opacity } else { -1.0 }).collect();
|
||||
assert_eq!(opacity, [1.0, 0.25]);
|
||||
}
|
||||
|
||||
/// Every bad look refuses the whole result, naming the field: an opacity that is not a number from
|
||||
/// 0 to 1, a blending mode that is not an identifier exactly, an `effects` that is not a list, a
|
||||
/// record with another key or an id the host refuses (a plug-in effect, a geometry effect on a
|
||||
/// fill), and the limits of 16 records in a list and 4,096 in a result.
|
||||
#[test]
|
||||
fn invalid_appearance_field_refuses_every_piece_and_names_field() {
|
||||
let ok = json!({"path": square(), "opacity": 0.5});
|
||||
let shadow = json!({"id": "stylize.dropShadow"});
|
||||
for (piece, at) in [
|
||||
(json!({"path": square(), "opacity": 1.5}), "objects[1].opacity"),
|
||||
(json!({"path": square(), "opacity": -0.01}), "objects[1].opacity"),
|
||||
(json!({"path": square(), "opacity": "0.5"}), "objects[1].opacity"),
|
||||
(json!({"path": square(), "opacity": null}), "objects[1].opacity"),
|
||||
(json!({"path": square(), "blend": "multiply"}), "objects[1].blend"),
|
||||
(json!({"path": square(), "blend": "Color Burn"}), "objects[1].blend"),
|
||||
(json!({"path": square(), "blend": 2}), "objects[1].blend"),
|
||||
(json!({"path": square(), "effects": shadow}), "objects[1].effects"),
|
||||
(json!({"path": square(), "effects": [{"id": "stylize.dropShadow", "order": 1}]}), "objects[1].effects[0].order"),
|
||||
(json!({"path": square(), "effects": [{"id": ""}]}), "objects[1].effects[0]"),
|
||||
(json!({"path": square(), "effects": [{"id": "plugin.test.self"}]}), "objects[1].effects[0]"),
|
||||
(json!({"path": square(), "effects": [shadow, {"id": "stylize.nope"}]}), "objects[1].effects[1]"),
|
||||
(json!({"path": square(), "fills": [{"paint": red(), "effects": [{"id": "distort.roughen"}]}]}), "objects[1].fills[0].effects[0]"),
|
||||
(json!({"path": square(), "fills": [{"paint": red(), "tint": 1}]}), "objects[1].fills[0].tint"),
|
||||
(json!({"path": square(), "strokes": [{"paint": red(), "opacity": 2}]}), "objects[1].strokes[0].opacity"),
|
||||
(json!({"path": square(), "effects": vec![shadow.clone(); MAX_LOOK_EFFECTS + 1]}), "objects[1].effects"),
|
||||
] {
|
||||
let e = with_looks(json!([ok, piece])).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("{at}:")), "{at}: {e}");
|
||||
}
|
||||
let e = with_looks(json!([{"path": square(), "effects": [{"id": "plugin.test.self"}]}])).unwrap_err().to_string();
|
||||
assert!(e.contains("not taken: plugin.test.self"), "{e}");
|
||||
// 256 pieces of 16 records each fit; one more record does not.
|
||||
let full = json!({"path": square(), "effects": vec![shadow.clone(); MAX_LOOK_EFFECTS]});
|
||||
let mut many = vec![full.clone(); MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS];
|
||||
assert_eq!(with_looks(Value::from(many.clone())).unwrap().len(), MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS);
|
||||
many.push(json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]}));
|
||||
let e = with_looks(Value::from(many)).unwrap_err().to_string();
|
||||
assert!(
|
||||
e.contains(&format!("objects[{}].fills[0].effects[0]: a result carries at most {MAX_RESULT_EFFECTS}", MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS)),
|
||||
"{e}"
|
||||
);
|
||||
// A host that has set no check lets no record in.
|
||||
let e = decode_with(&out(json!([{"path": square(), "effects": [shadow]}])), Scope::Object, FillRule::NonZero, Some(no_effects)).unwrap_err();
|
||||
assert!(e.to_string().contains("objects[0].effects[0]:"), "{e}");
|
||||
}
|
||||
|
||||
/// An effect on a fill or a stroke sits among that fill's or stroke's own effects, so the fills
|
||||
/// and strokes it returns take an opacity and a blending mode but no `effects`, even an empty
|
||||
/// list; its pieces still take effects of their own.
|
||||
#[test]
|
||||
fn rows_of_an_effect_on_a_fill_or_stroke_take_no_effects() {
|
||||
let shadow = json!({"id": "stylize.dropShadow"});
|
||||
for (scope, piece, at) in [
|
||||
(Scope::Fill, json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]}), "objects[0].fills[0].effects"),
|
||||
(Scope::Fill, json!({"path": square(), "fills": [{"paint": red(), "effects": []}]}), "objects[0].fills[0].effects"),
|
||||
(Scope::Stroke, json!({"path": square(), "strokes": [{"paint": red(), "effects": [shadow]}]}), "objects[0].strokes[0].effects"),
|
||||
] {
|
||||
let e = decode_with(&out(json!([piece])), scope, FillRule::NonZero, Some(shadows_only)).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("{at}:")), "{at}: {e}");
|
||||
}
|
||||
for (scope, piece) in [
|
||||
(Scope::Fill, json!({"path": square(), "effects": [shadow], "fills": [{"paint": red(), "opacity": 0.5, "blend": "Screen"}]})),
|
||||
(Scope::Stroke, json!({"path": square(), "effects": [shadow], "strokes": [{"paint": red(), "width": 1, "opacity": 0.5}]})),
|
||||
(Scope::Object, json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]})),
|
||||
] {
|
||||
let pieces = decode_with(&out(json!([piece])), scope, FillRule::NonZero, Some(shadows_only));
|
||||
assert!(pieces.is_ok(), "{scope:?}: {pieces:?}");
|
||||
}
|
||||
}
|
||||
@@ -15,10 +15,14 @@ use crate::{Error, Kind, Result};
|
||||
|
||||
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
|
||||
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
|
||||
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]) and a manifest's
|
||||
/// `context` ([`CONTEXT_API`]).
|
||||
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]), a live effect's
|
||||
/// `appearanceOutput` ([`APPEARANCE_API`]) and a manifest's `context` ([`CONTEXT_API`]).
|
||||
pub const API_LEVEL: u32 = 3;
|
||||
|
||||
/// The API level that adds a painted live effect's `appearanceOutput`: opacity, a blending mode
|
||||
/// and effects on the pieces it returns and on their fills and strokes ([`crate::painted`]).
|
||||
pub const APPEARANCE_API: u32 = 3;
|
||||
|
||||
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
|
||||
/// `settings`, `cache` and `commands` permissions they need.
|
||||
pub const PROGRESS_API: u32 = 2;
|
||||
|
||||
+353
-114
@@ -1,12 +1,15 @@
|
||||
//! The wasmi host: loading, instantiating and calling a plug-in under resource limits.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use wasmi::{
|
||||
Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall,
|
||||
Val, ValType, WasmParams, WasmResults,
|
||||
TypedResumableCallHostTrap, Val, ValType, WasmParams, WasmResults,
|
||||
};
|
||||
use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures};
|
||||
|
||||
use crate::host::{self, Bridge, Deadline, Host, Report, Run};
|
||||
use crate::host::{self, Bridge, CallFailure, Deadline, Host, Import, Report, Run};
|
||||
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime};
|
||||
use crate::permissions::Permission;
|
||||
use crate::{Error, Kind, Result};
|
||||
@@ -169,6 +172,15 @@ impl Default for Limits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Do the plug-ins loaded from now on keep their module's bytes ([`Plugin::module_bytes`])?
|
||||
static KEEP_MODULES: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// From now on, each plug-in loaded keeps its module's bytes ([`Plugin::module_bytes`]) when `on`.
|
||||
/// The web build turns it on: it runs filters in a worker, which it hands the module to.
|
||||
pub fn keep_modules(on: bool) {
|
||||
KEEP_MODULES.store(on, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]).
|
||||
enum Code {
|
||||
Wasm { engine: Engine, module: Module },
|
||||
@@ -179,7 +191,12 @@ enum Code {
|
||||
/// every run gets its own store and instance, or for a JavaScript plug-in its own realm.
|
||||
pub struct Plugin {
|
||||
manifest: Manifest,
|
||||
/// The manifest JSON as `vc_manifest` returned it, or as the module's [`MANIFEST_SECTION`]
|
||||
/// custom section holds it. Empty for a JavaScript plug-in.
|
||||
manifest_text: Vec<u8>,
|
||||
code: Code,
|
||||
/// The module's bytes, kept while [`keep_modules`] is on.
|
||||
bytes: Option<Arc<[u8]>>,
|
||||
limits: Limits,
|
||||
size: usize,
|
||||
hash: String,
|
||||
@@ -187,6 +204,64 @@ pub struct Plugin {
|
||||
serial: u64,
|
||||
}
|
||||
|
||||
/// Where a run that [`Plugin::begin_run`] started is: waiting for the answer to a command call it
|
||||
/// made with `vc_call`, or ended.
|
||||
#[derive(Debug)]
|
||||
pub enum Step {
|
||||
/// It called command `command` with `args`, and waits for [`Plugin::resume_run`]'s answer.
|
||||
Call { command: String, args: serde_json::Value },
|
||||
/// It ended: its output JSON, or why it has none, and what it reported through the host imports.
|
||||
Done(Result<Vec<u8>>, Report),
|
||||
}
|
||||
|
||||
/// A run that [`Plugin::begin_run`] started: what it needs to go on after a command call.
|
||||
#[derive(Default)]
|
||||
pub struct RunJob {
|
||||
paused: Option<Paused>,
|
||||
}
|
||||
|
||||
impl RunJob {
|
||||
/// Does it wait for a command call's answer?
|
||||
pub fn waiting(&self) -> bool {
|
||||
self.paused.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A run paused at a `vc_call` of command `command`.
|
||||
struct Paused {
|
||||
live: Live,
|
||||
left: u64,
|
||||
deadline: Deadline,
|
||||
limits: Limits,
|
||||
command: String,
|
||||
call: Box<TypedResumableCallHostTrap<i64>>,
|
||||
}
|
||||
|
||||
/// What a call does next once the store's fuel pauses are dealt with: it finished, or it waits for
|
||||
/// the answer to a command call (the command, its arguments and the paused call).
|
||||
enum Driven<R> {
|
||||
Finished(R),
|
||||
Call(String, serde_json::Value, Box<TypedResumableCallHostTrap<R>>),
|
||||
}
|
||||
|
||||
/// Runs `f`, catching a panic as [`Error::Trap`]: wasmi reports misbehaving modules as errors, so a
|
||||
/// panic is a bug in it, and must still not take the document down (native builds; wasm aborts on
|
||||
/// panic anyway).
|
||||
fn guarded(f: impl FnOnce() -> (Option<Paused>, Step)) -> (Option<Paused>, Step) {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
|
||||
.unwrap_or_else(|_| (None, Step::Done(Err(Error::Trap("the runtime panicked".into())), Report::default())))
|
||||
}
|
||||
|
||||
/// Is export `name` of `module` a function with these `params` and `results`?
|
||||
fn exports_func(module: &Module, name: &str, params: &[ValType], results: &[ValType]) -> Result<()> {
|
||||
let e = match module.get_export(name) {
|
||||
Some(ExternType::Func(f)) if f.params() == params && f.results() == results => return Ok(()),
|
||||
Some(_) => "it has another type",
|
||||
None => "it is missing",
|
||||
};
|
||||
Err(Error::Abi(format!("export `{name}`: {e}")))
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Plugin {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Plugin").field("manifest", &self.manifest).field("size", &self.size).field("source", &self.source).finish()
|
||||
@@ -261,8 +336,9 @@ type RunArgs = (i32, i32, i32, i32);
|
||||
/// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none.
|
||||
/// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`],
|
||||
/// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must
|
||||
/// give the ABI version as `abi`, in place of the `vc_abi_version` export.
|
||||
fn section_manifest(module: &Module) -> Result<Option<Manifest>> {
|
||||
/// give the ABI version as `abi`, in place of the `vc_abi_version` export. Also gives the section's
|
||||
/// bytes, the manifest JSON.
|
||||
fn section_manifest(module: &Module) -> Result<Option<(Manifest, Vec<u8>)>> {
|
||||
let mut sections = module.custom_sections().filter(|s| s.name() == MANIFEST_SECTION);
|
||||
let Some(section) = sections.next() else {
|
||||
return Ok(None);
|
||||
@@ -278,7 +354,7 @@ fn section_manifest(module: &Module) -> Result<Option<Manifest>> {
|
||||
"the manifest in the `{MANIFEST_SECTION}` custom section must give `abi` as {ABI_VERSION}, the ABI version this host implements"
|
||||
)));
|
||||
}
|
||||
Ok(Some(manifest))
|
||||
Ok(Some((manifest, section.data().to_vec())))
|
||||
}
|
||||
|
||||
/// Most tables a module may define: the store an instance runs in holds no more.
|
||||
@@ -350,16 +426,123 @@ impl Plugin {
|
||||
/// `"runtime": "js"` are a JavaScript plug-in ([`crate::js`]): its manifest is checked and its
|
||||
/// script parsed, and none of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]).
|
||||
pub fn load(bytes: &[u8], limits: Limits) -> Result<Plugin> {
|
||||
let (mut p, imports) = Self::compile(bytes, limits)?;
|
||||
if p.read_section(bytes, &imports)? {
|
||||
return Ok(p);
|
||||
}
|
||||
let deadline = Deadline::new(p.limits.wall_time_ms);
|
||||
// The manifest isn't read yet: every host import is linked, what it reports is dropped and
|
||||
// there is no storage to reach.
|
||||
let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?;
|
||||
let version: TypedFunc<(), i32> = live.func("vc_abi_version")?;
|
||||
let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?;
|
||||
if v != ABI_VERSION {
|
||||
return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}")));
|
||||
}
|
||||
let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?;
|
||||
let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?;
|
||||
let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e {
|
||||
Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")),
|
||||
e => e,
|
||||
})?;
|
||||
p.read(text, &imports)?;
|
||||
// The other exports must exist with the right types.
|
||||
live.func::<i32, i32>("vc_alloc")?;
|
||||
live.func::<RunArgs, i64>("vc_run")?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// [`Plugin::load`] of a module that a load of the same bytes in another place (the web build's
|
||||
/// plug-in worker) has checked, with the manifest JSON that load read ([`Plugin::manifest_text`]).
|
||||
/// Every check that needs none of the module's code to run is made again; the module's start
|
||||
/// function, `vc_abi_version` and `vc_manifest` don't run. A module with a [`MANIFEST_SECTION`]
|
||||
/// custom section loads as [`Plugin::load`] loads it, from that section, and `manifest` is unused.
|
||||
pub fn load_checked(bytes: &[u8], limits: Limits, manifest: &[u8]) -> Result<Plugin> {
|
||||
let (mut p, imports) = Self::compile(bytes, limits)?;
|
||||
if p.read_section(bytes, &imports)? {
|
||||
return Ok(p);
|
||||
}
|
||||
if manifest.len() > MAX_MANIFEST_BYTES {
|
||||
return Err(Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")));
|
||||
}
|
||||
// A JavaScript plug-in has no section to read, and `read_section` has loaded it.
|
||||
let Code::Wasm { module, .. } = &p.code else { return Ok(p) };
|
||||
exports_func(module, "vc_abi_version", &[], &[ValType::I32])?;
|
||||
exports_func(module, "vc_manifest", &[], &[ValType::I64])?;
|
||||
exports_func(module, "vc_alloc", &[ValType::I32], &[ValType::I32])?;
|
||||
exports_func(module, "vc_run", &[ValType::I32; 4], &[ValType::I64])?;
|
||||
if !matches!(module.get_export("memory"), Some(ExternType::Memory(_))) {
|
||||
return Err(Error::Abi("the module must export its linear memory as `memory`".into()));
|
||||
}
|
||||
p.read(manifest.to_vec(), &imports)?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Takes manifest JSON `text` as the plug-in's: parses it, checks that it allows each host
|
||||
/// import of `imports`, and gives a heavy filter its larger budget.
|
||||
fn read(&mut self, text: Vec<u8>, imports: &[&Import]) -> Result<()> {
|
||||
let manifest = Manifest::parse(&text)?;
|
||||
self.take(manifest, text, imports)
|
||||
}
|
||||
|
||||
/// Reads the manifest from the module's [`MANIFEST_SECTION`] custom section
|
||||
/// ([`section_manifest`]) and checks the exports and tables a run needs, running none of the
|
||||
/// module's code; `bytes` is the module → false, with nothing read, when it has no such section.
|
||||
/// A JavaScript plug-in, whose manifest [`Plugin::compile`] has read, gives true.
|
||||
fn read_section(&mut self, bytes: &[u8], imports: &[&Import]) -> Result<bool> {
|
||||
let Code::Wasm { module, .. } = &self.code else {
|
||||
return Ok(true);
|
||||
};
|
||||
let module = module.clone();
|
||||
let Some((manifest, text)) = section_manifest(&module)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.take(manifest, text, imports)?;
|
||||
check_exports(&module, self.limits.max_memory_bytes)?;
|
||||
check_tables(bytes)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Takes `manifest`, parsed from JSON `text`, as the plug-in's: checks that it allows each host
|
||||
/// import of `imports`, and gives a heavy filter its larger budget. A WebAssembly module's
|
||||
/// manifest must leave `runtime` out.
|
||||
fn take(&mut self, manifest: Manifest, text: Vec<u8>, imports: &[&Import]) -> Result<()> {
|
||||
if manifest.runtime != Runtime::Wasm {
|
||||
return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into()));
|
||||
}
|
||||
self.manifest = manifest;
|
||||
host::check_granted(&self.manifest, imports)?;
|
||||
self.heavy_limits();
|
||||
self.manifest_text = text;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The checks of a module that run none of its code: its size, header, WebAssembly proposals and
|
||||
/// host imports, and wasmi's own validation → the plug-in, with its manifest still to be read,
|
||||
/// and the host imports it asks for. In Safe Mode nothing is loaded ([`Error::SafeMode`]).
|
||||
fn compile(bytes: &[u8], limits: Limits) -> Result<(Plugin, Vec<&'static Import>)> {
|
||||
crate::safe_mode::check()?;
|
||||
if bytes.len() > limits.max_module_bytes {
|
||||
return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes)));
|
||||
}
|
||||
let kept = || KEEP_MODULES.load(Ordering::Relaxed).then(|| Arc::from(bytes));
|
||||
// A JavaScript plug-in's manifest is read here; `read_section` then has nothing to read.
|
||||
if bytes.trim_ascii_start().starts_with(b"{") {
|
||||
let (manifest, script) = crate::js::read_bundle(bytes)?;
|
||||
let hash = crate::permissions::sha256_hex(bytes);
|
||||
let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 };
|
||||
let mut p = Plugin {
|
||||
manifest,
|
||||
manifest_text: Vec::new(),
|
||||
code: Code::Js(script),
|
||||
bytes: kept(),
|
||||
limits,
|
||||
size: bytes.len(),
|
||||
hash,
|
||||
source: None,
|
||||
serial: 0,
|
||||
};
|
||||
p.heavy_limits();
|
||||
return Ok(p);
|
||||
return Ok((p, Vec::new()));
|
||||
}
|
||||
if !bytes.starts_with(b"\0asm") {
|
||||
return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into()));
|
||||
@@ -375,58 +558,18 @@ impl Plugin {
|
||||
let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?;
|
||||
let imports = host::check_imports(&module)?;
|
||||
let hash = crate::permissions::sha256_hex(bytes);
|
||||
let section = section_manifest(&module)?;
|
||||
let mut p = Plugin {
|
||||
let p = Plugin {
|
||||
manifest: Manifest::placeholder(),
|
||||
code: Code::Wasm { engine, module: module.clone() },
|
||||
manifest_text: Vec::new(),
|
||||
code: Code::Wasm { engine, module },
|
||||
bytes: kept(),
|
||||
limits,
|
||||
size: bytes.len(),
|
||||
hash,
|
||||
source: None,
|
||||
serial: 0,
|
||||
};
|
||||
let live = match section {
|
||||
Some(manifest) => {
|
||||
p.manifest = manifest;
|
||||
None
|
||||
}
|
||||
None => {
|
||||
let deadline = Deadline::new(p.limits.wall_time_ms);
|
||||
// The manifest isn't read yet: every host import is linked, what it reports is
|
||||
// dropped and there is no storage to reach.
|
||||
let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?;
|
||||
let version: TypedFunc<(), i32> = live.func("vc_abi_version")?;
|
||||
let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?;
|
||||
if v != ABI_VERSION {
|
||||
return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}")));
|
||||
}
|
||||
let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?;
|
||||
let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?;
|
||||
let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e {
|
||||
Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")),
|
||||
e => e,
|
||||
})?;
|
||||
p.manifest = Manifest::parse(&text)?;
|
||||
Some(live)
|
||||
}
|
||||
};
|
||||
if p.manifest.runtime != Runtime::Wasm {
|
||||
return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into()));
|
||||
}
|
||||
host::check_granted(&p.manifest, &imports)?;
|
||||
p.heavy_limits();
|
||||
// The other exports must exist with the right types.
|
||||
match live {
|
||||
Some(live) => {
|
||||
live.func::<i32, i32>("vc_alloc")?;
|
||||
live.func::<RunArgs, i64>("vc_run")?;
|
||||
}
|
||||
None => {
|
||||
check_exports(&module, p.limits.max_memory_bytes)?;
|
||||
check_tables(bytes)?;
|
||||
}
|
||||
}
|
||||
Ok(p)
|
||||
Ok((p, imports))
|
||||
}
|
||||
|
||||
/// A heavy filter's runs get the larger budget the host allows for one, which the host lets the
|
||||
@@ -454,6 +597,15 @@ impl Plugin {
|
||||
pub fn manifest(&self) -> &Manifest {
|
||||
&self.manifest
|
||||
}
|
||||
/// The manifest JSON as the module's `vc_manifest` returned it or its manifest section holds
|
||||
/// it, for [`Plugin::load_checked`].
|
||||
pub fn manifest_text(&self) -> &[u8] {
|
||||
&self.manifest_text
|
||||
}
|
||||
/// The module's bytes, when it was loaded while [`keep_modules`] was on.
|
||||
pub fn module_bytes(&self) -> Option<&Arc<[u8]>> {
|
||||
self.bytes.as_ref()
|
||||
}
|
||||
pub fn id(&self) -> &str {
|
||||
&self.manifest.id
|
||||
}
|
||||
@@ -531,67 +683,83 @@ impl Plugin {
|
||||
/// storage call pays for its bytes ([`host::STORAGE_BYTES_PER_FUEL`]) from the store's fuel and
|
||||
/// the rest of the budget as it is made, and one they can't pay for ends the run.
|
||||
fn call<P: WasmParams, R: WasmResults>(&self, live: &mut Live, f: &TypedFunc<P, R>, params: P, fuel: u64, deadline: &Deadline) -> Result<R> {
|
||||
self.call_with(live, f, params, fuel, deadline, None)
|
||||
let mut left = fuel;
|
||||
let call = Self::first_slice(live, &mut left, |store| f.call_resumable(store, params))?;
|
||||
match Self::drive(live, &mut left, deadline, call)? {
|
||||
Driven::Finished(r) => Ok(r),
|
||||
Driven::Call(..) => Err(Error::Trap("unexpected host trap".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Plugin::call`], making each command call a `vc_call` pauses it for with `bridge`
|
||||
/// ([`host::Run::pending`]) and resuming it with the code. Each call costs [`host::CALL_FUEL`]
|
||||
/// instructions and one for every 64 bytes of its arguments and result; the deadline and the
|
||||
/// caller's cancellation are checked before and after it.
|
||||
fn call_with<P: WasmParams, R: WasmResults>(
|
||||
&self,
|
||||
/// Starts a call with `start`, on the first slice of the `left` instructions it may use.
|
||||
fn first_slice<R>(
|
||||
live: &mut Live,
|
||||
f: &TypedFunc<P, R>,
|
||||
params: P,
|
||||
fuel: u64,
|
||||
deadline: &Deadline,
|
||||
mut bridge: Option<&mut Bridge<'_>>,
|
||||
) -> Result<R> {
|
||||
let mut left = fuel;
|
||||
let give = left.min(FUEL_SLICE);
|
||||
left -= give;
|
||||
left: &mut u64,
|
||||
start: impl FnOnce(&mut Store<Host>) -> std::result::Result<TypedResumableCall<R>, wasmi::Error>,
|
||||
) -> Result<TypedResumableCall<R>> {
|
||||
let give = (*left).min(FUEL_SLICE);
|
||||
*left -= give;
|
||||
live.store.set_fuel(give).map_err(wasm_err)?;
|
||||
let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?;
|
||||
slice(live, left, start)
|
||||
}
|
||||
|
||||
/// Goes on with `call` slice by slice ([`Plugin::call`]) until it finishes or pauses for a
|
||||
/// command call that `vc_call` asked for ([`host::Run::pending`]). Each command call costs
|
||||
/// [`host::CALL_FUEL`] instructions and one for every 64 bytes of its arguments, and the deadline
|
||||
/// and the caller's cancellation are checked before it is made ([`Plugin::answer`]).
|
||||
fn drive<R: WasmResults>(live: &mut Live, left: &mut u64, deadline: &Deadline, mut call: TypedResumableCall<R>) -> Result<Driven<R>> {
|
||||
loop {
|
||||
match call {
|
||||
TypedResumableCall::Finished(r) => return Ok(r),
|
||||
TypedResumableCall::Finished(r) => return Ok(Driven::Finished(r)),
|
||||
TypedResumableCall::HostTrap(inv) => {
|
||||
if inv.host_error().downcast_ref::<host::StorageStop>().is_some() {
|
||||
return Err(stop_reason(&mut live.store));
|
||||
}
|
||||
let pending = live.store.data_mut().run.pending.take();
|
||||
let (Some((id, args, size)), Some(bridge)) = (pending, bridge.as_deref_mut()) else {
|
||||
let Some((id, args, size)) = live.store.data_mut().run.pending.take() else {
|
||||
return Err(Error::Trap("unexpected host trap".into()));
|
||||
};
|
||||
charge(live, &mut left, host::CALL_FUEL.saturating_add(size as u64 / 64))?;
|
||||
charge(live, left, host::CALL_FUEL.saturating_add(size as u64 / 64))?;
|
||||
deadline.check()?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
let answer = bridge(&id, &args);
|
||||
let code = live.store.data_mut().run.call_answered(&id, answer);
|
||||
let returned = live.store.data().run.call_result.as_ref().map_or(0, Vec::len);
|
||||
charge(live, &mut left, returned as u64 / 64)?;
|
||||
deadline.check()?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
call = slice(live, &mut left, |store| inv.resume(store, &[Val::I32(code)]))?;
|
||||
return Ok(Driven::Call(id, args, Box::new(inv)));
|
||||
}
|
||||
TypedResumableCall::OutOfFuel(inv) => {
|
||||
let need = inv.required_fuel();
|
||||
let held = live.store.get_fuel().map_err(wasm_err)?;
|
||||
let total = held.saturating_add(left);
|
||||
let total = held.saturating_add(*left);
|
||||
if need > total {
|
||||
return Err(Error::Limit("instruction budget".into()));
|
||||
}
|
||||
deadline.check()?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
let fill = total.min(FUEL_SLICE.max(need)).max(held);
|
||||
left -= fill - held;
|
||||
*left -= fill - held;
|
||||
live.store.set_fuel(fill).map_err(wasm_err)?;
|
||||
call = slice(live, &mut left, |store| inv.resume(store))?;
|
||||
call = slice(live, left, |store| inv.resume(store))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resumes `call`, which paused for command call `id`, with the host's `answer`: the code
|
||||
/// `vc_call` returns comes from [`host::Run::call_answered`]. The result costs one instruction for
|
||||
/// every 64 bytes, and the deadline and the caller's cancellation are checked again first.
|
||||
fn answer<R: WasmResults>(
|
||||
live: &mut Live,
|
||||
left: &mut u64,
|
||||
deadline: &Deadline,
|
||||
id: &str,
|
||||
answer: std::result::Result<serde_json::Value, CallFailure>,
|
||||
call: Box<TypedResumableCallHostTrap<R>>,
|
||||
) -> Result<TypedResumableCall<R>> {
|
||||
let code = live.store.data_mut().run.call_answered(id, answer);
|
||||
let returned = live.store.data().run.call_result.as_ref().map_or(0, Vec::len);
|
||||
charge(live, left, returned as u64 / 64)?;
|
||||
deadline.check()?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
slice(live, left, |store| call.resume(store, &[Val::I32(code)]))
|
||||
}
|
||||
|
||||
/// Runs `vc_run` on `input` (the objects JSON) with `params` (the parameters JSON) in a fresh
|
||||
/// instance and returns the output JSON bytes.
|
||||
pub fn run(&self, input: &[u8], params: &[u8]) -> Result<Vec<u8>> {
|
||||
@@ -621,58 +789,94 @@ impl Plugin {
|
||||
self.run_guarded(input, params, limits, Some(bridge))
|
||||
}
|
||||
|
||||
fn run_guarded(&self, input: &[u8], params: &[u8], limits: &Limits, bridge: Option<&mut Bridge<'_>>) -> (Result<Vec<u8>>, Report) {
|
||||
let mut report = Report::default();
|
||||
if let Err(e) = crate::safe_mode::check() {
|
||||
return (Err(e), report);
|
||||
fn run_guarded(&self, input: &[u8], params: &[u8], limits: &Limits, mut bridge: Option<&mut Bridge<'_>>) -> (Result<Vec<u8>>, Report) {
|
||||
let (mut job, mut step) = self.begin_run(input, params, limits, bridge.is_some());
|
||||
loop {
|
||||
match step {
|
||||
Step::Done(out, report) => return (out, report),
|
||||
Step::Call { command, args } => {
|
||||
let Some(bridge) = bridge.as_deref_mut() else {
|
||||
return (Err(Error::Trap("unexpected host trap".into())), Report::default());
|
||||
};
|
||||
// A panic making the call fails the run, as one in the runtime does.
|
||||
let Ok(answer) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| bridge(&command, &args))) else {
|
||||
return (Err(Error::Trap("the runtime panicked".into())), Report::default());
|
||||
};
|
||||
step = self.resume_run(&mut job, answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
// wasmi reports misbehaving modules as errors; a panic would be a bug in it, and must
|
||||
// still not take the document down (native builds; wasm aborts on panic anyway).
|
||||
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits, &mut report, bridge)));
|
||||
(run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report)
|
||||
}
|
||||
|
||||
fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits, report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<Vec<u8>> {
|
||||
/// Starts [`Plugin::run_reporting`]'s run, which can wait for the answers to its command calls
|
||||
/// in between: with `calls`, each `vc_call` of a command its manifest's `commandAllowlist` names
|
||||
/// ends the step with [`Step::Call`], and [`Plugin::resume_run`] goes on with the answer. The
|
||||
/// run's time budget runs on while it waits. In Safe Mode nothing runs ([`Error::SafeMode`]).
|
||||
pub fn begin_run(&self, input: &[u8], params: &[u8], limits: &Limits, calls: bool) -> (RunJob, Step) {
|
||||
if let Err(e) = crate::safe_mode::check() {
|
||||
return (RunJob::default(), Step::Done(Err(e), Report::default()));
|
||||
}
|
||||
let (paused, step) = guarded(|| self.begin_inner(input, params, limits, calls));
|
||||
(RunJob { paused }, step)
|
||||
}
|
||||
|
||||
/// Goes on with `job`, which waits for the answer to a command call ([`Step::Call`]), with that
|
||||
/// call's `answer` → where the run is next. A failed call fails the run, also when the plug-in
|
||||
/// goes on and returns an output; the error names the command.
|
||||
pub fn resume_run(&self, job: &mut RunJob, answer: std::result::Result<serde_json::Value, CallFailure>) -> Step {
|
||||
let Some(Paused { mut live, mut left, deadline, limits, command, call }) = job.paused.take() else {
|
||||
return Step::Done(Err(Error::Trap("unexpected host trap".into())), Report::default());
|
||||
};
|
||||
let (paused, step) = guarded(|| {
|
||||
let next = Self::answer(&mut live, &mut left, &deadline, &command, answer, call);
|
||||
self.advance(live, left, deadline, limits, next)
|
||||
});
|
||||
job.paused = paused;
|
||||
step
|
||||
}
|
||||
|
||||
fn begin_inner(&self, input: &[u8], params: &[u8], limits: &Limits, calls: bool) -> (Option<Paused>, Step) {
|
||||
let total = input.len().checked_add(params.len()).filter(|b| *b <= i32::MAX as usize && *b <= self.limits.max_memory_bytes / 2);
|
||||
total.ok_or_else(|| Error::Limit(SELECTION_TOO_LARGE.into()))?;
|
||||
if total.is_none() {
|
||||
return (None, Step::Done(Err(Error::Limit(SELECTION_TOO_LARGE.into())), Report::default()));
|
||||
}
|
||||
let deadline = Deadline::new(limits.wall_time_ms);
|
||||
let m = &self.manifest;
|
||||
let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id));
|
||||
let mut report = Report::default();
|
||||
if let Code::Js(script) = &self.code {
|
||||
// Its manifest lists no `commands`, so nothing calls it with a bridge.
|
||||
if bridge.is_some() {
|
||||
return Err(Error::Abi("a JavaScript plug-in makes no command calls".into()));
|
||||
if calls {
|
||||
return (None, Step::Done(Err(Error::Abi("a JavaScript plug-in makes no command calls".into())), report));
|
||||
}
|
||||
let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline };
|
||||
return crate::js::run(script, m, &call, run, report);
|
||||
let out = crate::js::run(script, m, &call, run, &mut report);
|
||||
return (None, Step::Done(out, report));
|
||||
}
|
||||
let mut live = self.instantiate(run, &m.permissions(), report)?;
|
||||
let mut live = match self.instantiate(run, &m.permissions(), &mut report) {
|
||||
Ok(live) => live,
|
||||
Err(e) => return (None, Step::Done(Err(e), report)),
|
||||
};
|
||||
// Calls can be made from `vc_run` on, not from the start function.
|
||||
if bridge.is_some() {
|
||||
if calls {
|
||||
live.store.data_mut().run.allow_calls(m.command_allowlist.clone());
|
||||
}
|
||||
let out = self.run_live(&mut live, input, params, limits, &deadline, bridge);
|
||||
let state = &mut live.store.data_mut().run;
|
||||
*report = std::mem::take(&mut state.report);
|
||||
// A failed call fails the run, whatever the plug-in did after it, unless the run was
|
||||
// canceled.
|
||||
match (state.call_failure.take(), out) {
|
||||
(_, Err(Error::Cancelled)) => Err(Error::Cancelled),
|
||||
(Some(e), _) => Err(e),
|
||||
(None, out) => out,
|
||||
}
|
||||
let mut left = 0;
|
||||
let call = self.start_live(&mut live, &mut left, input, params, limits, &deadline);
|
||||
self.advance(live, left, deadline, limits.clone(), call)
|
||||
}
|
||||
|
||||
/// Hands `input` and `params` to the instance `live` and runs `vc_run` → the output JSON bytes.
|
||||
fn run_live(
|
||||
/// Hands `input` and `params` to the instance `live` and starts `vc_run`, on the first slice of
|
||||
/// its instructions; the rest is left in `left`.
|
||||
fn start_live(
|
||||
&self,
|
||||
live: &mut Live,
|
||||
left: &mut u64,
|
||||
input: &[u8],
|
||||
params: &[u8],
|
||||
limits: &Limits,
|
||||
deadline: &Deadline,
|
||||
bridge: Option<&mut Bridge<'_>>,
|
||||
) -> Result<Vec<u8>> {
|
||||
) -> Result<TypedResumableCall<i64>> {
|
||||
let alloc: TypedFunc<i32, i32> = live.func("vc_alloc")?;
|
||||
let run: TypedFunc<RunArgs, i64> = live.func("vc_run")?;
|
||||
let place = |live: &mut Live, bytes: &[u8]| -> Result<usize> {
|
||||
@@ -687,8 +891,43 @@ impl Plugin {
|
||||
};
|
||||
let iptr = place(live, input)?;
|
||||
let pptr = place(live, params)?;
|
||||
let fuel = limits.fuel_base.saturating_add((input.len() as u64).saturating_mul(limits.fuel_per_byte));
|
||||
let packed = self.call_with(live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, deadline, bridge)?;
|
||||
*left = limits.fuel_base.saturating_add((input.len() as u64).saturating_mul(limits.fuel_per_byte));
|
||||
let args = (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32);
|
||||
Self::first_slice(live, left, |store| run.call_resumable(store, args))
|
||||
}
|
||||
|
||||
/// Takes `vc_run`'s `call` on until it pauses for a command call (kept, with the instance, to
|
||||
/// go on from) or ends, then → its output JSON bytes or why it has none, with its report.
|
||||
fn advance(
|
||||
&self,
|
||||
mut live: Live,
|
||||
mut left: u64,
|
||||
deadline: Deadline,
|
||||
limits: Limits,
|
||||
call: Result<TypedResumableCall<i64>>,
|
||||
) -> (Option<Paused>, Step) {
|
||||
let out = match call.and_then(|call| Self::drive(&mut live, &mut left, &deadline, call)) {
|
||||
Ok(Driven::Call(command, args, call)) => {
|
||||
let step = Step::Call { command: command.clone(), args };
|
||||
return (Some(Paused { live, left, deadline, limits, command, call }), step);
|
||||
}
|
||||
Ok(Driven::Finished(packed)) => Self::output(&live, packed, &limits, &deadline),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
let state = &mut live.store.data_mut().run;
|
||||
let report = std::mem::take(&mut state.report);
|
||||
// A failed call fails the run, whatever the plug-in did after it, unless the run was
|
||||
// canceled.
|
||||
let out = match (state.call_failure.take(), out) {
|
||||
(_, Err(Error::Cancelled)) => Err(Error::Cancelled),
|
||||
(Some(e), _) => Err(e),
|
||||
(None, out) => out,
|
||||
};
|
||||
(None, Step::Done(out, report))
|
||||
}
|
||||
|
||||
/// The output block `vc_run` returned (`packed`) → the output JSON bytes.
|
||||
fn output(live: &Live, packed: i64, limits: &Limits, deadline: &Deadline) -> Result<Vec<u8>> {
|
||||
// A cancelled run, or one past its time budget, changes nothing, also when the plug-in saw
|
||||
// `vc_cancelled` and returned.
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
//! The messages between the web build's page and its plug-in worker, and the worker's side of them
|
||||
//! ([`Worker`]).
|
||||
//!
|
||||
//! The web build checks a module being installed, and runs filters, in a Web Worker of its own: a
|
||||
//! module that loops in its start function, `vc_manifest` or `vc_run` then leaves the page
|
||||
//! responsive, and the page ends it by terminating the worker. The page sends [`ToWorker`]
|
||||
//! messages and reads [`FromWorker`] replies, each one byte buffer ([`ToWorker::encode`],
|
||||
//! [`FromWorker::decode`]): a little-endian `u32` length, a JSON header of that length, then the
|
||||
//! header's `blobs`, one after another.
|
||||
//!
|
||||
//! The worker posts [`FromWorker::Ready`] once it reads messages. It answers a
|
||||
//! [`ToWorker::Check`] with the manifest JSON a [`Plugin::load`] of the module read
|
||||
//! ([`FromWorker::Checked`]), which the page then loads the module with
|
||||
//! ([`Plugin::load_checked`]), and a [`ToWorker::Run`] with the run's progress
|
||||
//! ([`FromWorker::Progress`]), its command calls ([`FromWorker::Call`], each answered with
|
||||
//! [`ToWorker::Answer`] before the run goes on) and its end ([`FromWorker::Done`]). One worker runs
|
||||
//! one thing at a time; the page starts one per check or run.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::host::{CallFailure, LogLevel, LogLine, Report};
|
||||
use crate::runtime::{RunJob, Step};
|
||||
use crate::{Error, Limits, Plugin, Result};
|
||||
|
||||
/// The version of these messages, which [`FromWorker::Ready`] gives: a page and a worker of other
|
||||
/// builds (a worker file a browser kept from before an update) don't run plug-ins together.
|
||||
pub const PROTOCOL: u64 = 2;
|
||||
|
||||
/// What the page asks the worker to do.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ToWorker {
|
||||
/// Load `module` as [`Plugin::load`] does, running its start function, `vc_abi_version` and
|
||||
/// `vc_manifest`.
|
||||
Check { module: Vec<u8> },
|
||||
/// Run filter `module`, which a [`ToWorker::Check`] read `manifest` from, on `input` with
|
||||
/// `params` under `limits`. With `calls`, each command call it makes comes back as a
|
||||
/// [`FromWorker::Call`].
|
||||
Run { module: Vec<u8>, manifest: Vec<u8>, input: Vec<u8>, params: Vec<u8>, limits: Limits, calls: bool },
|
||||
/// The answer to the run's last [`FromWorker::Call`]: the command's result, or why it didn't run.
|
||||
Answer(std::result::Result<Value, CallFailure>),
|
||||
}
|
||||
|
||||
/// What the worker tells the page.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum FromWorker {
|
||||
/// It reads messages now, in [`PROTOCOL`] `protocol`.
|
||||
Ready { protocol: u64 },
|
||||
/// The module checked: its manifest JSON, or why it doesn't load.
|
||||
Checked(Result<Vec<u8>>),
|
||||
/// How far the run has got, as the plug-in reports it (`total` 0: not known).
|
||||
Progress { done: u64, total: u64 },
|
||||
/// The run called command `command` with `args`, and waits for the [`ToWorker::Answer`].
|
||||
Call { command: String, args: Value },
|
||||
/// The run ended: its output JSON, or why it has none, and the lines it logged.
|
||||
Done(Result<Vec<u8>>, Vec<LogLine>),
|
||||
}
|
||||
|
||||
/// `header` with `blobs` after it, as one message.
|
||||
fn pack(mut header: Value, blobs: &[&[u8]]) -> Vec<u8> {
|
||||
header["blobs"] = json!(blobs.iter().map(|b| b.len()).collect::<Vec<_>>());
|
||||
let text = header.to_string().into_bytes();
|
||||
let mut out = Vec::with_capacity(4 + text.len() + blobs.iter().map(|b| b.len()).sum::<usize>());
|
||||
out.extend_from_slice(&(text.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&text);
|
||||
for b in blobs {
|
||||
out.extend_from_slice(b);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The header and the blobs of message `msg`; `None` when it isn't one.
|
||||
fn unpack(msg: &[u8]) -> Option<(Value, Vec<Vec<u8>>)> {
|
||||
let len = u32::from_le_bytes(msg.get(..4)?.try_into().ok()?) as usize;
|
||||
let header: Value = serde_json::from_slice(msg.get(4..4usize.checked_add(len)?)?).ok()?;
|
||||
let mut at = 4 + len;
|
||||
let mut blobs = Vec::new();
|
||||
for n in header.get("blobs")?.as_array()? {
|
||||
let end = at.checked_add(usize::try_from(n.as_u64()?).ok()?)?;
|
||||
blobs.push(msg.get(at..end)?.to_vec());
|
||||
at = end;
|
||||
}
|
||||
(at == msg.len()).then_some((header, blobs))
|
||||
}
|
||||
|
||||
/// Error `e` as a header member.
|
||||
fn error_json(e: &Error) -> Value {
|
||||
let (kind, text) = match e {
|
||||
Error::Module(t) => ("module", t.as_str()),
|
||||
Error::Abi(t) => ("abi", t.as_str()),
|
||||
Error::Manifest(t) => ("manifest", t.as_str()),
|
||||
Error::Trap(t) => ("trap", t.as_str()),
|
||||
Error::Limit(t) => ("limit", t.as_str()),
|
||||
Error::Params(t) => ("params", t.as_str()),
|
||||
Error::Output(t) => ("output", t.as_str()),
|
||||
Error::Failed(t) => ("failed", t.as_str()),
|
||||
Error::NotFound(t) => ("notFound", t.as_str()),
|
||||
Error::Cancelled => ("cancelled", ""),
|
||||
Error::SafeMode => ("safeMode", ""),
|
||||
Error::NeedsApproval(t) => ("needsApproval", t.as_str()),
|
||||
Error::Io(t) => ("io", t.as_str()),
|
||||
};
|
||||
json!({ "kind": kind, "text": text })
|
||||
}
|
||||
|
||||
/// The error header member `v` gives ([`error_json`]).
|
||||
fn error_from(v: &Value) -> Option<Error> {
|
||||
let text = v.get("text")?.as_str()?.to_string();
|
||||
Some(match v.get("kind")?.as_str()? {
|
||||
"module" => Error::Module(text),
|
||||
"abi" => Error::Abi(text),
|
||||
"manifest" => Error::Manifest(text),
|
||||
"trap" => Error::Trap(text),
|
||||
"limit" => Error::Limit(text),
|
||||
"params" => Error::Params(text),
|
||||
"output" => Error::Output(text),
|
||||
"failed" => Error::Failed(text),
|
||||
"notFound" => Error::NotFound(text),
|
||||
"cancelled" => Error::Cancelled,
|
||||
"safeMode" => Error::SafeMode,
|
||||
"needsApproval" => Error::NeedsApproval(text),
|
||||
"io" => Error::Io(text),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Limits `l` as a header member.
|
||||
fn limits_json(l: &Limits) -> Value {
|
||||
json!({
|
||||
"maxModuleBytes": l.max_module_bytes,
|
||||
"maxMemoryBytes": l.max_memory_bytes,
|
||||
"maxOutputBytes": l.max_output_bytes,
|
||||
"fuelBase": l.fuel_base,
|
||||
"fuelPerByte": l.fuel_per_byte,
|
||||
"maxRecursionDepth": l.max_recursion_depth,
|
||||
"wallTimeMs": l.wall_time_ms,
|
||||
"heavyFuel": l.heavy_fuel,
|
||||
"heavyWallTimeMs": l.heavy_wall_time_ms,
|
||||
"exportFuel": l.export_fuel,
|
||||
"exportWallTimeMs": l.export_wall_time_ms,
|
||||
})
|
||||
}
|
||||
|
||||
/// The limits header member `v` gives ([`limits_json`]).
|
||||
fn limits_from(v: &Value) -> Option<Limits> {
|
||||
let n = |k: &str| v.get(k).and_then(Value::as_u64);
|
||||
let size = |k: &str| n(k).and_then(|x| usize::try_from(x).ok());
|
||||
Some(Limits {
|
||||
max_module_bytes: size("maxModuleBytes")?,
|
||||
max_memory_bytes: size("maxMemoryBytes")?,
|
||||
max_output_bytes: size("maxOutputBytes")?,
|
||||
fuel_base: n("fuelBase")?,
|
||||
fuel_per_byte: n("fuelPerByte")?,
|
||||
max_recursion_depth: size("maxRecursionDepth")?,
|
||||
wall_time_ms: n("wallTimeMs")?,
|
||||
heavy_fuel: n("heavyFuel")?,
|
||||
heavy_wall_time_ms: n("heavyWallTimeMs")?,
|
||||
export_fuel: n("exportFuel")?,
|
||||
export_wall_time_ms: n("exportWallTimeMs")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn level_name(l: LogLevel) -> &'static str {
|
||||
match l {
|
||||
LogLevel::Error => "error",
|
||||
LogLevel::Warn => "warn",
|
||||
LogLevel::Info => "info",
|
||||
LogLevel::Debug => "debug",
|
||||
}
|
||||
}
|
||||
|
||||
fn level_from(name: &str) -> Option<LogLevel> {
|
||||
Some(match name {
|
||||
"error" => LogLevel::Error,
|
||||
"warn" => LogLevel::Warn,
|
||||
"info" => LogLevel::Info,
|
||||
"debug" => LogLevel::Debug,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl ToWorker {
|
||||
/// The message, as the page posts it.
|
||||
pub fn encode(&self) -> Vec<u8> {
|
||||
match self {
|
||||
ToWorker::Check { module } => pack(json!({"kind": "check"}), &[module]),
|
||||
ToWorker::Run { module, manifest, input, params, limits, calls } => {
|
||||
pack(json!({"kind": "run", "limits": limits_json(limits), "calls": calls}), &[module, manifest, input, params])
|
||||
}
|
||||
// The result goes in a blob of its own, so it may nest as deep as a command's result.
|
||||
ToWorker::Answer(Ok(result)) => pack(json!({"kind": "answer"}), &[result.to_string().as_bytes()]),
|
||||
ToWorker::Answer(Err(f)) => pack(json!({"kind": "answer", "failure": {"code": f.code, "why": f.why}}), &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The message `msg` holds; `None` when it holds none.
|
||||
pub fn decode(msg: &[u8]) -> Option<ToWorker> {
|
||||
let (h, mut blobs) = unpack(msg)?;
|
||||
match (h.get("kind")?.as_str()?, blobs.len()) {
|
||||
("check", 1) => Some(ToWorker::Check { module: blobs.pop()? }),
|
||||
("run", 4) => {
|
||||
let (params, input, manifest, module) = (blobs.pop()?, blobs.pop()?, blobs.pop()?, blobs.pop()?);
|
||||
let limits = limits_from(h.get("limits")?)?;
|
||||
Some(ToWorker::Run { module, manifest, input, params, limits, calls: h.get("calls")?.as_bool()? })
|
||||
}
|
||||
("answer", n) => match (blobs.pop(), h.get("failure")) {
|
||||
(Some(result), None) if n == 1 => Some(ToWorker::Answer(Ok(serde_json::from_slice(&result).ok()?))),
|
||||
(None, Some(f)) => {
|
||||
let code = i32::try_from(f.get("code")?.as_i64()?).ok()?;
|
||||
Some(ToWorker::Answer(Err(CallFailure { code, why: f.get("why")?.as_str()?.to_string() })))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorker {
|
||||
/// The message, as the worker posts it.
|
||||
pub fn encode(&self) -> Vec<u8> {
|
||||
match self {
|
||||
FromWorker::Ready { protocol } => pack(json!({"kind": "ready", "protocol": protocol}), &[]),
|
||||
FromWorker::Checked(Ok(manifest)) => pack(json!({"kind": "checked"}), &[manifest]),
|
||||
FromWorker::Checked(Err(e)) => pack(json!({"kind": "checked", "error": error_json(e)}), &[]),
|
||||
FromWorker::Progress { done, total } => pack(json!({"kind": "progress", "done": done, "total": total}), &[]),
|
||||
// The arguments go in a blob of their own, so they may nest as deep as a call's arguments.
|
||||
FromWorker::Call { command, args } => pack(json!({"kind": "call", "command": command}), &[args.to_string().as_bytes()]),
|
||||
FromWorker::Done(out, lines) => {
|
||||
let lines: Vec<Value> = lines.iter().map(|l| json!([level_name(l.level), l.text])).collect();
|
||||
match out {
|
||||
Ok(output) => pack(json!({"kind": "done", "lines": lines}), &[output]),
|
||||
Err(e) => pack(json!({"kind": "done", "lines": lines, "error": error_json(e)}), &[]),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The message `msg` holds; `None` when it holds none.
|
||||
pub fn decode(msg: &[u8]) -> Option<FromWorker> {
|
||||
let (h, mut blobs) = unpack(msg)?;
|
||||
let error = h.get("error");
|
||||
match (h.get("kind")?.as_str()?, blobs.len(), error) {
|
||||
("ready", 0, None) => Some(FromWorker::Ready { protocol: h.get("protocol")?.as_u64()? }),
|
||||
("checked", 1, None) => Some(FromWorker::Checked(Ok(blobs.pop()?))),
|
||||
("checked", 0, Some(e)) => Some(FromWorker::Checked(Err(error_from(e)?))),
|
||||
("progress", 0, None) => Some(FromWorker::Progress { done: h.get("done")?.as_u64()?, total: h.get("total")?.as_u64()? }),
|
||||
("call", 1, None) => {
|
||||
Some(FromWorker::Call { command: h.get("command")?.as_str()?.to_string(), args: serde_json::from_slice(&blobs.pop()?).ok()? })
|
||||
}
|
||||
("done", n, e) => {
|
||||
let mut lines = Vec::new();
|
||||
for l in h.get("lines")?.as_array()? {
|
||||
let (level, text) = (l.get(0)?.as_str()?, l.get(1)?.as_str()?);
|
||||
lines.push(LogLine { level: level_from(level)?, text: text.to_string() });
|
||||
}
|
||||
let out = match (n, e) {
|
||||
(1, None) => Ok(blobs.pop()?),
|
||||
(0, Some(e)) => Err(error_from(e)?),
|
||||
_ => return None,
|
||||
};
|
||||
Some(FromWorker::Done(out, lines))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the `lines` a run of plug-in `id` logged in a worker to the app's log, as a run on the
|
||||
/// page writes them.
|
||||
pub fn log_lines(id: &str, lines: &[LogLine]) {
|
||||
for l in lines {
|
||||
log::log!(target: "vectorcraft_plugins", l.level.log_level(), "{id}: {}", l.text);
|
||||
}
|
||||
}
|
||||
|
||||
/// The worker's side: it reads the page's messages ([`Worker::handle`]) and posts its replies with
|
||||
/// the function it was made with.
|
||||
pub struct Worker {
|
||||
post: Rc<dyn Fn(Vec<u8>)>,
|
||||
/// The run waiting for the answer to a command call, and its plug-in.
|
||||
run: Option<(Plugin, RunJob)>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
/// A worker that posts each reply with `post`.
|
||||
pub fn new(post: Rc<dyn Fn(Vec<u8>)>) -> Worker {
|
||||
Worker { post, run: None }
|
||||
}
|
||||
|
||||
/// Tells the page that it reads messages now ([`FromWorker::Ready`]).
|
||||
pub fn ready(&self) {
|
||||
(self.post)(FromWorker::Ready { protocol: PROTOCOL }.encode());
|
||||
}
|
||||
|
||||
/// Does what message `msg` asks. A message it doesn't read, and an answer when no run waits for
|
||||
/// one, end what it is doing with an error.
|
||||
pub fn handle(&mut self, msg: &[u8]) {
|
||||
match ToWorker::decode(msg) {
|
||||
Some(ToWorker::Check { module }) => {
|
||||
let checked = Plugin::load(&module, Limits::default()).map(|p| p.manifest_text().to_vec());
|
||||
(self.post)(FromWorker::Checked(checked).encode());
|
||||
}
|
||||
Some(ToWorker::Run { module, manifest, input, params, limits, calls }) => {
|
||||
self.run = None;
|
||||
let plugin = match Plugin::load_checked(&module, limits.clone(), &manifest) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return self.done(Err(e), Report::default()),
|
||||
};
|
||||
let (job, step) = self.scoped(|| plugin.begin_run(&input, ¶ms, &limits, calls));
|
||||
self.step(plugin, job, step);
|
||||
}
|
||||
Some(ToWorker::Answer(answer)) => {
|
||||
let Some((plugin, mut job)) = self.run.take() else {
|
||||
return self.done(Err(Error::Failed(unexpected())), Report::default());
|
||||
};
|
||||
let step = self.scoped(|| plugin.resume_run(&mut job, answer));
|
||||
self.step(plugin, job, step);
|
||||
}
|
||||
None => {
|
||||
self.run = None;
|
||||
self.done(Err(Error::Failed(unexpected())), Report::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` with the run's progress reports posted as [`FromWorker::Progress`].
|
||||
fn scoped<T>(&self, f: impl FnOnce() -> T) -> T {
|
||||
let post = Rc::clone(&self.post);
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = Rc::new(move |done, total, _| post(FromWorker::Progress { done, total }.encode()));
|
||||
vectorcraft_doc::cancel::scope(&vectorcraft_doc::cancel::CancelToken::new(), Some(sink), f)
|
||||
}
|
||||
|
||||
/// Posts where the run of `plugin` is: a command call (keeping the run to go on with), or its end.
|
||||
fn step(&mut self, plugin: Plugin, job: RunJob, step: Step) {
|
||||
match step {
|
||||
Step::Call { command, args } => {
|
||||
(self.post)(FromWorker::Call { command, args }.encode());
|
||||
self.run = Some((plugin, job));
|
||||
}
|
||||
Step::Done(out, report) => self.done(out, report),
|
||||
}
|
||||
}
|
||||
|
||||
fn done(&self, out: Result<Vec<u8>>, report: Report) {
|
||||
(self.post)(FromWorker::Done(out, report.lines).encode());
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the worker, or the page, ends what it is doing when a message makes no sense where it is: a
|
||||
/// bug, as a thread that stops is.
|
||||
const UNEXPECTED: &str = "internal error: a message between the page and the plug-in worker came out of turn (please report this bug)";
|
||||
|
||||
/// [`UNEXPECTED`], for an error.
|
||||
pub fn unexpected() -> String {
|
||||
UNEXPECTED.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::RefCell;
|
||||
|
||||
use super::*;
|
||||
use crate::wat as tpl;
|
||||
|
||||
const INPUT: &str = r#"{"objects":[]}"#;
|
||||
|
||||
/// A worker whose replies are kept, decoded, in the cell it gives.
|
||||
fn worker() -> (Worker, Rc<RefCell<Vec<FromWorker>>>) {
|
||||
let got = Rc::new(RefCell::new(Vec::new()));
|
||||
let kept = Rc::clone(&got);
|
||||
let w = Worker::new(Rc::new(move |m: Vec<u8>| kept.borrow_mut().push(FromWorker::decode(&m).expect("a reply the page reads"))));
|
||||
(w, got)
|
||||
}
|
||||
|
||||
fn take(got: &Rc<RefCell<Vec<FromWorker>>>) -> Vec<FromWorker> {
|
||||
std::mem::take(&mut *got.borrow_mut())
|
||||
}
|
||||
|
||||
/// A filter that calls `select.all` with `{"a":1}` and returns the call's result.
|
||||
fn caller() -> Vec<u8> {
|
||||
let calls = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))
|
||||
(import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32)))
|
||||
(data (i32.const 0x2000) "select.all")
|
||||
(data (i32.const 0x2100) "{\22a\22:1}")"#;
|
||||
let manifest = r#"{"id":"test.worker.call","name":"Caller","kind":"filter","api":2,"permissions":["doc.read","doc.write","commands"],"commandAllowlist":["select.all"]}"#;
|
||||
let run = "(if (i32.ne (call $vc_call (i32.const 0x2000) (i32.const 10) (i32.const 0x2100) (i32.const 7)) (i32.const 0)) (then unreachable)) \
|
||||
(i64.or (i64.shl (i64.extend_i32_u (call $vc_call_result (i32.const 0x3000) (i32.const 64))) (i64.const 32)) (i64.const 0x3000))";
|
||||
wat::parse_str(tpl::module(manifest, run, calls, 1)).unwrap()
|
||||
}
|
||||
|
||||
fn checked(w: &mut Worker, got: &Rc<RefCell<Vec<FromWorker>>>, module: &[u8]) -> Vec<u8> {
|
||||
w.handle(&ToWorker::Check { module: module.to_vec() }.encode());
|
||||
match take(got).as_slice() {
|
||||
[FromWorker::Checked(Ok(manifest))] => manifest.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_msg(module: &[u8], manifest: &[u8], calls: bool) -> Vec<u8> {
|
||||
let limits = Limits::default();
|
||||
ToWorker::Run { module: module.to_vec(), manifest: manifest.to_vec(), input: INPUT.into(), params: b"{}".to_vec(), limits, calls }.encode()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_message_reads_back_as_it_was_sent() {
|
||||
let to = [
|
||||
ToWorker::Check { module: b"\0asm".to_vec() },
|
||||
ToWorker::Run {
|
||||
module: vec![1, 2],
|
||||
manifest: b"{}".to_vec(),
|
||||
input: vec![],
|
||||
params: vec![3],
|
||||
limits: Limits { wall_time_ms: 7, ..Limits::default() },
|
||||
calls: true,
|
||||
},
|
||||
ToWorker::Answer(Ok(json!({"n": [1, "two"]}))),
|
||||
ToWorker::Answer(Err(CallFailure { code: -3, why: "no".into() })),
|
||||
];
|
||||
for m in to {
|
||||
assert_eq!(ToWorker::decode(&m.encode()), Some(m));
|
||||
}
|
||||
let line = LogLine { level: LogLevel::Warn, text: "careful".into() };
|
||||
let from = [
|
||||
FromWorker::Ready { protocol: PROTOCOL },
|
||||
FromWorker::Checked(Ok(b"{\"id\":\"x\"}".to_vec())),
|
||||
FromWorker::Checked(Err(Error::Module("bad".into()))),
|
||||
FromWorker::Progress { done: 3, total: 0 },
|
||||
FromWorker::Call { command: "select.all".into(), args: json!({}) },
|
||||
FromWorker::Done(Ok(vec![]), vec![line.clone()]),
|
||||
FromWorker::Done(Err(Error::Cancelled), vec![]),
|
||||
FromWorker::Done(Err(Error::Limit("time budget".into())), vec![line]),
|
||||
];
|
||||
for m in from {
|
||||
assert_eq!(FromWorker::decode(&m.encode()), Some(m));
|
||||
}
|
||||
}
|
||||
|
||||
/// A call's arguments and a command's result read back at the deepest nesting a JSON parse
|
||||
/// takes: the message adds no level around them.
|
||||
#[test]
|
||||
fn arguments_and_results_as_deep_as_json_takes_read_back() {
|
||||
let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
|
||||
let deepest = (1..512).take_while(|&n| serde_json::from_str::<Value>(&nested(n)).is_ok()).last().unwrap();
|
||||
assert!(deepest < 511, "the parse has a depth limit");
|
||||
let value: Value = serde_json::from_str(&nested(deepest)).unwrap();
|
||||
let call = FromWorker::Call { command: "select.all".into(), args: value.clone() };
|
||||
assert_eq!(FromWorker::decode(&call.encode()), Some(call));
|
||||
let answer = ToWorker::Answer(Ok(value));
|
||||
assert_eq!(ToWorker::decode(&answer.encode()), Some(answer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_or_padded_message_is_not_read() {
|
||||
let m = ToWorker::Check { module: b"\0asm".to_vec() }.encode();
|
||||
assert_eq!(ToWorker::decode(&m[..m.len() - 1]), None);
|
||||
assert_eq!(ToWorker::decode(&[m.as_slice(), &[0]].concat()), None);
|
||||
assert_eq!(ToWorker::decode(&[]), None);
|
||||
assert_eq!(FromWorker::decode(&m), None, "a request is not a reply");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_checked_module_loads_on_the_page_without_running_its_code() {
|
||||
let (mut w, got) = worker();
|
||||
w.ready();
|
||||
assert_eq!(take(&got), [FromWorker::Ready { protocol: PROTOCOL }]);
|
||||
let module = caller();
|
||||
let manifest = checked(&mut w, &got, &module);
|
||||
let page = Plugin::load_checked(&module, Limits::default(), &manifest).unwrap();
|
||||
assert_eq!(page.manifest(), Plugin::load(&module, Limits::default()).unwrap().manifest());
|
||||
// A module that traps before its manifest can be read is refused in the worker.
|
||||
let trapping =
|
||||
wat::parse_str(tpl::module(&tpl::manifest("test.worker.trap", "filter", "{}"), tpl::ECHO, "(start $s) (func $s unreachable)", 1))
|
||||
.unwrap();
|
||||
w.handle(&ToWorker::Check { module: trapping }.encode());
|
||||
assert!(matches!(take(&got).as_slice(), [FromWorker::Checked(Err(Error::Trap(_)))]));
|
||||
}
|
||||
|
||||
/// A module that carries its manifest in its custom section, with neither `vc_abi_version` nor
|
||||
/// `vc_manifest`, is checked in a worker and loads on the page from that section.
|
||||
#[test]
|
||||
fn a_module_with_a_manifest_section_loads_on_the_page_from_its_section() {
|
||||
let (mut w, got) = worker();
|
||||
let section = r#"{"id":"test.worker.section","name":"Sectioned","version":"1","kind":"filter","abi":1}"#;
|
||||
let module = wat::parse_str(tpl::sectioned(section, tpl::ECHO, "", 1)).unwrap();
|
||||
let manifest = checked(&mut w, &got, &module);
|
||||
assert_eq!(manifest, section.as_bytes(), "the worker sends the section's manifest");
|
||||
let page = Plugin::load_checked(&module, Limits::default(), &manifest).unwrap();
|
||||
assert_eq!(page.manifest(), Plugin::load(&module, Limits::default()).unwrap().manifest());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_load_checks_the_manifest_it_is_given() {
|
||||
let module = caller();
|
||||
// The manifest lists `commands`, which the module's imports need; one without it is refused,
|
||||
// as `Plugin::load` refuses it.
|
||||
let without = r#"{"id":"test.worker.call","name":"Caller","kind":"filter","api":2,"permissions":["doc.read"]}"#;
|
||||
assert!(Plugin::load_checked(&module, Limits::default(), without.as_bytes()).is_err());
|
||||
assert!(Plugin::load_checked(&module, Limits::default(), b"not json").is_err());
|
||||
let no_run = wat::parse_str(r#"(module (memory (export "memory") 1) (func (export "vc_abi_version") (result i32) (i32.const 1)))"#).unwrap();
|
||||
assert!(matches!(Plugin::load_checked(&no_run, Limits::default(), b"{}"), Err(Error::Abi(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_comes_back_for_each_command_call_and_ends_with_its_output() {
|
||||
let (mut w, got) = worker();
|
||||
let module = caller();
|
||||
let manifest = checked(&mut w, &got, &module);
|
||||
w.handle(&run_msg(&module, &manifest, true));
|
||||
assert_eq!(take(&got), [FromWorker::Call { command: "select.all".into(), args: json!({"a": 1}) }]);
|
||||
w.handle(&ToWorker::Answer(Ok(json!({"n": 1}))).encode());
|
||||
assert_eq!(take(&got), [FromWorker::Done(Ok(br#"{"n":1}"#.to_vec()), vec![])]);
|
||||
// The output equals what a run on the page with the same answer returns.
|
||||
let page = Plugin::load(&module, Limits::default()).unwrap();
|
||||
let mut bridge = |_: &str, _: &Value| Ok(json!({"n": 1}));
|
||||
assert_eq!(page.run_calling(INPUT.as_bytes(), b"{}", page.limits(), &mut bridge).0.unwrap(), br#"{"n":1}"#);
|
||||
}
|
||||
|
||||
/// A run in the worker keeps to the memory limit the page sends with it, as a run on the page
|
||||
/// with those limits does.
|
||||
#[test]
|
||||
fn a_run_keeps_to_the_memory_limit_it_is_sent() {
|
||||
let (mut w, got) = worker();
|
||||
let module = wat::parse_str(tpl::module(&tpl::manifest("test.worker.memory", "filter", "{}"), tpl::ECHO, "", 2)).unwrap();
|
||||
let manifest = checked(&mut w, &got, &module);
|
||||
let limits = Limits { max_memory_bytes: 1 << 16, ..Limits::default() };
|
||||
let msg = ToWorker::Run { module, manifest, input: INPUT.into(), params: b"{}".to_vec(), limits, calls: false };
|
||||
w.handle(&msg.encode());
|
||||
assert!(matches!(take(&got).as_slice(), [FromWorker::Done(Err(_), _)]), "two pages don't fit in one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_call_fails_the_run_with_the_reason() {
|
||||
let (mut w, got) = worker();
|
||||
let module = caller();
|
||||
let manifest = checked(&mut w, &got, &module);
|
||||
w.handle(&run_msg(&module, &manifest, true));
|
||||
take(&got);
|
||||
w.handle(&ToWorker::Answer(Err(CallFailure { code: crate::host::CALL_COMMAND_FAILED, why: "nope".into() })).encode());
|
||||
match take(&got).as_slice() {
|
||||
[FromWorker::Done(Err(Error::Failed(why)), _)] => assert!(why.contains("nope"), "{why}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_no_run_waits_for_and_an_unread_message_end_with_an_error() {
|
||||
let (mut w, got) = worker();
|
||||
w.handle(&ToWorker::Answer(Ok(json!(1))).encode());
|
||||
assert!(matches!(take(&got).as_slice(), [FromWorker::Done(Err(Error::Failed(_)), _)]));
|
||||
let module = caller();
|
||||
let manifest = checked(&mut w, &got, &module);
|
||||
w.handle(&run_msg(&module, &manifest, true));
|
||||
take(&got);
|
||||
w.handle(b"junk");
|
||||
assert!(matches!(take(&got).as_slice(), [FromWorker::Done(Err(Error::Failed(_)), _)]));
|
||||
// The run that waited is gone: a late answer finds none.
|
||||
w.handle(&ToWorker::Answer(Ok(json!(1))).encode());
|
||||
assert!(matches!(take(&got).as_slice(), [FromWorker::Done(Err(Error::Failed(_)), _)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_is_posted_while_the_run_computes() {
|
||||
let (mut w, got) = worker();
|
||||
let manifest = r#"{"id":"test.worker.progress","name":"P","kind":"filter","api":2,"permissions":["doc.read","progress"]}"#;
|
||||
let first = "(call $vc_progress (i64.const 1) (i64.const 4)) (call $vc_progress (i64.const 3) (i64.const 4))";
|
||||
let module = wat::parse_str(tpl::with_imports(manifest, tpl::HOST_IMPORTS, first, INPUT)).unwrap();
|
||||
let text = checked(&mut w, &got, &module);
|
||||
w.handle(&run_msg(&module, &text, false));
|
||||
let replies = take(&got);
|
||||
let shares: Vec<_> =
|
||||
replies.iter().filter_map(|r| if let FromWorker::Progress { done, total } = r { Some((*done, *total)) } else { None }).collect();
|
||||
assert!(shares.len() >= 2 && shares.windows(2).all(|w| w[0].0 < w[1].0), "{replies:?}");
|
||||
assert!(matches!(replies.last(), Some(FromWorker::Done(Ok(_), _))), "{replies:?}");
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,16 @@ fn a_failed_command_fails_the_run_with_its_reason() {
|
||||
assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into())));
|
||||
}
|
||||
|
||||
/// A call that panics in the host fails the run with an error, as a panic in the runtime does, and
|
||||
/// the caller's thread goes on.
|
||||
#[test]
|
||||
fn a_call_that_panics_fails_the_run() {
|
||||
let p = calling("test.call.panics", &format!("(drop {})", select_all()));
|
||||
let (out, seen) = run_with(&p, |_| panic!("the command broke"));
|
||||
assert_eq!(out, Err(Error::Trap("the runtime panicked".into())));
|
||||
assert_eq!(seen.len(), 1);
|
||||
}
|
||||
|
||||
/// After the run's first failed call, a plug-in that goes on calling gets [`CALL_NO_CONTEXT`] for
|
||||
/// each call and the host makes none of them; the run fails with the first call's reason.
|
||||
#[test]
|
||||
|
||||
@@ -30,6 +30,7 @@ mod meshwarp;
|
||||
mod movedstroke;
|
||||
mod objectfx;
|
||||
mod paintedbrush;
|
||||
mod paintedlook;
|
||||
mod placed_document;
|
||||
mod rasterize;
|
||||
mod setup;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! A live-effect plug-in that declares `appearanceOutput` gives each piece it returns an opacity, a
|
||||
//! blending mode and effects, and the canvas draws the piece with them. A refused look (an unknown
|
||||
//! blending mode, a plug-in effect) leaves the source as it is.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use crate::{RenderOptions, Renderer};
|
||||
|
||||
/// A 20 × 20 square at `x`, 40.
|
||||
fn square_at(x: f64) -> PathData {
|
||||
PathData::single(SubPath::polyline(&[Point::new(x, 40.0), Point::new(x + 20.0, 40.0), Point::new(x + 20.0, 60.0), Point::new(x, 60.0)], true))
|
||||
}
|
||||
|
||||
/// The output of a plug-in that returns one piece: the square at `x`, 40 filled red, with `look`'s
|
||||
/// keys added to it.
|
||||
fn output(x: f64, look: &serde_json::Value) -> String {
|
||||
let red = serde_json::to_value(Paint::solid(Color::rgb(1.0, 0.0, 0.0))).unwrap();
|
||||
let mut piece = json!({"path": square_at(x), "fills": [red]});
|
||||
if let (Some(p), Some(l)) = (piece.as_object_mut(), look.as_object()) {
|
||||
p.extend(l.clone());
|
||||
}
|
||||
json!({ "objects": [piece] }).to_string()
|
||||
}
|
||||
|
||||
/// The manifest of live-effect plug-in `id`, which declares `appearanceOutput`.
|
||||
fn manifest(id: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#)
|
||||
}
|
||||
|
||||
/// Installs live-effect plug-in `id`, which returns one piece: the square at 120, 40 filled red,
|
||||
/// with `look`'s keys added to it.
|
||||
fn install(id: &str, look: serde_json::Value) {
|
||||
let module = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest(id), &output(120.0, &look))).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
}
|
||||
|
||||
/// Installs live-effect plug-in `id` as [`install`] does, except that it returns the square at 160,
|
||||
/// 40 when its input holds the text `moved`.
|
||||
fn install_moving(id: &str, look: serde_json::Value, moved: &str) {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let module = tpl::when_given_else(&manifest(id), tpl::Given::Input, moved, &output(160.0, &look), &output(120.0, &look));
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(module).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
/// A document with a blue rectangle over all of it and, above it, the square at `x`, 40 filled
|
||||
/// green with live-effect plug-in `plugin` as its own effect.
|
||||
fn document(plugin: &str, x: f64) -> Document {
|
||||
let mut d = Document::new(300.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let blue = Node::path(
|
||||
d.alloc_id(),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 100.0)),
|
||||
Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0),
|
||||
);
|
||||
d.insert(Some(l), 0, blue).unwrap();
|
||||
let mut ap = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0);
|
||||
ap.effects = vec![Effect { id: format!("plugin.{plugin}"), params: json!({}), visible: true }];
|
||||
let n = Node::path(d.alloc_id(), square_at(x), ap);
|
||||
d.insert(Some(l), usize::MAX, n).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The color a new renderer draws `d` with at (`x`, `y`).
|
||||
fn pixel(d: &Document, x: f64, y: f64) -> [u8; 4] {
|
||||
pixel_with(&mut Renderer::new(), d, x, y)
|
||||
}
|
||||
|
||||
/// The color renderer `r` draws `d` with at (`x`, `y`).
|
||||
fn pixel_with(r: &mut Renderer, d: &Document, x: f64, y: f64) -> [u8; 4] {
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
r.render(d, 1, 1, Affine::translate((-x, -y)), &opts).pixel(0, 0)
|
||||
}
|
||||
|
||||
fn near(got: [u8; 4], want: [u8; 3]) -> bool {
|
||||
got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8)
|
||||
}
|
||||
|
||||
/// A piece at 50% opacity with Multiply draws red multiplied with the blue under it (black) at
|
||||
/// half strength: half blue. Moved in the same document and drawn by the same renderer, the source
|
||||
/// runs the plug-in again, which now returns the square at 160, 40, and the new piece draws the
|
||||
/// same way. Without the look the piece is plain red.
|
||||
#[test]
|
||||
fn a_piece_s_opacity_and_blending_mode_draw_and_survive_a_rerun() {
|
||||
const ID: &str = "test.render.paintedlook.multiply";
|
||||
install_moving(ID, json!({"opacity": 0.5, "blend": "Multiply"}), "33.25");
|
||||
let mut d = document(ID, 0.0);
|
||||
let source = d.layers[0].children().and_then(|c| c.last()).map(|n| n.id).unwrap();
|
||||
let mut r = Renderer::new();
|
||||
let p = pixel_with(&mut r, &d, 130.0, 50.0);
|
||||
assert!(near(p, [0, 0, 128]), "before the move: {p:?}");
|
||||
assert!(near(pixel_with(&mut r, &d, 10.0, 50.0), [0, 0, 255]), "the source is not drawn");
|
||||
d.node_mut(source).unwrap().transform(Affine::translate((33.25, 0.0)), false);
|
||||
let p = pixel_with(&mut r, &d, 170.0, 50.0);
|
||||
assert!(near(p, [0, 0, 128]), "after the move: {p:?}");
|
||||
assert!(near(pixel_with(&mut r, &d, 130.0, 50.0), [0, 0, 255]), "the earlier piece is not drawn");
|
||||
assert!(near(pixel_with(&mut r, &d, 43.0, 50.0), [0, 0, 255]), "the moved source is not drawn");
|
||||
assert_eq!(vectorcraft_plugins::effect::last_error(ID), None);
|
||||
install(ID, json!({}));
|
||||
assert!(near(pixel(&document(ID, 4.0), 130.0, 50.0), [255, 0, 0]));
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
}
|
||||
|
||||
/// A piece's geometry effect reshapes it: Offset Path by 10 pt draws red 5 pt left of the square.
|
||||
#[test]
|
||||
fn a_piece_s_geometry_effect_draws_on_it() {
|
||||
const ID: &str = "test.render.paintedlook.offset";
|
||||
install(ID, json!({"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]}));
|
||||
let d = document(ID, 0.0);
|
||||
assert!(near(pixel(&d, 115.0, 50.0), [255, 0, 0]), "{:?}", pixel(&d, 115.0, 50.0));
|
||||
assert!(near(pixel(&d, 130.0, 50.0), [255, 0, 0]));
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
}
|
||||
|
||||
/// An unknown blending mode, a plug-in effect (this one itself) and too many effects refuse the
|
||||
/// whole result: the source draws as it is, green at its own place, with no piece, and the plug-in
|
||||
/// reports the field.
|
||||
#[test]
|
||||
fn a_refused_look_leaves_the_source_unchanged() {
|
||||
for (name, look, field) in [
|
||||
("blend", json!({"blend": "multiply"}), "objects[0].blend"),
|
||||
("self", json!({"effects": [{"id": "plugin.test.render.paintedlook.self"}]}), "objects[0].effects[0]"),
|
||||
("many", json!({"effects": vec![json!({"id": "stylize.dropShadow"}); 17]}), "objects[0].effects"),
|
||||
] {
|
||||
let id = format!("test.render.paintedlook.{name}");
|
||||
install(&id, look);
|
||||
let d = document(&id, 0.0);
|
||||
assert!(near(pixel(&d, 10.0, 50.0), [0, 255, 0]), "{name}: the source draws");
|
||||
assert!(near(pixel(&d, 130.0, 50.0), [0, 0, 255]), "{name}: no piece");
|
||||
let e = vectorcraft_plugins::effect::last_error(&id).unwrap_or_default();
|
||||
assert!(e.contains(field), "{name}: {e}");
|
||||
vectorcraft_plugins::registry::remove(&id);
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,7 @@ features! {
|
||||
Notify "notify" Language,
|
||||
OperatorOverloading "operatorOverloading" HostOnly,
|
||||
Preferences "preferences" Language,
|
||||
Reflection "reflection" HostOnly,
|
||||
Reflection "reflection" Language,
|
||||
ScriptuiDialog "scriptui.dialog" Dialogs,
|
||||
ScriptuiDrawing "scriptui.drawing" Dialogs,
|
||||
ScriptuiPalette "scriptui.palette" HostOnly,
|
||||
|
||||
@@ -212,6 +212,13 @@ fn directives_are_read_at_the_start_of_a_line_in_both_forms() {
|
||||
assert_eq!(r.needs, [Need::Language], "VectorCraft runs #targetengine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflection_needs_only_the_language() {
|
||||
let r = report("var p = obj.reflect.properties;\nvar m = $.reflect.find('write');\n");
|
||||
assert_eq!(feature(&r, "reflection").map(|f| f.lines.clone()), Some(vec![1, 2]));
|
||||
assert_eq!(r.needs, [Need::Language], "VectorCraft runs reflect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_byte_order_mark_and_every_line_break_are_read() {
|
||||
// U+2028 ends line 2.
|
||||
|
||||
@@ -23,11 +23,10 @@ mod tests {
|
||||
let ns = "<!DOCTYPE svg [<!ENTITY ns_svg \"http://www.w3.org/2000/svg\">]><svg xmlns=\"&ns_svg;\"/>";
|
||||
assert!(!expansion_too_large(ns));
|
||||
assert!(!expansion_too_large("<svg a=\"& \"/>"));
|
||||
// Many `&`s with no `;` after them are read in linear time.
|
||||
// Many `&`s with no `;` after them expand to nothing. The guard's own tests in craft-libs
|
||||
// check that it reads them in linear time.
|
||||
let ampersands = format!("<!DOCTYPE svg [<!ENTITY a \"x\">]><svg id=\"{}\"/>", "&".repeat(1 << 20));
|
||||
let start = std::time::Instant::now();
|
||||
assert!(!expansion_too_large(&ersands));
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -56,6 +56,19 @@ pub(crate) struct Edits {
|
||||
styles: HashMap<roxmltree::NodeId, (usize, bool, String)>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The numbers [`Edits::id`] has tried for a made-up id on this thread, taken or not: the
|
||||
/// work of making up ids.
|
||||
static TRIED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Count one number tried for a made-up id in [`TRIED`]; nothing outside tests.
|
||||
fn tried() {
|
||||
#[cfg(test)]
|
||||
TRIED.set(TRIED.get() + 1);
|
||||
}
|
||||
|
||||
impl Edits {
|
||||
fn insert(&mut self, at: usize, text: String) {
|
||||
self.list.push((at..at, text));
|
||||
@@ -71,8 +84,10 @@ impl Edits {
|
||||
return id.clone();
|
||||
}
|
||||
let taken = self.taken.get_or_insert_with(|| named_made_up_ids(n.document()));
|
||||
tried();
|
||||
while taken.contains(&self.next) {
|
||||
self.next += 1;
|
||||
tried();
|
||||
}
|
||||
let id = format!("{MADE_UP_ID}{}", self.next);
|
||||
self.next += 1;
|
||||
@@ -491,7 +506,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A file that already holds the made-up ids does not make each new id try them all again:
|
||||
/// 5,000 ids made up past 50,000 taken ones take a moment, not 250 million tries.
|
||||
/// 5,000 ids made up past 50,000 taken ones try 55,000 numbers, not 250 million.
|
||||
#[test]
|
||||
fn made_up_ids_skip_the_taken_ones_once() {
|
||||
let taken: String = (0..50_000).map(|i| format!("<g id=\"{MADE_UP_ID}{i}\"/>")).collect();
|
||||
@@ -500,9 +515,9 @@ mod tests {
|
||||
let doc = roxmltree::Document::parse(&svg).unwrap();
|
||||
let rects: Vec<XNode> = doc.descendants().filter(|n| n.has_tag_name("rect")).collect();
|
||||
let mut edits = Edits::default();
|
||||
let start = std::time::Instant::now();
|
||||
TRIED.set(0);
|
||||
let ids: Vec<String> = rects.iter().map(|n| edits.id(&svg, *n)).collect();
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(1), "{:?}", start.elapsed());
|
||||
assert_eq!(TRIED.get(), 55_000);
|
||||
assert_eq!(ids.first().map(String::as_str), Some(format!("{MADE_UP_ID}50000").as_str()));
|
||||
assert_eq!(ids.iter().collect::<HashSet<_>>().len(), ids.len());
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! The optional craft-fonts build input (https://github.com/storytold/craft-fonts,
|
||||
//! `docs/integration.md`): with `CRAFT_FONTS_DIR=<checkout>` set, every font in its
|
||||
//! `fonts/manifest.txt` is embedded as `CRAFT_FONTS` (the framework's `craft_fonts_build::Embed`);
|
||||
//! unset, `CRAFT_FONTS` is empty and the app uses its own and the installed fonts.
|
||||
//! unset, `CRAFT_FONTS` is empty and the app uses its own and the installed fonts. Desktop builds
|
||||
//! also embed the Noto Sans Condensed SemiBold row of the checkout's `fonts/latin-manifest.txt`
|
||||
//! (`Embed::tab_face`), which document tab titles draw in; a checkout without it gives a warning.
|
||||
//! `CRAFT_FONTS_REQUIRED=1` turns a bad checkout into a build error (release builds). Nothing is
|
||||
//! fetched: the build reads only the local checkout.
|
||||
//!
|
||||
@@ -40,7 +42,10 @@ fn main() {
|
||||
None => embed,
|
||||
}
|
||||
};
|
||||
if let Err(e) = fonts().filter(move |f| !wasm || (f.family == WEB_FONT.0 && f.style == WEB_FONT.1)).write("craft_fonts.rs") {
|
||||
// Desktop builds also embed the checkout's condensed face for document tab titles.
|
||||
let embedded = fonts().filter(move |f| !wasm || (f.family == WEB_FONT.0 && f.style == WEB_FONT.1));
|
||||
let embedded = if wasm { embedded } else { embedded.tab_face() };
|
||||
if let Err(e) = embedded.write("craft_fonts.rs") {
|
||||
println!("cargo::error={e}");
|
||||
}
|
||||
let mut web = String::new();
|
||||
|
||||
@@ -72,6 +72,7 @@ fn japanese_document_fonts_from(fonts: &[EmbeddedFace]) -> Vec<&EmbeddedFace> {
|
||||
/// first: the fallback for Arabic text; the other families are picked by name), then the Thai ones
|
||||
/// (Noto Sans Thai: the fallback for Thai text where no Thai font is installed, and on the web),
|
||||
/// then the Georgian ones (Noto Sans Georgian, the same for Georgian). Remaining faces follow in manifest order, so every explicitly supplied family can be selected.
|
||||
/// The tab-title face (role `tab`), which only document tab titles draw in, is left out.
|
||||
/// Empty when built without craft-fonts.
|
||||
pub fn document_fonts() -> Vec<&'static EmbeddedFace> {
|
||||
document_fonts_from(CRAFT_FONTS)
|
||||
@@ -79,7 +80,9 @@ pub fn document_fonts() -> Vec<&'static EmbeddedFace> {
|
||||
|
||||
fn document_fonts_from(fonts: &[EmbeddedFace]) -> Vec<&EmbeddedFace> {
|
||||
let mut v = japanese_document_fonts_from(fonts);
|
||||
let rest = |f: &&EmbeddedFace, earlier: &[&str]| !f.has_script("Jpan") && !earlier.iter().any(|s| f.has_script(s));
|
||||
let rest = |f: &&EmbeddedFace, earlier: &[&str]| {
|
||||
f.role != Some(craft_fonts_build::TAB_ROLE) && !f.has_script("Jpan") && !earlier.iter().any(|s| f.has_script(s))
|
||||
};
|
||||
v.extend(fonts.iter().filter(|f| f.has_script("Arab") && rest(f, &[])));
|
||||
v.extend(fonts.iter().filter(|f| f.has_script("Thai") && rest(f, &["Arab"])));
|
||||
v.extend(fonts.iter().filter(|f| f.has_script("Geor") && rest(f, &["Arab", "Thai"])));
|
||||
@@ -131,6 +134,14 @@ mod tests {
|
||||
assert!(document_fonts_from(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_fonts_leave_out_the_tab_title_face() {
|
||||
let latin = EmbeddedFace { family: "Latin", style: "Regular", scripts: &["Latn"], index: 0, bytes: &[], role: None };
|
||||
let tab = EmbeddedFace { family: "Noto Sans", style: "Condensed SemiBold", role: Some(craft_fonts_build::TAB_ROLE), ..latin };
|
||||
let listed: Vec<_> = document_fonts_from(&[latin, tab]).into_iter().map(|f| f.family).collect();
|
||||
assert_eq!(listed, ["Latin"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_fonts_follow_the_list() {
|
||||
if CRAFT_FONTS.is_empty() {
|
||||
|
||||
@@ -398,8 +398,8 @@ fn place(placing: &Placing, base: usize, amount: f64) -> Tree {
|
||||
/// next to it: `true` when a point just off the line on the left is inside it and the matching
|
||||
/// point on the right is not, `false` the other way round. `on` (a point of the line where the
|
||||
/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an
|
||||
/// eighth of the way along, each with the nearest offset first; `None` when no point tells the
|
||||
/// sides apart.
|
||||
/// eighth of the way along. Every position is tried at the nearest offset before larger offsets;
|
||||
/// `None` when no point tells the sides apart.
|
||||
fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option<bool> {
|
||||
let bp = outline.to_bezpath();
|
||||
let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0];
|
||||
@@ -407,8 +407,8 @@ fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option<boo
|
||||
let mut offsets = [1e-3, 0.25, len * 0.01];
|
||||
offsets.sort_by(f64::total_cmp);
|
||||
let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t)));
|
||||
std::iter::once(on).chain(along).find_map(|at| {
|
||||
offsets.into_iter().find_map(|off| {
|
||||
offsets.into_iter().find_map(|off| {
|
||||
std::iter::once(on).chain(along).find_map(|at| {
|
||||
let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0);
|
||||
(l != r).then_some(l)
|
||||
})
|
||||
@@ -518,3 +518,29 @@ fn crossings(rings: &[Vec<V3>], normal: V3, offset: f64, u: V3, tolerance: f64)
|
||||
at.sort_by(f64::total_cmp);
|
||||
at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod side_tests {
|
||||
use super::*;
|
||||
use vectorcraft_geom::SubPath;
|
||||
|
||||
#[test]
|
||||
fn a_nearby_probe_at_another_position_precedes_a_remote_probe_at_the_hinge() {
|
||||
let points = [
|
||||
(-2.0, -1.0),
|
||||
(-1.0, -1.0),
|
||||
(-1.0, -0.0005),
|
||||
(1.0, -0.0005),
|
||||
(1.0, -1.0),
|
||||
(101.0, -1.0),
|
||||
(101.0, 0.0),
|
||||
(-1.0, 0.0),
|
||||
(-1.0, 0.2),
|
||||
(1.0, 0.2),
|
||||
(1.0, 0.3),
|
||||
(-2.0, 0.3),
|
||||
];
|
||||
let outline = PathData::single(SubPath::polyline(&points.map(|(x, y)| Point::new(x, y)), true));
|
||||
assert_eq!(side_of(&outline, [0.0; 3], [100.0, 0.0, 0.0], 100.0, [0.0; 3]), Some(true));
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,6 @@ pub const MAX_SIDE: u32 = 4096;
|
||||
pub const MAX_PIXELS: u32 = 1 << 21;
|
||||
/// The share of the eye's distance a panel is cut at in front of the eye.
|
||||
const NEAREST: f64 = 1e-3;
|
||||
/// How far apart (points of view depth) two panels in one plane may be and still tie.
|
||||
const TIE: f64 = 1e-4;
|
||||
/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one
|
||||
/// plane.
|
||||
const PARALLEL: f64 = 1e-9;
|
||||
@@ -269,6 +267,13 @@ struct Mapped {
|
||||
shade: f32,
|
||||
}
|
||||
|
||||
impl Mapped {
|
||||
fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
|
||||
let [u, v, w] = mul(&self.inverse, [x, y, 1.0]);
|
||||
(w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite())
|
||||
}
|
||||
}
|
||||
|
||||
fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 {
|
||||
[dot(m[0], v), dot(m[1], v), dot(m[2], v)]
|
||||
}
|
||||
@@ -340,6 +345,8 @@ struct Target {
|
||||
/// [`planes`] gives them), panel number and colors.
|
||||
struct Fill<'a> {
|
||||
mapped: &'a Mapped,
|
||||
/// The group's comparison plane, or this panel when grouping is bypassed.
|
||||
plane: &'a Mapped,
|
||||
rank: u16,
|
||||
planes: &'a [u16],
|
||||
panel: u16,
|
||||
@@ -354,8 +361,7 @@ struct Fill<'a> {
|
||||
impl Fill<'_> {
|
||||
/// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye.
|
||||
fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
|
||||
let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]);
|
||||
(w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite())
|
||||
self.mapped.flat_at(x, y)
|
||||
}
|
||||
|
||||
/// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel.
|
||||
@@ -382,15 +388,15 @@ impl Fill<'_> {
|
||||
for col in first as usize..=last as usize {
|
||||
let x = col as f64 + 0.5;
|
||||
let Some((u, v)) = self.flat_at(x, y) else { continue };
|
||||
let [a, b, c] = self.mapped.depth;
|
||||
let z = u * a + v * b + c;
|
||||
let Some((pu, pv)) = self.plane.flat_at(x, y) else { continue };
|
||||
let [a, b, c] = self.plane.depth;
|
||||
let z = pu * a + pv * b + c;
|
||||
let i = row * target.width + col;
|
||||
let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue };
|
||||
// Panels in one plane tie within `TIE` and stack by rank; panels in different planes
|
||||
// that pass this close go by depth alone. Panel numbers count from 1.
|
||||
// Members of a plane have the same comparison depth and stack by rank. Distinct
|
||||
// planes compare by depth, then by their number at an exact crossing.
|
||||
let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p));
|
||||
let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a));
|
||||
let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb };
|
||||
let wins = z.total_cmp(&zb).then_with(|| plane(self.panel).cmp(&plane(pb))).then(self.rank.cmp(&rb)).then(self.panel.cmp(&pb)).is_gt();
|
||||
if !wins {
|
||||
continue;
|
||||
}
|
||||
@@ -639,6 +645,17 @@ pub fn render(scene: &Scene) -> Option<Image> {
|
||||
for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) {
|
||||
let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue };
|
||||
let Some(mapped) = map_panel(&local, &f.local) else { continue };
|
||||
let plane = if scene.folded.panels.len() <= super::MAX_PANELS {
|
||||
planes.get(pi).and_then(|kind| {
|
||||
planes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, k)| *k == kind)
|
||||
.find_map(|(i, _)| scene.folded.panels.get(i).and_then(|f| map_panel(&local, &f.local)))
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(rings) = flat_rings(panel, camera.scale) else { continue };
|
||||
let rings: Vec<Vec<[f64; 2]>> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect();
|
||||
let projected: Vec<Vec<[f64; 2]>> = rings
|
||||
@@ -661,6 +678,7 @@ pub fn render(scene: &Scene) -> Option<Image> {
|
||||
.collect();
|
||||
let fill = Fill {
|
||||
mapped: &mapped,
|
||||
plane: plane.as_ref().unwrap_or(&mapped),
|
||||
rank,
|
||||
planes: &planes,
|
||||
panel: u16::try_from(pi + 1).unwrap_or(u16::MAX),
|
||||
@@ -677,39 +695,51 @@ pub fn render(scene: &Scene) -> Option<Image> {
|
||||
/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their
|
||||
/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them
|
||||
/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the
|
||||
/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is
|
||||
/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`]
|
||||
/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the
|
||||
/// planes. Past [`super::MAX_PANELS`] panels, one plane for all.
|
||||
/// base). Each panel's bounds corners are measured by its pose about [`Folded::origin`]
|
||||
/// ([`super::FoldedPanel::local`]). Past [`super::MAX_PANELS`] panels, one plane for all.
|
||||
fn planes(folded: &Folded, blank: &Blank) -> Vec<u16> {
|
||||
let n = folded.panels.len();
|
||||
if n > super::MAX_PANELS {
|
||||
return vec![0; n];
|
||||
}
|
||||
let length = |v: V3| dot(v, v).sqrt();
|
||||
// Each plane's normal, a point of it, the size of the coordinates that point came from and the
|
||||
// hinges that placed it.
|
||||
let mut kinds: Vec<(V3, V3, f64, usize)> = vec![];
|
||||
struct Plane {
|
||||
normal: V3,
|
||||
at: V3,
|
||||
size: f64,
|
||||
depth: usize,
|
||||
corners: [V3; 4],
|
||||
}
|
||||
let separation = |normal: V3, at: V3, points: &[V3; 4]| {
|
||||
points.iter().map(|p| dot(normal, [p[0] - at[0], p[1] - at[1], p[2] - at[2]]).abs()).fold(0.0, f64::max)
|
||||
};
|
||||
let mut kinds: Vec<Vec<Plane>> = vec![];
|
||||
folded
|
||||
.panels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| {
|
||||
let o = folded.origin;
|
||||
let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]);
|
||||
let bounds = blank.panels.get(i).and_then(|p| p.outline.bounds());
|
||||
let middle = bounds.map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]);
|
||||
let flat =
|
||||
bounds.map_or([middle; 4], |b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| [x - o[0], -y - o[1], 0.0]));
|
||||
let corners = flat.map(|p| f.local.apply(p));
|
||||
let (normal, at) = (f.local.normal(), f.local.apply(middle));
|
||||
let size = length(at).max(length(middle));
|
||||
let same = |(m, p, s, d): &(V3, V3, f64, usize)| {
|
||||
let size = flat.iter().chain(&corners).map(|&p| length(p)).fold(0.0, f64::max);
|
||||
let same = |p: &Plane| {
|
||||
let m = p.normal;
|
||||
let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]];
|
||||
let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs();
|
||||
let apart = separation(m, p.at, &corners).max(separation(normal, at, &p.corners));
|
||||
// Saturating: a `Folded` built by a caller may carry any depth.
|
||||
let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX));
|
||||
length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s))
|
||||
let hinges = f64::from(u32::try_from(f.depth.saturating_add(p.depth).saturating_add(1)).unwrap_or(u32::MAX));
|
||||
length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(p.size))
|
||||
};
|
||||
let k = kinds.iter().position(same).unwrap_or_else(|| {
|
||||
kinds.push((normal, at, size, f.depth));
|
||||
let k = kinds.iter().position(|group| group.iter().all(&same)).unwrap_or_else(|| {
|
||||
kinds.push(vec![]);
|
||||
kinds.len() - 1
|
||||
});
|
||||
kinds[k].push(Plane { normal, at, size, depth: f.depth, corners });
|
||||
u16::try_from(k).unwrap_or(u16::MAX)
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -13,6 +13,18 @@ fn panel(subpaths: Vec<SubPath>) -> Panel {
|
||||
Panel { outline: PathData::new(subpaths), area: 0.0 }
|
||||
}
|
||||
|
||||
fn poly(pts: &[(f64, f64)], closed: bool) -> PathData {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
}
|
||||
|
||||
fn fold_line(path: PathData, kind: super::super::LineKind, key: u64, angle: Option<f64>) -> super::super::FoldLine {
|
||||
super::super::FoldLine { path, kind, key, angle }
|
||||
}
|
||||
|
||||
fn line(pts: &[(f64, f64)], closed: bool, kind: super::super::LineKind, key: u64, angle: Option<f64>) -> super::super::FoldLine {
|
||||
fold_line(poly(pts, closed), kind, key, angle)
|
||||
}
|
||||
|
||||
/// A blank of `panels` and a fold that places each at `poses`, in the order given.
|
||||
fn scene_of(panels: Vec<Panel>, poses: Vec<Pose>) -> (Blank, Folded) {
|
||||
let n = panels.len();
|
||||
@@ -37,6 +49,62 @@ fn moved(z: f64) -> Pose {
|
||||
Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_middle_plane_does_not_join_two_separate_planes_into_one_stack() {
|
||||
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
|
||||
let (b, f) = scene_of(vec![whole(), whole(), whole()], vec![moved(4e-13), moved(8e-13), moved(0.0)]);
|
||||
let image = render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera: front() }).expect("drawn");
|
||||
assert_eq!(image.panel_at(50, 50), Some(1), "the separate farther panel does not cover the near stack");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caller_supplied_scene_past_the_panel_limit_keeps_actual_depth() {
|
||||
let n = super::super::MAX_PANELS + 1;
|
||||
let panels = (0..n).map(|_| panel(vec![square(0.0, 0.0, 100.0, 100.0)])).collect();
|
||||
let mut poses = vec![Pose::IDENTITY; n];
|
||||
poses[1] = moved(5.0);
|
||||
let (b, f) = scene_of(panels, poses);
|
||||
let image = render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera: front() }).expect("drawn");
|
||||
assert_eq!(image.panel_at(50, 50), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_a_stack_selects_the_same_pixel_in_every_draw_order() {
|
||||
let angle = 1e-4_f64;
|
||||
let (s, c) = angle.sin_cos();
|
||||
let crossing = Pose { m: [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]], t: [0.0, 0.0, s * 50.5 / c + 2e-13] };
|
||||
let maps = [Pose::IDENTITY, crossing, moved(4e-13)].map(|p| map_panel(&front(), &p).expect("mapped"));
|
||||
let planes = [0, 1, 0];
|
||||
let ranks = [3, 2, 1];
|
||||
let mut winners = vec![];
|
||||
for order in [[0, 1, 2], [2, 1, 0], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1]] {
|
||||
let mut target = Target {
|
||||
width: 100,
|
||||
height: 100,
|
||||
color: vec![0; 40_000],
|
||||
depth: vec![f64::NEG_INFINITY; 10_000],
|
||||
rank: vec![0; 10_000],
|
||||
panel: vec![0; 10_000],
|
||||
};
|
||||
for i in order {
|
||||
Fill {
|
||||
mapped: &maps[i],
|
||||
plane: &maps[usize::from(planes[i])],
|
||||
rank: ranks[i],
|
||||
planes: &planes,
|
||||
panel: (i + 1) as u16,
|
||||
print: None,
|
||||
origin: [0.0; 2],
|
||||
inside: [0.0; 4],
|
||||
outside: [0.0; 4],
|
||||
}
|
||||
.span(&mut target, 50, 50.0, 51.0);
|
||||
}
|
||||
winners.push(target.panel[5050]);
|
||||
}
|
||||
assert!(winners.iter().all(|&winner| winner == winners[0]), "{winners:?}");
|
||||
}
|
||||
|
||||
fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = (y * img.width + x) as usize * 4;
|
||||
[img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]]
|
||||
@@ -139,9 +207,23 @@ fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() {
|
||||
assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearly_parallel_panels_that_cross_use_depth_on_both_sides() {
|
||||
let angle = 5e-10f64;
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let tilted = Pose { m: [[cos, 0.0, sin], [0.0, 1.0, 0.0], [-sin, 0.0, cos]], t: [50.0 * (1.0 - cos), 0.0, 50.0 * sin] };
|
||||
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
|
||||
for (poses, left, right) in [(vec![Pose::IDENTITY, tilted], 1, 0), (vec![tilted, Pose::IDENTITY], 0, 1)] {
|
||||
let (b, f) = scene_of(vec![whole(), whole()], poses);
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
|
||||
assert_eq!(img.panel_at(25, 50), Some(left));
|
||||
assert_eq!(img.panel_at(75, 50), Some(right));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn of_two_parallel_panels_the_nearer_shows_however_close() {
|
||||
// 2 and 2.0001 points deep: a hair more than `TIE` apart once subtracted, though 2 + `TIE`
|
||||
// 2 and 2.0001 points deep: a hair more than 0.0001 apart once subtracted, though 2 + 0.0001
|
||||
// equals 2.0001. The panels lie in different planes, so the nearer shows whichever is drawn
|
||||
// first.
|
||||
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
|
||||
@@ -167,24 +249,11 @@ fn a_scene_whose_panels_claim_any_depth_still_draws() {
|
||||
#[test]
|
||||
fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() {
|
||||
// A 100 × 60 blank with a crease at x = 60: the flap (x 60 to 100) folds over onto the base.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
// Folds a hair short of flat lie on the same side, everywhere within a tie of the base.
|
||||
for (angle, flap_in_front) in [(180.0, false), (-180.0, true), (179.9999, false), (-179.9999, true)] {
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(60.0, 0.0), (60.0, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key: 2,
|
||||
angle: Some(angle),
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
fold_line(poly(&[(60.0, 0.0), (60.0, 60.0)], false), super::super::LineKind::Crease, 2, Some(angle)),
|
||||
];
|
||||
let (blanks, issues) = super::super::blanks(&lines, 0.1);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
@@ -211,22 +280,9 @@ fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() {
|
||||
fn a_hinge_left_at_0_degrees_keeps_its_panel_level_with_its_parent() {
|
||||
// A 100 × 60 blank: the base (x 0 to 60), a strip (60 to 65) left flat at 0°, and a flap (65 to
|
||||
// 100) folded back at 180°, which lies behind the base from x 30 to 60.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(angle),
|
||||
};
|
||||
let crease = |x: f64, key: u64, angle: f64| fold_line(poly(&[(x, 0.0), (x, 60.0)], false), super::super::LineKind::Crease, key, Some(angle));
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
crease(60.0, 2, 0.0),
|
||||
crease(65.0, 3, 180.0),
|
||||
];
|
||||
@@ -243,22 +299,9 @@ fn a_flap_folded_back_over_a_folded_panel_lies_between_it_and_the_base() {
|
||||
// A 110 × 60 strip: the base (x 0 to 60), a panel (60 to 100) folded back under the base at
|
||||
// 180°, and a flap (100 to 110) folded back at 180° from that panel, between it and the base, at
|
||||
// x 20 to 30.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let crease = |x: f64, key: u64| super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(180.0),
|
||||
};
|
||||
let crease = |x: f64, key: u64| fold_line(poly(&[(x, 0.0), (x, 60.0)], false), super::super::LineKind::Crease, key, Some(180.0));
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
crease(60.0, 2),
|
||||
crease(100.0, 3),
|
||||
];
|
||||
@@ -289,19 +332,9 @@ fn a_strip_far_from_the_origin_stacks_the_same_about_any_base() {
|
||||
let at = |x: f64, y: f64| Point::new(3_000_000.0 + (x - y) * s, 3_000_000.0 + (x + y) * s);
|
||||
let poly =
|
||||
|pts: &[(f64, f64)], closed: bool| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| at(x, y)).collect::<Vec<_>>(), closed));
|
||||
let crease = |x: f64, key: u64| super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(180.0),
|
||||
};
|
||||
let crease = |x: f64, key: u64| fold_line(poly(&[(x, 0.0), (x, 60.0)], false), super::super::LineKind::Crease, key, Some(180.0));
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
crease(60.0, 2),
|
||||
crease(100.0, 3),
|
||||
];
|
||||
@@ -326,19 +359,9 @@ fn a_flat_stack_far_from_the_origin_stays_in_one_plane() {
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x0 + x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let crease = |x: f64, key: u64| super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(180.0),
|
||||
};
|
||||
let crease = |x: f64, key: u64| fold_line(poly(&[(x, 0.0), (x, 60.0)], false), super::super::LineKind::Crease, key, Some(180.0));
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
crease(60.0, 2),
|
||||
crease(100.0, 3),
|
||||
];
|
||||
@@ -373,19 +396,9 @@ fn parallel_a_hair_behind(dx: f64, back: f64, w: f64) {
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + dx, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 30.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(angle),
|
||||
};
|
||||
let crease = |x: f64, key: u64, angle: f64| fold_line(poly(&[(x, 0.0), (x, 30.0)], false), super::super::LineKind::Crease, key, Some(angle));
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
crease(100.0, 2, 180.0 - back),
|
||||
crease(100.0 + w, 3, back),
|
||||
];
|
||||
@@ -414,18 +427,8 @@ fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + at, y + at)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(2.0, 0.0), (2.0, 1.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key: 2,
|
||||
angle: Some(179.999999),
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
fold_line(poly(&[(2.0, 0.0), (2.0, 1.0)], false), super::super::LineKind::Crease, 2, Some(179.999999)),
|
||||
];
|
||||
let (blanks, issues) = super::super::blanks(&lines, 0.0001);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
@@ -448,23 +451,10 @@ fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() {
|
||||
fn a_blank_lying_flat_takes_its_ranks_from_the_order_alone() {
|
||||
// A strip of 64 panels, each crease at 180°, not yet folded: no panel overlaps another, so no
|
||||
// layer is worked out.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let mut lines = vec![super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
}];
|
||||
let mut lines = vec![fold_line(poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true), super::super::LineKind::Cut, 1, None)];
|
||||
for i in 1..64u32 {
|
||||
let x = f64::from(i) * 10.0;
|
||||
lines.push(super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 10.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key: u64::from(i) + 1,
|
||||
angle: Some(180.0),
|
||||
});
|
||||
lines.push(fold_line(poly(&[(x, 0.0), (x, 10.0)], false), super::super::LineKind::Crease, u64::from(i) + 1, Some(180.0)));
|
||||
}
|
||||
let (blanks, issues) = super::super::blanks(&lines, 0.1);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
@@ -479,23 +469,12 @@ fn round_a_loop_of_panels_the_stack_follows_the_hinges_that_placed_them() {
|
||||
// point. The crease that closes the loop when folded about the largest panel folds at 180° and
|
||||
// the rest at 0°; folded about a panel on that crease, the crease is in the tree and its flap
|
||||
// lies flat behind the panel.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let lines = |flat_key: Option<u64>| {
|
||||
let crease = |from: (f64, f64), to: (f64, f64), key: u64| super::super::FoldLine {
|
||||
path: poly(&[from, to], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(if Some(key) == flat_key { 180.0 } else { 0.0 }),
|
||||
let crease = |from: (f64, f64), to: (f64, f64), key: u64| {
|
||||
fold_line(poly(&[from, to], false), super::super::LineKind::Crease, key, Some(if Some(key) == flat_key { 180.0 } else { 0.0 }))
|
||||
};
|
||||
vec![
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), super::super::LineKind::Cut, 1, None),
|
||||
crease((50.0, 0.0), (50.0, 50.0), 2),
|
||||
crease((50.0, 50.0), (50.0, 100.0), 3),
|
||||
crease((0.0, 50.0), (50.0, 50.0), 4),
|
||||
@@ -531,22 +510,16 @@ fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() {
|
||||
// folded back at 180° off the top right panel: the first (x 100 to 130) under that panel, the
|
||||
// tip (130 to 140) between the two. Folded about the tip, the tree reaches the grid another way,
|
||||
// and the stack stays as it is about the largest panel.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| super::super::FoldLine {
|
||||
path: poly(&[from, to], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(angle),
|
||||
let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| {
|
||||
fold_line(poly(&[from, to], false), super::super::LineKind::Crease, key, Some(angle))
|
||||
};
|
||||
let lines = [
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
},
|
||||
fold_line(
|
||||
poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true),
|
||||
super::super::LineKind::Cut,
|
||||
1,
|
||||
None,
|
||||
),
|
||||
crease((60.0, 0.0), (60.0, 40.0), 2, 0.0),
|
||||
crease((60.0, 40.0), (60.0, 100.0), 3, 0.0),
|
||||
crease((0.0, 40.0), (60.0, 40.0), 4, 0.0),
|
||||
@@ -570,10 +543,7 @@ fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() {
|
||||
fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() {
|
||||
// The base (x 30 to 80) with a window (52 to 58), a flap on each side folded back at 180°: the
|
||||
// left one to x 30 to 60, the right one to 50 to 80, so both lie behind the window.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let lines = [
|
||||
line(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true, Cut, 1, None),
|
||||
@@ -598,10 +568,7 @@ fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() {
|
||||
fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() {
|
||||
// The base (x 30 to 90), a right flap (90 to 140) folded back to 40 to 90, and a left flap (0 to
|
||||
// 30) folded back to 30 to 60 in two parts joined at 0° (x 15), both parts over the right flap.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let lines = [
|
||||
line(&[(0.0, 0.0), (140.0, 0.0), (140.0, 60.0), (0.0, 60.0)], true, Cut, 1, None),
|
||||
@@ -633,10 +600,7 @@ fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() {
|
||||
// Left to right: a tip (x 0 to 20), a left flap (20 to 70), the base (70 to 140) and a right flap
|
||||
// (140 to 205). Both flaps fold back at 180° behind the base (to 70 to 120 and 75 to 140), and
|
||||
// the tip folds at -180° on the left flap (to 100 to 120), so the three overlap from 100 to 120.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let lines = [
|
||||
line(&[(0.0, 0.0), (205.0, 0.0), (205.0, 60.0), (0.0, 60.0)], true, Cut, 1, None),
|
||||
@@ -665,10 +629,7 @@ fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() {
|
||||
fn a_tip_folded_back_toward_a_folded_panel_s_print_covers_it_from_the_back() {
|
||||
// The base (x 0 to 60), a panel (60 to 100) folded back at 180° to 20 to 60, and a tip (100 to
|
||||
// 110) folded at -180° onto that panel's printed side, to 20 to 30, behind it from the front.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
// The same with the tip a hair short of flat, and with an 80 pt panel under a 100 pt base.
|
||||
for (middle, tip_angle) in [(40.0, -180.0), (40.0, -179.9999), (40.0, -179.999), (80.0, -179.9999), (1000.0, -179.999)] {
|
||||
@@ -697,10 +658,7 @@ fn overlapping_lid_flaps_keep_their_order_as_the_view_turns_on_one_side_of_the_l
|
||||
// A box strip: a left flap (x 0 to 60), a wall (60 to 100), the base (100 to 200), a wall (200 to
|
||||
// 240) and a right flap (240 to 300). The walls fold 90° down and the flaps 90° in, so the flaps
|
||||
// meet in one plane 40 pt below the base and overlap from x 140 to 160.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let crease = |x: f64, key| line(&[(x, 0.0), (x, 60.0)], false, Crease, key, Some(90.0));
|
||||
let lines = [
|
||||
@@ -729,10 +687,7 @@ fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() {
|
||||
// The base (x 0 to 100, y -50 to 110) and a panel (100 to 200, 0 to 60) on a crease at x = 100,
|
||||
// with a flap above (y -40 to 0) and one below (60 to 100), each cut free of the base and folded
|
||||
// at -180° onto the panel's printed side, where they overlap from y 20 to 40.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let shown = |tilt: f64| {
|
||||
let outline = [(0.0, -50.0), (100.0, -50.0), (100.0, -40.0), (200.0, -40.0), (200.0, 100.0), (100.0, 100.0), (100.0, 110.0), (0.0, 110.0)];
|
||||
@@ -752,9 +707,11 @@ fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() {
|
||||
let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn");
|
||||
let flap = |y: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.y0 - y).abs() < 1e-6 && r.x0 > 99.0));
|
||||
let shown = img.panel_at(100, 50);
|
||||
if shown == flap(-40.0) {
|
||||
let above = flap(-40.0).expect("the upper flap exists");
|
||||
let below = flap(60.0).expect("the lower flap exists");
|
||||
if shown == Some(above) {
|
||||
"above"
|
||||
} else if shown == flap(60.0) {
|
||||
} else if shown == Some(below) {
|
||||
"below"
|
||||
} else {
|
||||
"neither"
|
||||
@@ -769,10 +726,7 @@ fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() {
|
||||
fn a_flap_folded_onto_a_wall_standing_at_90_degrees_covers_its_print() {
|
||||
// The base (x 0 to 60), a wall (60 to 100) folded 90° and a flap (100 to 130) folded at -180°
|
||||
// onto the wall's printed side, where it covers the wall from 10 to 40 pt out from the base.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let lines = [
|
||||
line(&[(0.0, 0.0), (130.0, 0.0), (130.0, 60.0), (0.0, 60.0)], true, Cut, 1, None),
|
||||
@@ -808,10 +762,7 @@ fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_s
|
||||
// The base (x 40 to 140, y 0 to 60) and a side wall on each side (0 to 40 and 140 to 180), each
|
||||
// with an end flap (y 60 to 160) that folds in across the carton's end, so both flaps cover
|
||||
// the same 100 pt. Looking straight through that end, the base and walls are edge on.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let outline = [(0.0, 0.0), (180.0, 0.0), (180.0, 160.0), (140.0, 160.0), (140.0, 60.0), (40.0, 60.0), (40.0, 160.0), (0.0, 160.0)];
|
||||
let lines = [
|
||||
@@ -853,10 +804,7 @@ fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_s
|
||||
fn a_flap_looped_round_onto_the_base_shows_from_the_side_it_came_from() {
|
||||
// A strip: the base (x 0 to 100) and panels 40, 60, 40 and 80 pt wide, folded 90°, -90°, -90°
|
||||
// and -90°, so the last one comes round and lies on the base's plane over part of it.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let lines = [
|
||||
line(&[(0.0, 0.0), (320.0, 0.0), (320.0, 60.0), (0.0, 60.0)], true, Cut, 1, None),
|
||||
@@ -895,13 +843,9 @@ fn a_strip_wrapped_round_a_wall_lands_its_flap_on_the_print_side_it_came_from()
|
||||
// flap folds from stands on the printed side of the base, and the flap lands on the base at x
|
||||
// 50 to 80. With `tab`, the wall also runs on past the flap's hinge (to x 340, y 30 to 60),
|
||||
// through the base's plane, which moves its middle to the other side of that plane.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
// With `cutout` of 5, a 10 pt hole on the middle of each crease breaks every hinge in two; with
|
||||
// a larger one, the hole runs to within 2 pt of each end, as wide as `cutout` either side.
|
||||
let shown = |tab: bool, cutout: f64| {
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let mut lines = if tab {
|
||||
vec![
|
||||
@@ -963,9 +907,6 @@ fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_
|
||||
// 20 pt wide back level, one up through the base's plane to `drop` in front of it, a ramp
|
||||
// `ramp` wide that comes back down to the base's plane over its width, and a flap (30 pt) that
|
||||
// lies on the base from where the ramp ends.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let shown = |base: f64, ramp: f64, drop: f64| {
|
||||
// To the millionth of a degree a line keeps, and the drop that ramp comes down by.
|
||||
let tilt = super::super::kept_angle((drop / ramp).asin().to_degrees());
|
||||
@@ -973,19 +914,9 @@ fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_
|
||||
let up = base + 30.0;
|
||||
let creases = [(base, 90.0), (base + 10.0, -90.0), (up, -90.0), (up + 10.0 + drop, -90.0 - tilt), (up + 10.0 + drop + ramp, tilt)];
|
||||
let end = up + 10.0 + drop + ramp + 30.0;
|
||||
let mut lines = vec![super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
}];
|
||||
let mut lines = vec![fold_line(poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true), super::super::LineKind::Cut, 1, None)];
|
||||
for (i, (x, a)) in creases.into_iter().enumerate() {
|
||||
lines.push(super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 30.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key: 2 + i as u64,
|
||||
angle: Some(a),
|
||||
});
|
||||
lines.push(fold_line(poly(&[(x, 0.0), (x, 30.0)], false), super::super::LineKind::Crease, 2 + i as u64, Some(a)));
|
||||
}
|
||||
let (blanks, issues) = super::super::blanks(&lines, 0.0001);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
@@ -1021,23 +952,10 @@ fn a_flap_brought_back_by_folds_all_near_flat_lands_on_the_side_its_ramp_came_fr
|
||||
}
|
||||
|
||||
fn flap_brought_back_by_folds_all_near_flat(tilt: f64) {
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let creases = [(1000.0, tilt), (1100.0, 180.0), (1400.0, -2.0 * tilt), (1600.0, tilt)];
|
||||
let mut lines = vec![super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
}];
|
||||
let mut lines = vec![fold_line(poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true), super::super::LineKind::Cut, 1, None)];
|
||||
for (i, (x, a)) in creases.into_iter().enumerate() {
|
||||
lines.push(super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 30.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key: 2 + i as u64,
|
||||
angle: Some(a),
|
||||
});
|
||||
lines.push(fold_line(poly(&[(x, 0.0), (x, 30.0)], false), super::super::LineKind::Crease, 2 + i as u64, Some(a)));
|
||||
}
|
||||
let (blanks, issues) = super::super::blanks(&lines, 0.0001);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
@@ -1067,10 +985,7 @@ fn flap_brought_back_by_folds_all_near_flat(tilt: f64) {
|
||||
fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_came_from() {
|
||||
// The strip of the test above, with a larger base (x -150 to 0) on the left that the strip's
|
||||
// first panel (0 to 100) stands up from at -90°. The flap lands on that panel's printed side.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle };
|
||||
|
||||
use super::super::LineKind::{Crease, Cut};
|
||||
let mut lines = vec![line(&[(-150.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (-150.0, 60.0)], true, Cut, 1, None)];
|
||||
lines.push(line(&[(0.0, 0.0), (0.0, 60.0)], false, Crease, 2, Some(-90.0)));
|
||||
@@ -1103,24 +1018,11 @@ fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_
|
||||
fn a_strip_rolled_up_45_times_keeps_the_base_in_front() {
|
||||
// A strip: the base (x 0 to 60) and 45 panels 50 pt wide, every crease folded back at 180°, so
|
||||
// each panel rolls under the one before it and all of them lie behind the base.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let end = 60.0 + 45.0 * 50.0;
|
||||
let mut lines = vec![super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
}];
|
||||
let mut lines = vec![fold_line(poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None)];
|
||||
lines.extend((0u32..45).map(|i| {
|
||||
let x = 60.0 + 50.0 * f64::from(i);
|
||||
super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key: 10 + u64::from(i),
|
||||
angle: Some(180.0),
|
||||
}
|
||||
fold_line(poly(&[(x, 0.0), (x, 60.0)], false), super::super::LineKind::Crease, 10 + u64::from(i), Some(180.0))
|
||||
}));
|
||||
let (blanks, issues) = super::super::blanks(&lines, 0.1);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
@@ -1135,21 +1037,8 @@ fn hinges_left_at_0_degrees_before_two_folds_back_do_not_use_up_layers() {
|
||||
// A 155 × 60 strip: the base (x 0 to 60), 45 strips 1 pt wide left flat at 0°, a panel (105 to
|
||||
// 145) folded back at 180° and a flap (145 to 155) folded back at 180° from it, which lies
|
||||
// behind the flat strips at x 65 to 75.
|
||||
let poly = |pts: &[(f64, f64)], closed: bool| {
|
||||
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed))
|
||||
};
|
||||
let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine {
|
||||
path: poly(&[(x, 0.0), (x, 60.0)], false),
|
||||
kind: super::super::LineKind::Crease,
|
||||
key,
|
||||
angle: Some(angle),
|
||||
};
|
||||
let mut lines = vec![super::super::FoldLine {
|
||||
path: poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true),
|
||||
kind: super::super::LineKind::Cut,
|
||||
key: 1,
|
||||
angle: None,
|
||||
}];
|
||||
let crease = |x: f64, key: u64, angle: f64| fold_line(poly(&[(x, 0.0), (x, 60.0)], false), super::super::LineKind::Crease, key, Some(angle));
|
||||
let mut lines = vec![fold_line(poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true), super::super::LineKind::Cut, 1, None)];
|
||||
lines.extend((0u32..45).map(|i| crease(60.0 + f64::from(i), 10 + u64::from(i), 0.0)));
|
||||
lines.push(crease(105.0, 2, 180.0));
|
||||
lines.push(crease(145.0, 3, 180.0));
|
||||
|
||||
@@ -355,9 +355,11 @@ impl VectorcraftApp {
|
||||
}
|
||||
|
||||
/// Applies the work that finished off the UI thread. It stays pending while a script runs, since
|
||||
/// every change to the documents ends in a busy error until the script ends.
|
||||
/// every change to the documents ends in a busy error until the script ends. Plug-in worker runs
|
||||
/// are still read then, so Cancel and their time budgets still end them ([`plugin_runs::poll`]).
|
||||
pub(crate) fn poll_finished_work(&mut self) {
|
||||
if self.session.script_running() {
|
||||
plugin_runs::poll(self);
|
||||
return;
|
||||
}
|
||||
background::poll(self);
|
||||
@@ -530,7 +532,7 @@ impl VectorcraftApp {
|
||||
crate::addons::select::link_status::refresh(self, now);
|
||||
if !self.background.jobs.is_empty()
|
||||
|| !self.opening.pending.is_empty()
|
||||
|| !self.plugin_runs.running.is_empty()
|
||||
|| plugin_runs::any_pending(self)
|
||||
|| !self.placing.pending.is_empty()
|
||||
|| !self.trace_runs.running.is_empty()
|
||||
|| self.retype_runs.running.is_some()
|
||||
|
||||
@@ -75,6 +75,15 @@ fn substitute_warnings_follow_current_font_inventory() {
|
||||
impl VectorcraftApp {
|
||||
/// Run a UI or engine command by id. The single entry point for every frontend path.
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
// A plug-in run that holds the documents (the web's worker runs of a filter that calls
|
||||
// commands) lets only its Cancel through, and the `plugin.run` that applies its output.
|
||||
if crate::plugin_runs::holds_documents(self) && id != "plugin.cancelRuns" && !self.session.plugin_calls_end_with(id) {
|
||||
return Err(vectorcraft_engine::EngineError::PluginBusy.to_string());
|
||||
}
|
||||
// On the web a plug-in command runs in a worker ([`crate::plugin_runs`]).
|
||||
if crate::plugin_runs::routes(self, id) {
|
||||
return crate::plugin_runs::start_command(self, id, params);
|
||||
}
|
||||
self.beacon.command(id);
|
||||
let touch_workspace = self.session.prefs.touch_workspace;
|
||||
// A `prefs.reset` that ran straight on the session applies before this command can switch workspaces.
|
||||
|
||||
@@ -30,6 +30,9 @@ impl VectorcraftApp {
|
||||
}
|
||||
|
||||
pub(crate) fn drain_inbox(&mut self) {
|
||||
if self.session.plugin_calls_open() {
|
||||
return;
|
||||
}
|
||||
fn take(q: Option<&Inbox>) -> Vec<(String, Vec<u8>)> {
|
||||
q.map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default()
|
||||
}
|
||||
@@ -37,11 +40,7 @@ impl VectorcraftApp {
|
||||
let mut arrived: Vec<_> = take(self.services.inbox.as_ref()).into_iter().map(|f| (f, false)).collect();
|
||||
arrived.extend(take(self.services.page_inbox.as_ref()).into_iter().map(|f| (f, true)));
|
||||
for ((name, bytes), automated) in arrived {
|
||||
crate::file_asks::as_automated(self, automated, |app| {
|
||||
if let Err(e) = io::open_bytes(app, &name, &bytes, None) {
|
||||
io::report_open_error(app, &name, &e);
|
||||
}
|
||||
});
|
||||
crate::file_asks::as_automated(self, automated, |app| io::open_bytes_reporting(app, &name, &bytes));
|
||||
}
|
||||
place::drain(self);
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
//! The ••• button at a toolbar's foot opens the All Tools drawer beside it, and tools dragged from the
|
||||
//! drawer fill it (`edit_toolbar`, with the `toolbar` param of its commands). The + button above it
|
||||
//! opens Add Tool…, a menu of every tool where a click adds the tool at the end, and whose Remove Tool
|
||||
//! items take tools out: VectorCraft's own way to fill a toolbar without a drag. Each toolbar is listed
|
||||
//! under Window › Toolbars, where its item shows or hides it. Window › Toolbars › Manage Toolbars (also
|
||||
//! in the drawer's menu) renames, copies and deletes them.
|
||||
//! items take tools out: VectorCraft's own way to fill a toolbar without a drag. The same menu's Add
|
||||
//! Command submenu searches the Command Palette's results and adds a command button after the tools,
|
||||
//! which runs what the command's menu item runs (`toolbar.addCommand`, `toolbar.removeCommand`);
|
||||
//! command buttons are VectorCraft's own. Each toolbar is listed under Window › Toolbars, where its
|
||||
//! item shows or hides it. Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames,
|
||||
//! copies and deletes them.
|
||||
//!
|
||||
//! Behavior from the public documentation:
|
||||
//! <https://helpx.adobe.com/illustrator/using/tools.html> (Create and manage toolbars: New Toolbar
|
||||
@@ -24,10 +27,10 @@ use std::collections::BTreeSet;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target};
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::buttons::{Button, IconButton};
|
||||
use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
|
||||
use craft::ui::dialog::DialogResult;
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, HostedListManager, HostedParamDialog, ListManagerAction, ListManagerChoice, ListManagerEntry, ListManagerWords, Param,
|
||||
@@ -35,6 +38,7 @@ use craft::ui::patterns::form_dialogs::{
|
||||
};
|
||||
use craft::ui::rails::RailFooter;
|
||||
use craft::ui::runtime::commands::CommandRef;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::pos2;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_tools::tool_info;
|
||||
@@ -47,6 +51,8 @@ use crate::{VectorcraftApp, panel_docking};
|
||||
pub(crate) const MAX: usize = 64;
|
||||
/// The most characters a toolbar's name has.
|
||||
const MAX_NAME: usize = 200;
|
||||
/// The most command buttons a toolbar holds.
|
||||
const MAX_COMMANDS: usize = 200;
|
||||
/// Where the first toolbar made floats, right of the Tools panel; the next ones go lower.
|
||||
const NEW_AT: [f32; 2] = [96.0, 120.0];
|
||||
/// The kind every Manage Toolbars entry has: all of them rename in place.
|
||||
@@ -179,6 +185,7 @@ fn blank(id: u32, name: String) -> CustomToolbar {
|
||||
slot_tool: Default::default(),
|
||||
double: false,
|
||||
floating: Vec::new(),
|
||||
commands: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,8 +281,10 @@ pub(crate) fn delete(app: &mut VectorcraftApp, name: &str) -> Result<(), String>
|
||||
|
||||
/// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of
|
||||
/// known tools, each once in its toolbar, each group's tool chosen last only when the group holds it,
|
||||
/// and each with an id of its own: one saved without an id or repeating an earlier toolbar's gets
|
||||
/// the lowest id nobody holds (a hand-edited preferences file or workspace).
|
||||
/// at most [`MAX_COMMANDS`] command buttons, each command once and none for a tool, and each with an
|
||||
/// id of its own: one saved without an id or repeating an earlier toolbar's gets the lowest id nobody
|
||||
/// holds (a hand-edited preferences file or workspace). A command that is not known now stays: it may
|
||||
/// be an uninstalled plug-in's.
|
||||
pub(crate) fn sanitize(bars: &mut Vec<CustomToolbar>) {
|
||||
let mut names = BTreeSet::new();
|
||||
bars.retain_mut(|b| {
|
||||
@@ -285,6 +294,9 @@ pub(crate) fn sanitize(bars: &mut Vec<CustomToolbar>) {
|
||||
s.retain(|id| tool_info(id).is_some() && seen.insert(id.clone()));
|
||||
}
|
||||
b.slots.retain(|s| !s.is_empty());
|
||||
let mut commands = BTreeSet::new();
|
||||
b.commands.retain(|id| !id.trim().is_empty() && !id.starts_with("tool:") && commands.insert(id.clone()));
|
||||
b.commands.truncate(MAX_COMMANDS);
|
||||
let old = std::mem::take(&mut b.last_used);
|
||||
for (first, slot) in b.slots.iter().filter_map(|s| Some((s.first()?, s))) {
|
||||
let at = crate::toolbar::slot_id(first);
|
||||
@@ -559,6 +571,41 @@ fn run_choice(app: &mut VectorcraftApp, choice: &ListManagerChoice) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The toolbar the `toolbar` param of `toolbar.addCommand` and `toolbar.removeCommand` names,
|
||||
/// which must be one made with New Toolbar: the Tools panel's toolbar holds tools only.
|
||||
fn command_target(ui: &UiState, p: &Value) -> Result<usize, String> {
|
||||
let name = target(ui, p)?.ok_or("toolbar (a toolbar's name) is required: only toolbars made with New Toolbar hold commands")?;
|
||||
index(ui, &name)
|
||||
}
|
||||
|
||||
/// Put the command button for the Command Palette result `id` in `bar`, moving it if it is there
|
||||
/// already: at place `at` among its command buttons (0 = the first; none: at the end). A command
|
||||
/// that is gone (an uninstalled plug-in's) can still move, but not be added. A tool, and a UI
|
||||
/// command that fails without params, can't be added.
|
||||
pub(crate) fn add_command(bar: &mut CustomToolbar, id: &str, at: Option<usize>) -> Result<(), String> {
|
||||
if id.starts_with("tool:") {
|
||||
return Err(format!("`{id}` is a tool: toolbar.addTool adds tools"));
|
||||
}
|
||||
if crate::shortcut_editor::ui_command_needs_params(id) {
|
||||
return Err(format!("`{id}` needs params, which a click on a button does not give"));
|
||||
}
|
||||
if !bar.commands.iter().any(|c| c == id) && !crate::palette::is_command(id) {
|
||||
return Err(format!("unknown command `{id}`"));
|
||||
}
|
||||
let mut list: Vec<String> = bar.commands.iter().filter(|c| *c != id).cloned().collect();
|
||||
if list.len() >= MAX_COMMANDS {
|
||||
return Err(format!("a toolbar holds at most {MAX_COMMANDS} commands"));
|
||||
}
|
||||
let at = match at {
|
||||
None => list.len(),
|
||||
Some(n) if n <= list.len() => n,
|
||||
Some(n) => return Err(format!("`at` must be a whole number from 0 to {} (got {n})", list.len())),
|
||||
};
|
||||
list.insert(at, id.to_string());
|
||||
bar.commands = list;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The commands of the toolbars made with New Toolbar; `None` for other ids.
|
||||
pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
|
||||
Some(match id {
|
||||
@@ -591,6 +638,25 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?;
|
||||
delete(app, name).map(|_| Value::Null)
|
||||
})(),
|
||||
"toolbar.addCommand" => (|| {
|
||||
let k = command_target(&app.ui, p)?;
|
||||
let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?;
|
||||
let at = match p.get("at") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(
|
||||
v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| format!("`at` must be 0 or a larger whole number (got {v})"))?,
|
||||
),
|
||||
};
|
||||
let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?;
|
||||
add_command(bar, id, at).map(|_| json!(bar.commands))
|
||||
})(),
|
||||
"toolbar.removeCommand" => (|| {
|
||||
let k = command_target(&app.ui, p)?;
|
||||
let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?;
|
||||
let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?;
|
||||
bar.commands.retain(|c| c != id);
|
||||
Ok(json!(bar.commands))
|
||||
})(),
|
||||
"window.toolbar.dock" => dock(app, p),
|
||||
"window.toolbar.float" => float(app, p),
|
||||
"window.toolbar.list" => {
|
||||
@@ -609,6 +675,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
"shown": panel_docking::visible(app, &panel),
|
||||
"double": double,
|
||||
"slots": b.slots,
|
||||
"commands": b.commands,
|
||||
"floating": docked.is_none(),
|
||||
"side": side_name(last_edge(&app.ui, &panel)),
|
||||
"order": docked.map(|(_, n)| *n),
|
||||
@@ -651,19 +718,100 @@ pub(crate) fn shown_tool(bar: &CustomToolbar, active: &'static str, tools: &[&'s
|
||||
Some(bar.last_used.get(crate::toolbar::slot_id(first)).and_then(|id| tools.iter().copied().find(|t| *t == id.as_str())).unwrap_or(first))
|
||||
}
|
||||
|
||||
/// Add Tool…, in the footer of the toolbar with id `id`: the + button opens a menu where, under Remove
|
||||
/// Tool, a click takes one of the toolbar's tools out; then every tool under the All Tools drawer's
|
||||
/// headings, where a click adds one at the end (dimmed: in the toolbar already). `measured`: the rail
|
||||
/// measures its footer, which draws the button alone.
|
||||
pub(crate) fn add_menu(app: &VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer: RailFooter, measured: bool) {
|
||||
let Some(bar) = app.ui.custom_toolbars.iter().find(|b| b.id == id) else { return };
|
||||
let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect();
|
||||
let plus = IconButton::new(IconId::new("plus")).label(tl!("Add Tool…")).popup(PopupKind::Menu).show(ui).response;
|
||||
// The rail measures its footer too: the menu opens from the button the rail shows.
|
||||
if measured || craft::ui::runtime::measure::active(ui.ctx()) {
|
||||
/// What a command button shows, worked out before its toolbar's footer is drawn.
|
||||
#[derive(Clone, Debug)]
|
||||
struct CommandLook {
|
||||
/// The Command Palette result it runs.
|
||||
id: String,
|
||||
/// Its label, name and command; none while the palette lists no result with its id (an
|
||||
/// uninstalled plug-in's command).
|
||||
text: Option<crate::palette::ButtonText>,
|
||||
}
|
||||
|
||||
impl CommandLook {
|
||||
/// The label the button shows: the command's, or its id while the command is gone.
|
||||
fn label(&self) -> &str {
|
||||
self.text.as_ref().map_or(self.id.as_str(), |t| t.label.as_str())
|
||||
}
|
||||
|
||||
/// Its full name, with the menu path that tells it apart from a command of the same label, or
|
||||
/// its id while the command is gone.
|
||||
fn name(&self) -> &str {
|
||||
self.text.as_ref().map_or(self.id.as_str(), |t| t.name.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// How each command button of the toolbar with id `id` looks now.
|
||||
fn command_looks(app: &mut VectorcraftApp, ui: &egui::Ui, id: u32) -> Vec<CommandLook> {
|
||||
let commands = app.ui.custom_toolbars.iter().find(|b| b.id == id).map(|b| b.commands.clone()).unwrap_or_default();
|
||||
let texts = crate::palette::button_texts(app, ui, &commands);
|
||||
commands.into_iter().zip(texts).map(|(id, text)| CommandLook { id, text }).collect()
|
||||
}
|
||||
|
||||
/// A command button on the toolbar named `bar`: the command's label, cut short with … when it is
|
||||
/// longer than the toolbar is wide, and its full name and shortcut in its tooltip. A click runs what a
|
||||
/// pick of the command in the Command Palette runs, and while the command's menu item is dimmed the
|
||||
/// button is dimmed too. A command that is gone shows its id, dimmed. Its context menu moves it up or
|
||||
/// down among the toolbar's command buttons (`place`: its place and how many there are) and takes it
|
||||
/// out; `measuring`: the rail measures its footer, which draws the button alone.
|
||||
fn command_button(app: &VectorcraftApp, ui: &mut egui::Ui, bar: &str, look: &CommandLook, place: (usize, usize), measuring: bool) {
|
||||
let shortcut = crate::menus::shortcut_of(app, &look.id).map(|c| c.display(crate::keymap::platform()));
|
||||
let tip = match (&look.text, shortcut) {
|
||||
(None, _) => format!("{}\n{}", look.id, crate::i18n::msg(&format!("command `{}` is not available right now", look.id))),
|
||||
(Some(t), Some(keys)) => format!("{} {keys}", t.name),
|
||||
(Some(t), None) => t.name.clone(),
|
||||
};
|
||||
let button = match &look.text {
|
||||
Some(t) => Button::command(t.command.clone()).label(look.label().to_string()),
|
||||
None => Button::new(look.label().to_string()).enabled(false),
|
||||
};
|
||||
let response = button.tooltip(tip).show(ui).response;
|
||||
if measuring {
|
||||
return;
|
||||
}
|
||||
let command = |verb: &str, tool: &str| CommandRef::with_params(verb, json!({ "tool": tool, "toolbar": bar.name }));
|
||||
let (i, n) = place;
|
||||
let moved = |at: usize| CommandRef::with_params("toolbar.addCommand", json!({ "command": look.id, "toolbar": bar, "at": at }));
|
||||
let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": bar }));
|
||||
Menu::context(look.name().to_string(), &response).show(ui, |ui, _| {
|
||||
MenuItem::command(moved(i.saturating_sub(1))).label(tl!("Move Up")).enabled(i > 0).show(ui);
|
||||
MenuItem::command(moved(i + 1)).label(tl!("Move Down")).enabled(i + 1 < n).show(ui);
|
||||
MenuItem::command(removed.clone()).label(tl!("Remove from Toolbar")).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The most commands the Add Command submenu lists for a search.
|
||||
const COMMAND_RESULTS: usize = 30;
|
||||
|
||||
/// Where the Add Command submenu of the toolbar with id `id` keeps the text of its search field.
|
||||
pub(crate) fn command_query_id(id: u32) -> egui::Id {
|
||||
egui::Id::unique(("custom-toolbar-command-query", id))
|
||||
}
|
||||
|
||||
/// Add Tool…, in the footer of the toolbar with id `id`, after the toolbar's command buttons
|
||||
/// ([`command_button`]): the + button opens a menu where, under Remove Tool, a click takes one of the
|
||||
/// toolbar's tools out; then every tool under the All Tools drawer's headings, where a click adds one
|
||||
/// at the end (dimmed: in the toolbar already); then, under Remove Command, the toolbar's command
|
||||
/// buttons by their full names, which a click takes out, and the Add Command submenu: a search field
|
||||
/// over the Command Palette's results other than tools, whose first [`COMMAND_RESULTS`] matches a
|
||||
/// click adds at the end (dimmed: on the toolbar already). `measured`: the rail measures its footer,
|
||||
/// which draws the buttons alone.
|
||||
pub(crate) fn add_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer: RailFooter, measured: bool) {
|
||||
let Some(bar) = app.ui.custom_toolbars.iter().find(|b| b.id == id) else { return };
|
||||
let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect();
|
||||
let name = bar.name.clone();
|
||||
let measuring = measured || craft::ui::runtime::measure::active(ui.ctx());
|
||||
let looks = command_looks(app, ui, id);
|
||||
for (i, look) in looks.iter().enumerate() {
|
||||
command_button(app, ui, &name, look, (i, looks.len()), measuring);
|
||||
}
|
||||
let plus = IconButton::new(IconId::new("plus")).label(tl!("Add Tool…")).popup(PopupKind::Menu).show(ui).response;
|
||||
// The rail measures its footer too: the menu opens from the button the rail shows.
|
||||
if measuring {
|
||||
return;
|
||||
}
|
||||
let command = |verb: &str, tool: &str| CommandRef::with_params(verb, json!({ "tool": tool, "toolbar": name }));
|
||||
let query_id = command_query_id(id);
|
||||
let mut query: String = ui.data(|d| d.get_temp(query_id)).unwrap_or_default();
|
||||
Menu::new(tl!("Add Tool…")).opened_by(&plus, Trigger::Click).show(ui, |ui, _| {
|
||||
if !held.is_empty() {
|
||||
MenuItem::heading(crate::i18n::colon(tl!("Remove Tool"))).show(ui);
|
||||
@@ -678,7 +826,35 @@ pub(crate) fn add_menu(app: &VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer
|
||||
MenuItem::command(command("toolbar.addTool", tool.id)).label(tool.label).enabled(!held.contains(&tool.id)).show(ui);
|
||||
}
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
if !looks.is_empty() {
|
||||
MenuItem::heading(crate::i18n::colon(tl!("Remove Command"))).show(ui);
|
||||
for look in &looks {
|
||||
let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": name }));
|
||||
MenuItem::command(removed).label(look.name().to_string()).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
}
|
||||
Menu::submenu_row(ui, tl!("Add Command"), |ui, cx| {
|
||||
// The field drives the submenu: Up and Down move its active row and Enter runs it, while
|
||||
// typing stays in the field.
|
||||
TextField::search(tl!("Search Commands"), Bind::bound(&mut query)).placeholder(tl!("Search Commands")).drives(cx.resolved.id).show(ui);
|
||||
if query.trim().is_empty() {
|
||||
Text::new(tl!("Type to find a command")).shade(Shade::Muted).show(ui);
|
||||
return;
|
||||
}
|
||||
let found = crate::palette::command_matches(app, ui, &query, COMMAND_RESULTS);
|
||||
if found.is_empty() {
|
||||
Text::new(tl!("No matching commands")).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
for (command, shown) in found {
|
||||
let on = !looks.iter().any(|l| l.id == command);
|
||||
let added = CommandRef::with_params("toolbar.addCommand", json!({ "command": command, "toolbar": name }));
|
||||
MenuItem::command(added).label(shown).enabled(on).show(ui);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(query_id, query));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -832,7 +1008,7 @@ mod tests {
|
||||
let names: Vec<String> = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect();
|
||||
assert_eq!(names, ["Mine", "Toolbar 1"]);
|
||||
let list = app.run("window.toolbar.list", json!({})).unwrap();
|
||||
let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null});
|
||||
let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "commands": [], "floating": true, "side": "left", "order": null});
|
||||
assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")]));
|
||||
}
|
||||
|
||||
@@ -876,7 +1052,10 @@ mod tests {
|
||||
assert!(app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Nope"})).is_err());
|
||||
let r = app.run("toolbar.removeTool", json!({"tool": "artboard", "toolbar": "Mine"})).unwrap();
|
||||
assert_eq!(r, json!([["pen", "curvature"]]));
|
||||
// Its command buttons go with it.
|
||||
app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
|
||||
let mine = find(&app.ui, "Mine").cloned().unwrap();
|
||||
assert_eq!(mine.commands, ["object.group"]);
|
||||
// Another workspace has its own toolbars (none); coming back brings Mine back.
|
||||
app.run("window.workspace", json!({"name": "Essentials"})).unwrap();
|
||||
assert!(app.ui.custom_toolbars.is_empty());
|
||||
@@ -1148,7 +1327,12 @@ mod tests {
|
||||
bars[0].last_used.set(slot("rectangle"), "pen".into());
|
||||
bars[4].last_used.set(slot("pen"), "curvature".into());
|
||||
bars[5].last_used.set(slot("pen"), "curvature".into());
|
||||
// Command buttons: each once, none for a tool or a blank id; one not known now stays.
|
||||
bars[4].commands = ["object.group", "tool:pen", " ", "object.group", "plugin:gone"].map(String::from).to_vec();
|
||||
bars[5].commands = (0..MAX_COMMANDS + 5).map(|i| format!("plugin:p{i}")).collect();
|
||||
sanitize(&mut bars);
|
||||
assert_eq!(bars[1].commands, ["object.group", "plugin:gone"]);
|
||||
assert_eq!(bars[2].commands.len(), MAX_COMMANDS);
|
||||
assert_eq!(bars.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["A", "B", "C"], "a name past {MAX_NAME} characters goes too");
|
||||
assert_eq!(bars.iter().map(|b| b.id).collect::<Vec<_>>(), [1, 3, 2], "the first has none, the third repeats the second's");
|
||||
assert_eq!(bars[0].last_used.get(slot("pen")), Some(&"curvature".to_string()));
|
||||
|
||||
@@ -8,10 +8,12 @@
|
||||
//! manifest's `budget`) has no Preview, since a run may take minutes: it runs in the background
|
||||
//! ([`crate::plugin_runs`]). A light filter that reports its progress (plug-in API level 2 with the
|
||||
//! `progress` permission) and calls no commands runs in the background too, with its progress and
|
||||
//! Cancel, when it runs at once or when OK runs it without a kept preview ([`in_background`]). A
|
||||
//! filter or live effect with commands of its own is a submenu named after it, holding its item and
|
||||
//! then its commands; a command with parameters opens the same dialog for them ([`open_command`]).
|
||||
//! A command whose manifest names another menu is listed in that menu instead ([`place_commands`]).
|
||||
//! Cancel, when it runs at once or when OK runs it without a kept preview ([`in_background`]). On the
|
||||
//! web every filter and plug-in command run here goes to a worker, and their dialogs have no Preview
|
||||
//! ([`crate::plugin_runs`]). A filter or live effect with commands of its own is a submenu named
|
||||
//! after it, holding its item and then its commands; a command with parameters opens the same dialog
|
||||
//! for them ([`open_command`]). A command whose manifest names another menu is listed in that menu
|
||||
//! instead ([`place_commands`]).
|
||||
//! Object › Plug-ins starts with Apply Last Filter and Last Filter…, which run the filter that last
|
||||
//! ran again with the same parameters or open its dialog with them, and a filter's dialog opens with
|
||||
//! the parameters it last ran with in the session ([`LastFilters`]).
|
||||
@@ -584,7 +586,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
/// Opens the dialog of filter `plugin`, or of its command `command`, with `m` the manifest it runs
|
||||
/// with, headed `heading`: the rows at `values`, with a live Preview for a light filter.
|
||||
/// with, headed `heading`: the rows at `values`, with a live Preview for a light filter. Where
|
||||
/// filters run in workers (the web build) the dialog has no Preview: a preview would run the plug-in
|
||||
/// on the page.
|
||||
fn open_filter(
|
||||
app: &mut VectorcraftApp,
|
||||
plugin: &Plugin,
|
||||
@@ -594,8 +598,9 @@ fn open_filter(
|
||||
values: Map<String, Value>,
|
||||
) -> Result<(), String> {
|
||||
let own = plugin.manifest();
|
||||
let light = own.budget == Budget::Light;
|
||||
let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: !light, ok: None };
|
||||
let heavy = own.budget == Budget::Heavy;
|
||||
let light = !heavy && !crate::plugin_runs::in_workers(app);
|
||||
let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: heavy, ok: None };
|
||||
let instance = command.as_deref().unwrap_or(plugin.id()).to_string();
|
||||
let (id, params) = open_hosted(app, KIND, &instance, m, values, look)?;
|
||||
let kind = Opened::Filter {
|
||||
@@ -645,9 +650,9 @@ fn in_background(m: &Manifest) -> bool {
|
||||
}
|
||||
|
||||
/// Runs filter `plugin` with `plugin.run`'s params `p`: at once, or in the background
|
||||
/// ([`in_background`]).
|
||||
/// ([`in_background`]). Where filters run in workers (the web build), every run does.
|
||||
fn run(app: &mut VectorcraftApp, plugin: &Plugin, p: Value) -> Result<Value, String> {
|
||||
match in_background(plugin.manifest()) {
|
||||
match in_background(plugin.manifest()) || crate::plugin_runs::in_workers(app) {
|
||||
false => app.run(CMD, p),
|
||||
true => crate::plugin_runs::start(app, p),
|
||||
}
|
||||
@@ -725,13 +730,23 @@ fn import_with(app: &mut VectorcraftApp, open: Value, values: Map<String, Value>
|
||||
|
||||
/// OK of a filter dialog: a filter keeps its previewed run as one undo step; a heavy one, which has
|
||||
/// no preview, and a light one that runs in the background ([`in_background`]) with Preview off or a
|
||||
/// failed preview, start in the background ([`run`]). A preview still shown when Preview was just
|
||||
/// turned off, or one that failed, is rolled back first.
|
||||
/// failed preview, start in the background ([`run`]). On the web the filter or its command always
|
||||
/// starts in a worker. A preview still shown when Preview was just turned off, or one that failed, is
|
||||
/// rolled back first.
|
||||
fn confirm_filter(app: &mut VectorcraftApp, kind: Opened, values: Map<String, Value>) -> Result<Value, String> {
|
||||
let Opened::Filter { plugin, command: own, preview, light, previewing, refused, .. } = kind else { return Ok(Value::Null) };
|
||||
let (cmd, p) = command(&plugin, own.as_deref(), values);
|
||||
let kept = light && previewing && app.session.in_interaction() && !refused;
|
||||
match registry::get(&plugin) {
|
||||
// On the web, with no Preview, the filter or its command always runs in a worker; a command
|
||||
// automation confirmed runs on the page and returns its result, as `routes` runs it.
|
||||
Some(found) if crate::plugin_runs::in_workers(app) && !(own.is_some() && app.automation_asked()) => {
|
||||
preview.cancel(app);
|
||||
match own {
|
||||
None => run(app, &found, p),
|
||||
Some(_) => crate::plugin_runs::start_command(app, &cmd, p),
|
||||
}
|
||||
}
|
||||
Some(found) if own.is_none() && in_background(found.manifest()) && !kept => {
|
||||
preview.cancel(app);
|
||||
run(app, &found, p)
|
||||
|
||||
@@ -297,7 +297,11 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
})(),
|
||||
"toolbar.reset" => (|| {
|
||||
if let Some(name) = crate::custom_toolbars::target(&app.ui, p)? {
|
||||
// A toolbar made with New Toolbar goes back to blank, as it was made.
|
||||
// A toolbar made with New Toolbar goes back to blank, as it was made, without its
|
||||
// command buttons too.
|
||||
if let Some(bar) = crate::custom_toolbars::find_mut(&mut app.ui, &name) {
|
||||
bar.commands.clear();
|
||||
}
|
||||
return edit_custom(app, &name, |cats| {
|
||||
cats.clear();
|
||||
Ok(())
|
||||
|
||||
@@ -3,8 +3,8 @@ use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Tall enough for the whole Basic toolbar and the whole drawer.
|
||||
const SCREEN: egui::Vec2 = vec2(1000.0, 4000.0);
|
||||
/// Tall enough for the whole Basic toolbar, the whole drawer and the whole Add Tool… menu.
|
||||
const SCREEN: egui::Vec2 = vec2(1000.0, 5000.0);
|
||||
/// The rail's Edit Toolbar button, by its access name.
|
||||
const EDIT: &str = "Edit Toolbar"; // PLAN: assumed `RailWords::edit_toolbar` in English
|
||||
/// The + button of a toolbar made with New Toolbar.
|
||||
@@ -566,3 +566,252 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
|
||||
assert!(slot_of(&app, tool).is_some(), "{tool}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The command buttons of the toolbar made with New Toolbar called Mine.
|
||||
fn mine_commands(app: &VectorcraftApp) -> Vec<String> {
|
||||
crate::custom_toolbars::find(&app.ui, "Mine").unwrap().commands.clone()
|
||||
}
|
||||
|
||||
/// `f` run with `app` and a `Ui` of one frame of `ctx` as the hosts run it ([`crate::testing::part_frame`]).
|
||||
fn in_pass<T>(app: &mut VectorcraftApp, ctx: &egui::Context, f: impl FnOnce(&mut VectorcraftApp, &egui::Ui) -> T) -> T {
|
||||
let mut f = Some(f);
|
||||
let mut got = None;
|
||||
let _ = crate::testing::part_frame(app, ctx, RawInput::default(), |app, ui| {
|
||||
if let Some(f) = f.take() {
|
||||
got = Some(f(app, ui));
|
||||
}
|
||||
});
|
||||
got.expect("the frame ran")
|
||||
}
|
||||
|
||||
/// `toolbar.addCommand` puts command buttons on a toolbar made with New Toolbar and moves them,
|
||||
/// `toolbar.removeCommand` takes them off, and a bad call changes nothing. Manage Toolbars' copy
|
||||
/// keeps them, and `toolbar.reset` takes them off with the tools.
|
||||
#[test]
|
||||
fn command_buttons_are_added_moved_and_removed_by_their_commands() {
|
||||
let mut app = app();
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
let added = app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
|
||||
assert_eq!(added, json!(["object.group"]));
|
||||
app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine"})).unwrap();
|
||||
app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine", "at": 0})).unwrap();
|
||||
assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "moved, not added twice");
|
||||
for (p, why) in [
|
||||
(json!({"command": "no.such", "toolbar": "Mine"}), "an unknown command"),
|
||||
(json!({"command": "tool:pen", "toolbar": "Mine"}), "a tool"),
|
||||
(json!({"command": "object.group", "toolbar": "Mine", "at": 2}), "a place past the end"),
|
||||
(json!({"command": "object.group", "toolbar": "Mine", "at": -1}), "a negative place"),
|
||||
(json!({"command": "toolbar.addTool", "toolbar": "Mine"}), "a command that needs params"),
|
||||
(json!({"command": "object.group"}), "no toolbar"),
|
||||
(json!({"toolbar": "Mine"}), "no command"),
|
||||
] {
|
||||
assert!(app.run("toolbar.addCommand", p.clone()).is_err(), "{why}: {p}");
|
||||
assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "{why} changes nothing");
|
||||
}
|
||||
assert!(app.run("toolbar.removeCommand", json!({"command": "object.group"})).is_err(), "no toolbar");
|
||||
let list = app.run("window.toolbar.list", json!({})).unwrap();
|
||||
assert_eq!(list[0]["commands"], json!(["object.path.cleanUp", "object.group"]));
|
||||
let copy = app.run("window.toolbar.duplicate", json!({"name": "Mine"})).unwrap();
|
||||
let copy = copy["toolbar"].as_str().unwrap().to_string();
|
||||
assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands, mine_commands(&app), "the copy has them");
|
||||
let left = app.run("toolbar.removeCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
|
||||
assert_eq!(left, json!(["object.path.cleanUp"]));
|
||||
app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap();
|
||||
app.run("toolbar.reset", json!({"toolbar": "Mine"})).unwrap();
|
||||
assert!(mine_commands(&app).is_empty(), "Reset makes the toolbar blank");
|
||||
assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands.len(), 2, "the copy keeps its own");
|
||||
}
|
||||
|
||||
/// What a frame drew inside the toolbar called Mine, by access name: (name, bounds, dimmed).
|
||||
fn on_mine(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64) -> Vec<(String, Rect, bool)> {
|
||||
frame(app, ctx, time, vec![]);
|
||||
let input = RawInput { time: Some(time + 0.05), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SCREEN)), ..Default::default() };
|
||||
let out = crate::testing::app_frame(app, ctx, input);
|
||||
let nodes: Vec<(String, Rect, bool)> = out
|
||||
.platform_output
|
||||
.accesskit_update
|
||||
.map(|u| u.nodes)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|(_, n)| {
|
||||
let b = n.bounds()?;
|
||||
let rect = Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32));
|
||||
Some((n.label()?.to_string(), rect, n.is_disabled()))
|
||||
})
|
||||
.collect();
|
||||
let bar = nodes.iter().filter(|(n, ..)| n == "Mine").map(|(_, r, _)| *r).max_by(|a, b| a.area().total_cmp(&b.area()));
|
||||
let Some(bar) = bar else { return vec![] };
|
||||
nodes.into_iter().filter(|(n, r, _)| n != "Mine" && bar.contains(r.center())).collect()
|
||||
}
|
||||
|
||||
/// The button inside the toolbar called Mine whose name is `name`: its bounds and whether it is dimmed.
|
||||
fn mine_button(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, name: &str) -> Option<(Rect, bool)> {
|
||||
on_mine(app, ctx, time).into_iter().find(|(n, ..)| n.trim() == name).map(|(_, r, off)| (r, off))
|
||||
}
|
||||
|
||||
/// A command button shows its command's label, without the ellipsis, and a click runs what the
|
||||
/// command's menu item runs. While that item would be dimmed, the button is dimmed too and a click
|
||||
/// runs nothing.
|
||||
#[test]
|
||||
fn a_command_button_runs_its_command_and_is_dimmed_while_it_cannot() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default());
|
||||
let ctx = ctx();
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
for c in ["object.group", "object.path.cleanUp"] {
|
||||
app.run("toolbar.addCommand", json!({"command": c, "toolbar": "Mine"})).unwrap();
|
||||
}
|
||||
let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.history.undo.len());
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
let (at, off) = mine_button(&mut app, &ctx, 0.0, "Group").expect("the button shows Group");
|
||||
assert!(off, "dimmed with nothing selected");
|
||||
let before = undo(&app);
|
||||
click(&mut app, &ctx, 1.0, at.center());
|
||||
assert_eq!(undo(&app), before, "a dimmed button runs nothing");
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let (at, off) = mine_button(&mut app, &ctx, 2.0, "Group").expect("the button shows Group");
|
||||
assert!(!off, "not dimmed with objects selected");
|
||||
click(&mut app, &ctx, 3.0, at.center());
|
||||
assert!(undo(&app) > before, "Group ran");
|
||||
assert!(mine_button(&mut app, &ctx, 4.0, "Clean Up").is_some(), "the button shows Clean Up");
|
||||
assert!(mine_button(&mut app, &ctx, 4.5, "Clean Up…").is_none(), "without the ellipsis");
|
||||
}
|
||||
|
||||
/// Command buttons are kept with the preferences, and a toolbar saved before toolbars held commands
|
||||
/// loads with none. A command that is gone, such as an uninstalled plug-in's, stays: its button is
|
||||
/// dimmed and shows its id, and Remove Command takes it off.
|
||||
#[test]
|
||||
fn a_missing_command_stays_dimmed_until_it_is_removed() {
|
||||
let mut app = app();
|
||||
let ctx = ctx();
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
|
||||
crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push("plugin:x".into());
|
||||
let kept = app.ui.custom_toolbars.clone();
|
||||
let prefs: crate::state::UiState = serde_json::from_slice(&serde_json::to_vec(&app.ui).unwrap()).unwrap();
|
||||
assert_eq!(prefs.sanitized().custom_toolbars, kept, "kept with the preferences, the missing command too");
|
||||
let mut old = serde_json::to_value(&kept[0]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("commands");
|
||||
let old: crate::state::CustomToolbar = serde_json::from_value(old).unwrap();
|
||||
assert!(old.commands.is_empty(), "an older toolbar loads without commands");
|
||||
let (_, off) = mine_button(&mut app, &ctx, 0.0, "plugin:x").expect("the button shows the command's id");
|
||||
assert!(off, "dimmed while it is gone");
|
||||
let left = app.run("toolbar.removeCommand", json!({"command": "plugin:x", "toolbar": "Mine"})).unwrap();
|
||||
assert_eq!(left, json!(["object.group"]));
|
||||
}
|
||||
|
||||
/// The footer looks up all its command buttons in one call: each id gets what a lookup of it alone
|
||||
/// gives, in order, and none for a tool, a command that needs params or a command that is gone.
|
||||
#[test]
|
||||
fn command_buttons_are_looked_up_together() {
|
||||
let mut app = app();
|
||||
let ctx = ctx();
|
||||
let ids: Vec<String> =
|
||||
["object.group", "tool:pen", "plugin:x", "toolbar.addTool", "object.path.cleanUp"].into_iter().map(str::to_string).collect();
|
||||
let together = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_texts(app, ui, &ids));
|
||||
let alone: Vec<_> = ids
|
||||
.iter()
|
||||
.map(|id| crate::palette::is_command(id).then(|| in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, id))).flatten())
|
||||
.collect();
|
||||
assert_eq!(together, alone);
|
||||
assert!(together[0].is_some() && together[4].is_some(), "Group and Clean Up are found: {together:?}");
|
||||
assert!(together[1..4].iter().all(Option::is_none), "a tool, a missing command and one that needs params: {together:?}");
|
||||
assert!(in_pass(&mut app, &ctx, |app, ui| crate::palette::button_texts(app, ui, &[])).is_empty());
|
||||
}
|
||||
|
||||
/// Add Tool…'s menu lists a toolbar's command buttons under Remove Command, where a click takes one
|
||||
/// off, and its Add Command submenu searches the Command Palette's results other than tools: a click
|
||||
/// on a match adds its button at the end of the toolbar.
|
||||
#[test]
|
||||
fn the_add_tool_menu_adds_and_removes_commands() {
|
||||
let mut app = app();
|
||||
let ctx = ctx();
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
|
||||
let id = crate::custom_toolbars::find(&app.ui, "Mine").unwrap().id;
|
||||
// The menu's items called `name`, top first: inside the menu, the Add Tool… node larger than the + button.
|
||||
let items = |nodes: &Nodes, name: &str| -> Vec<Rect> {
|
||||
let menu = named(nodes, ADD).into_iter().max_by(|a, b| a.area().total_cmp(&b.area())).expect("the menu is open");
|
||||
named(nodes, name).into_iter().filter(|r| menu.contains(r.center())).collect()
|
||||
};
|
||||
let open = |app: &mut VectorcraftApp, time: f64| -> Nodes {
|
||||
let nodes = settle(app, &ctx, time);
|
||||
if !named(&nodes, "Select:").is_empty() {
|
||||
return nodes;
|
||||
}
|
||||
let plus = inside(&nodes, ADD, one(&nodes, "Mine"));
|
||||
click(app, &ctx, time + 0.2, plus.center());
|
||||
settle(app, &ctx, time + 0.5)
|
||||
};
|
||||
let nodes = open(&mut app, 0.0);
|
||||
assert_eq!(named(&nodes, "Remove Command:").len(), 1, "a heading over the toolbar's commands");
|
||||
// The submenu lists the matches of its search; a click on one adds it at the end.
|
||||
ctx.data_mut(|d| d.insert_temp(crate::custom_toolbars::command_query_id(id), "clean up".to_string()));
|
||||
let row = items(&nodes, "Add Command");
|
||||
assert_eq!(row.len(), 1, "the Add Command row");
|
||||
let nodes = click(&mut app, &ctx, 1.0, row[0].center());
|
||||
let name = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, "object.path.cleanUp")).expect("Clean Up's result").name;
|
||||
let at = named(&nodes, &name).first().copied().unwrap_or_else(|| panic!("{name} is listed"));
|
||||
click(&mut app, &ctx, 2.0, at.center());
|
||||
assert_eq!(mine_commands(&app), ["object.group", "object.path.cleanUp"], "added at the end");
|
||||
let pen = in_pass(&mut app, &ctx, |app, ui| crate::palette::command_matches(app, ui, "pen", 30));
|
||||
assert!(!pen.is_empty() && pen.iter().all(|(id, _)| !id.starts_with("tool:")), "tools are not listed among the commands: {pen:?}");
|
||||
let twice = |name: &str| {
|
||||
let parts: Vec<&str> = name.split(" › ").collect();
|
||||
(1..=parts.len() / 2).any(|k| parts[..k] == parts[k..2 * k])
|
||||
};
|
||||
assert!(pen.iter().all(|(_, name)| !twice(name)), "a label that carries its menu path is not given it twice: {pen:?}");
|
||||
let toolbar = in_pass(&mut app, &ctx, |app, ui| crate::palette::command_matches(app, ui, "toolbar add", 30));
|
||||
assert!(toolbar.iter().all(|(id, _)| id != "toolbar.addTool" && id != "toolbar.addCommand"), "commands that need params: {toolbar:?}");
|
||||
// Under Remove Command, Group is listed by its full name, and a click takes it off.
|
||||
let name = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, "object.group")).expect("Group's result").name;
|
||||
let nodes = open(&mut app, 10.0);
|
||||
let group = items(&nodes, &name);
|
||||
assert!(!group.is_empty(), "{name} under Remove Command");
|
||||
click(&mut app, &ctx, 11.0, group[0].center());
|
||||
assert_eq!(mine_commands(&app), ["object.path.cleanUp"]);
|
||||
}
|
||||
|
||||
/// A button for a panel shows the panel, as the panel's Command Palette result does.
|
||||
#[test]
|
||||
fn a_panel_button_shows_its_panel() {
|
||||
let mut app = app();
|
||||
let ctx = ctx();
|
||||
let panel = crate::state::all_panels()
|
||||
.map(|(id, _)| id)
|
||||
.find(|id| !crate::panel_docking::visible(&app, id) && crate::palette::is_command(&format!("panel:{id}")))
|
||||
.expect("a hidden panel");
|
||||
let id = format!("panel:{panel}");
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap();
|
||||
let label = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, &id)).expect("the panel's result").label;
|
||||
let (at, _) = mine_button(&mut app, &ctx, 0.0, &label).unwrap_or_else(|| panic!("the button shows {label}"));
|
||||
click(&mut app, &ctx, 1.0, at.center());
|
||||
assert!(crate::panel_docking::visible(&app, panel), "{panel} is shown");
|
||||
}
|
||||
|
||||
/// A button for a plug-in's command that is not installed is dimmed and shows the command's id;
|
||||
/// once the plug-in is installed it shows the plug-in's name and can run, and when the plug-in is
|
||||
/// removed again it is dimmed again.
|
||||
#[test]
|
||||
fn a_plugin_command_button_works_again_when_the_plugin_returns() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default());
|
||||
let ctx = ctx();
|
||||
// A name no other test gives a plug-in.
|
||||
let filter = "test.UI.toolbar_command-probe";
|
||||
let id = format!("plugin:{filter}");
|
||||
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push(id.clone());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let gone = mine_button(&mut app, &ctx, 0.0, &id).map(|(_, off)| off);
|
||||
let manifest = format!(r#"{{"id":"{filter}","name":"Toolbar Probe","version":"1","kind":"filter","params":{{}}}}"#);
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let back = mine_button(&mut app, &ctx, 1.0, "Toolbar Probe").map(|(_, off)| off);
|
||||
let added = app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine", "at": 0}));
|
||||
vectorcraft_plugins::registry::remove(filter);
|
||||
let gone_again = mine_button(&mut app, &ctx, 2.0, &id).map(|(_, off)| off);
|
||||
assert_eq!(gone, Some(true), "dimmed, with its id, while it is not installed");
|
||||
assert_eq!(back, Some(false), "its name, and it can run, once it is installed");
|
||||
assert!(added.is_ok(), "an installed plug-in's command can be added: {added:?}");
|
||||
assert_eq!(gone_again, Some(true), "dimmed again once it is removed");
|
||||
}
|
||||
@@ -7828,6 +7828,15 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given s’ha omès un objecte de només lectura: retorneu-lo com a {{"id": …}} sol o tal com s’ha rebut
|
||||
@msg a string una cadena
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` un traç només té `paint`, `width`, `join`, `cap` i `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` una peça d’un efecte dinàmic de pintura només té `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` i `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` un traç només té `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` i `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` només pot ser true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` només és per a un efecte dinàmic que declara `paintOutput`, amb `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` ha de ser un nombre de 0 a 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} mode de fusió desconegut; `blend` és un de {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` ha de ser una llista d’un màxim de {MAX_LOOK_EFFECTS} registres
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un resultat porta com a màxim {MAX_RESULT_EFFECTS} registres d’efecte
|
||||
@msg this host takes no effects here aquest amfitrió no accepta efectes aquí
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} un traç ha de ser {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} un efecte ha de ser {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` un efecte en un farciment només retorna `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7441,6 +7441,15 @@ axis Y Axis osa Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objekt jen pro čtení byl vynechán: vraťte ho jako samotné {{"id": …}} nebo tak, jak byl předán
|
||||
@msg a string řetězec
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` tah má jen `paint`, `width`, `join`, `cap` a `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` část malujícího živého efektu má jen `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` a `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` tah má jen `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` a `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` může být jen true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` je jen pro živý efekt, který deklaruje `paintOutput`, s `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` musí být číslo od 0 do 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} neznámý režim míchání; `blend` je jedno z {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` musí být pole nejvýše {MAX_LOOK_EFFECTS} záznamů
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records výsledek nese nejvýše {MAX_RESULT_EFFECTS} záznamů efektů
|
||||
@msg this host takes no effects here tento hostitel zde nepřijímá žádné efekty
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} tah musí být {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} efekt musí být {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` efekt na výplni vrací jen `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -630,6 +630,15 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given et skrivebeskyttet objekt blev udeladt: returnér det, som {{"id": …}} alene eller som det blev givet
|
||||
@msg a string en streng
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` en streg har kun `paint`, `width`, `join`, `cap` og `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` et stykke fra en malet live-effekt har kun `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` og `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` en streg har kun `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` og `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` må kun være true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` er kun til en live-effekt, der angiver `paintOutput`, ved `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` skal være et tal fra 0 til 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} ukendt blandingstilstand; `blend` er en af {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` skal være en liste med højst {MAX_LOOK_EFFECTS} poster
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records et resultat bærer højst {MAX_RESULT_EFFECTS} effektposter
|
||||
@msg this host takes no effects here denne vært tager ikke imod effekter her
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} en streg skal være {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} en effekt skal være {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` en effekt på en udfyldning returnerer kun `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7022,6 +7022,15 @@ axis Y Axis Y-Achse
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given ein schreibgeschütztes Objekt wurde weggelassen: Geben Sie es zurück, als {{"id": …}} allein oder so, wie es übergeben wurde
|
||||
@msg a string eine Zeichenkette
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` eine Kontur hat nur `paint`, `width`, `join`, `cap` und `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` ein Teil eines malenden Live-Effekts hat nur `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` und `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` eine Kontur hat nur `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` und `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` darf nur true sein
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` gilt nur für einen Live-Effekt, der `paintOutput` angibt, mit `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` muss eine Zahl von 0 bis 1 sein
|
||||
@msg unknown blending mode; `blend` is one of {_1} unbekannter Mischmodus; `blend` ist einer von {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` muss eine Liste von höchstens {MAX_LOOK_EFFECTS} Einträgen sein
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records ein Ergebnis enthält höchstens {MAX_RESULT_EFFECTS} Effekteinträge
|
||||
@msg this host takes no effects here dieser Host nimmt hier keine Effekte an
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} eine Kontur muss {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} sein
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} ein Effekt muss {{"id", "params"?, "visible"?}} sein
|
||||
@msg an effect on a fill returns only `fills` ein Effekt auf einer Fläche gibt nur `fills` zurück
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7431,6 +7431,15 @@ axis Y Axis Άξονας Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given παραλείφθηκε ένα αντικείμενο μόνο για ανάγνωση: επιστρέψτε το ως {{"id": …}} μόνο ή όπως δόθηκε
|
||||
@msg a string συμβολοσειρά
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` ένα περίγραμμα έχει μόνο `paint`, `width`, `join`, `cap` και `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` ένα κομμάτι ζωντανού εφέ βαφής έχει μόνο `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` και `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` ένα περίγραμμα έχει μόνο `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` και `effects`
|
||||
@msg `appearanceOutput` may only be true Το `appearanceOutput` μπορεί να είναι μόνο true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 το `appearanceOutput` ισχύει μόνο για ζωντανό εφέ που δηλώνει `paintOutput`, με `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 το `opacity` πρέπει να είναι αριθμός από 0 έως 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} άγνωστη λειτουργία ανάμειξης· το `blend` είναι ένα από τα {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records το `effects` πρέπει να είναι πίνακας με το πολύ {MAX_LOOK_EFFECTS} εγγραφές
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records ένα αποτέλεσμα φέρει το πολύ {MAX_RESULT_EFFECTS} εγγραφές εφέ
|
||||
@msg this host takes no effects here αυτό το κεντρικό σύστημα δεν δέχεται εφέ εδώ
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} ένα περίγραμμα πρέπει να είναι {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} ένα εφέ πρέπει να είναι {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` ένα εφέ σε γέμισμα επιστρέφει μόνο `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7417,6 +7417,15 @@ axis Y Axis Eje Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given se omitió un objeto de solo lectura: devuélvalo como {{"id": …}} solo o tal como se recibió
|
||||
@msg a string una cadena
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` un trazo solo tiene `paint`, `width`, `join`, `cap` y `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` una pieza de un efecto dinámico de pintura solo tiene `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` y `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` un trazo solo tiene `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` y `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` solo puede ser true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` solo es para un efecto dinámico que declara `paintOutput`, con `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` debe ser un número de 0 a 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} modo de fusión desconocido; `blend` es uno de {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` debe ser una lista de {MAX_LOOK_EFFECTS} registros como máximo
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un resultado lleva como máximo {MAX_RESULT_EFFECTS} registros de efecto
|
||||
@msg this host takes no effects here este host no admite efectos aquí
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} un trazo debe ser {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} un efecto debe ser {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` un efecto en un relleno solo devuelve `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7508,6 +7508,15 @@ axis Y Axis Y-akseli
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given vain luku -objekti jätettiin pois: palauta se pelkkänä {{"id": …}}-muotona tai sellaisena kuin se annettiin
|
||||
@msg a string merkkijono
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` viivalla on vain `paint`, `width`, `join`, `cap` ja `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` maalaavan live-tehosteen osalla on vain `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` ja `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` viivalla on vain `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` ja `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` voi olla vain true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` on vain reaaliaikaiselle tehosteelle, joka ilmoittaa `paintOutput`-avaimen, tasolla `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` on oltava luku 0:sta 1:een
|
||||
@msg unknown blending mode; `blend` is one of {_1} tuntematon sekoitustila; `blend` on yksi seuraavista: {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` on oltava enintään {MAX_LOOK_EFFECTS} tietueen taulukko
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records tuloksessa on enintään {MAX_RESULT_EFFECTS} tehostetietuetta
|
||||
@msg this host takes no effects here tämä isäntä ei ota tässä vastaan tehosteita
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} viivan on oltava muotoa {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} tehosteen on oltava muotoa {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` täytön tehoste palauttaa vain kentän `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7437,6 +7437,15 @@ axis Y Axis Axe Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given un objet en lecture seule a été omis : renvoyez-le, sous la forme {{"id": …}} seul ou tel qu’il a été fourni
|
||||
@msg a string une chaîne
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` un contour a seulement `paint`, `width`, `join`, `cap` et `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` une pièce d’un effet dynamique de peinture a seulement `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` et `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` un contour a seulement `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` et `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` ne peut valoir que true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` est réservé à un effet dynamique qui déclare `paintOutput`, avec `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` doit être un nombre de 0 à 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} mode de fusion inconnu, `blend` vaut l’un de {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` doit être une liste d’au plus {MAX_LOOK_EFFECTS} enregistrements
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un résultat porte au plus {MAX_RESULT_EFFECTS} enregistrements d’effet
|
||||
@msg this host takes no effects here cet hôte n’accepte aucun effet ici
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} un contour doit être {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} un effet doit être {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` un effet sur un fond renvoie seulement `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6593,6 +6593,15 @@ arrowhead Feather पंख
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given एक केवल-पढ़ने योग्य ऑब्जेक्ट छोड़ दिया गया: इसे केवल {{"id": …}} के रूप में या जैसा दिया गया था वैसा लौटाएँ
|
||||
@msg a string एक स्ट्रिंग
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` स्ट्रोक में केवल `paint`, `width`, `join`, `cap` और `miterLimit` होते हैं
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` पेंट करने वाले लाइव इफ़ेक्ट के हिस्से में केवल `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` और `effects` होते हैं
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` स्ट्रोक में केवल `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` और `effects` होते हैं
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` केवल true हो सकता है
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` केवल `api` 3 पर ऐसे लाइव इफ़ेक्ट के लिए है जो `paintOutput` घोषित करता है
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` 0 से 1 तक की संख्या होनी चाहिए
|
||||
@msg unknown blending mode; `blend` is one of {_1} अज्ञात ब्लेंडिंग मोड; `blend` इनमें से एक है: {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` अधिकतम {MAX_LOOK_EFFECTS} रिकॉर्ड की सूची होनी चाहिए
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records एक परिणाम में अधिकतम {MAX_RESULT_EFFECTS} इफ़ेक्ट रिकॉर्ड होते हैं
|
||||
@msg this host takes no effects here यह होस्ट यहाँ कोई इफ़ेक्ट नहीं लेता
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} स्ट्रोक {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} होना चाहिए
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} इफ़ेक्ट {{"id", "params"?, "visible"?}} होना चाहिए
|
||||
@msg an effect on a fill returns only `fills` फ़िल पर इफ़ेक्ट केवल `fills` लौटाता है
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7426,6 +7426,15 @@ axis Y Axis Y tengely
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given kimaradt egy írásvédett objektum: adja vissza önmagában {{"id": …}} formában vagy úgy, ahogy megkapta
|
||||
@msg a string karakterlánc
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` a körvonalnak csak `paint`, `width`, `join`, `cap` és `miterLimit` kulcsa van
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` a festő élő effektus darabjának csak `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` és `effects` kulcsa van
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` a körvonalnak csak `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` és `effects` kulcsa van
|
||||
@msg `appearanceOutput` may only be true Az `appearanceOutput` értéke csak true lehet
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 az `appearanceOutput` csak `paintOutput` kulcsot megadó élő effektushoz használható, `api` 3 mellett
|
||||
@msg `opacity` must be a number from 0 to 1 az `opacity` értéke 0 és 1 közötti szám kell legyen
|
||||
@msg unknown blending mode; `blend` is one of {_1} ismeretlen keverési mód; a `blend` értéke ezek egyike: {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records az `effects` legfeljebb {MAX_LOOK_EFFECTS} bejegyzésből álló tömb lehet
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records egy eredmény legfeljebb {MAX_RESULT_EFFECTS} effektusbejegyzést tartalmazhat
|
||||
@msg this host takes no effects here ez a gazdagép itt nem fogad effektusokat
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} a körvonal formája {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} legyen
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} az effektus formája {{"id", "params"?, "visible"?}} legyen
|
||||
@msg an effect on a fill returns only `fills` a kitöltésen lévő effektus csak `fills` értéket ad vissza
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -511,6 +511,15 @@
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objek baca-saja dihilangkan: kembalikan objek itu, sebagai {{"id": …}} saja atau seperti yang diberikan
|
||||
@msg a string string
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` goresan hanya memiliki `paint`, `width`, `join`, `cap` dan `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` potongan efek langsung yang dicat hanya memiliki `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` dan `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` goresan hanya memiliki `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` dan `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` hanya boleh true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` hanya untuk efek langsung yang menyatakan `paintOutput`, pada `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` harus berupa angka dari 0 sampai 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} mode campuran tidak dikenal; `blend` adalah salah satu dari {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` harus berupa larik berisi paling banyak {MAX_LOOK_EFFECTS} catatan
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records satu hasil membawa paling banyak {MAX_RESULT_EFFECTS} catatan efek
|
||||
@msg this host takes no effects here host ini tidak menerima efek di sini
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} goresan harus berupa {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} efek harus berupa {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` efek pada isian hanya mengembalikan `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7061,6 +7061,15 @@ axis Y Axis Asse Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given è stato omesso un oggetto di sola lettura: restituiscilo come {{"id": …}} da solo o così come è stato fornito
|
||||
@msg a string una stringa
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` una traccia ha solo `paint`, `width`, `join`, `cap` e `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` un pezzo di un effetto dinamico di pittura ha solo `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` e `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` una traccia ha solo `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` e `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` può essere solo true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` vale solo per un effetto dinamico che dichiara `paintOutput`, con `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` deve essere un numero da 0 a 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} metodo di fusione sconosciuto; `blend` è uno di {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` deve essere un elenco di al massimo {MAX_LOOK_EFFECTS} record
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un risultato porta al massimo {MAX_RESULT_EFFECTS} record di effetto
|
||||
@msg this host takes no effects here questo host qui non accetta effetti
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} una traccia deve essere {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} un effetto deve essere {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` un effetto su un riempimento restituisce solo `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7136,6 +7136,15 @@ axis Y Axis Y 軸
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given 読み取り専用のオブジェクトが省かれています: {{"id": …}} だけの形か、渡されたとおりの形で返してください
|
||||
@msg a string 文字列
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` 線に使えるのは `paint`、`width`、`join`、`cap`、`miterLimit` だけです
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` ペイント型のライブ効果のピースに使えるのは `path`、`fillRule`、`fills`、`strokes`、`opacity`、`blend`、`effects` だけです
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` 線に使えるのは `paint`、`width`、`join`、`cap`、`miterLimit`、`opacity`、`blend`、`effects` だけです
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` には true のみ指定できます
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` は `paintOutput` を宣言した `api` 3 のライブ効果専用です
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` は 0 から 1 の数値にしてください
|
||||
@msg unknown blending mode; `blend` is one of {_1} 不明な描画モードです。`blend` は {_1} のいずれかです
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` は最大 {MAX_LOOK_EFFECTS} 件のレコードの配列にしてください
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records 1 つの結果に含められる効果レコードは最大 {MAX_RESULT_EFFECTS} 件です
|
||||
@msg this host takes no effects here このホストではここに効果を指定できません
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 線は {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} の形にしてください
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} 効果は {{"id", "params"?, "visible"?}} の形にしてください
|
||||
@msg an effect on a fill returns only `fills` 塗りの効果が返すのは `fills` だけです
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9546,6 +9546,15 @@ axis Y Axis Y ღერძი
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given გამოტოვებულია მხოლოდ წასაკითხი ობიექტი: დააბრუნეთ ის მხოლოდ {{"id": …}}-ის სახით ან ისე, როგორც მიიღეთ
|
||||
@msg a string სტრიქონი
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` კონტურს აქვს მხოლოდ `paint`, `width`, `join`, `cap` და `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` მხატვრული ცოცხალი ეფექტის ნაწილს აქვს მხოლოდ `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` და `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` კონტურს აქვს მხოლოდ `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` და `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` შეიძლება იყოს მხოლოდ true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` მხოლოდ ცოცხალი ეფექტისთვისაა, რომელიც აცხადებს `paintOutput`-ს, `api` 3-ზე
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` უნდა იყოს რიცხვი 0-დან 1-მდე
|
||||
@msg unknown blending mode; `blend` is one of {_1} შერევის უცნობი რეჟიმი; `blend` არის ერთ-ერთი: {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` უნდა იყოს მასივი არაუმეტეს {MAX_LOOK_EFFECTS} ჩანაწერით
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records შედეგი შეიცავს არაუმეტეს {MAX_RESULT_EFFECTS} ეფექტის ჩანაწერს
|
||||
@msg this host takes no effects here ეს ჰოსტი აქ ეფექტებს არ იღებს
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} კონტური უნდა იყოს {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} ეფექტი უნდა იყოს {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` შევსების ეფექტი აბრუნებს მხოლოდ `fills`-ს
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7033,6 +7033,15 @@ axis Y Axis Y축
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given 읽기 전용 개체가 빠졌습니다: {{"id": …}}만 있는 형태나 받은 그대로 반환하십시오
|
||||
@msg a string 문자열
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` 선에는 `paint`, `width`, `join`, `cap`, `miterLimit`만 있습니다
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` 페인트형 라이브 효과의 조각에는 `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend`, `effects`만 있습니다
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` 선에는 `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend`, `effects`만 있습니다
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput`에는 true만 지정할 수 있습니다
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput`은 `paintOutput`을 선언한 `api` 3의 라이브 효과에만 쓸 수 있습니다
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity`는 0에서 1 사이의 숫자여야 합니다
|
||||
@msg unknown blending mode; `blend` is one of {_1} 알 수 없는 혼합 모드입니다. `blend`는 {_1} 중 하나입니다
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects`는 최대 {MAX_LOOK_EFFECTS}개 레코드의 배열이어야 합니다
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records 결과 하나에는 효과 레코드가 최대 {MAX_RESULT_EFFECTS}개까지 들어갑니다
|
||||
@msg this host takes no effects here 이 호스트는 여기서 효과를 받지 않습니다
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 선은 {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 형태여야 합니다
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} 효과는 {{"id", "params"?, "visible"?}} 형태여야 합니다
|
||||
@msg an effect on a fill returns only `fills` 칠에 적용된 효과는 `fills`만 반환합니다
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -475,6 +475,15 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given een alleen-lezen object is weggelaten: geef het terug, als alleen {{"id": …}} of zoals het is gegeven
|
||||
@msg a string een string
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` een contour heeft alleen `paint`, `width`, `join`, `cap` en `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` een stuk van een geschilderd live-effect heeft alleen `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` en `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` een contour heeft alleen `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` en `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` mag alleen true zijn
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` is alleen voor een live-effect dat `paintOutput` opgeeft, bij `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` moet een getal van 0 tot 1 zijn
|
||||
@msg unknown blending mode; `blend` is one of {_1} onbekende overvloeimodus; `blend` is een van {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` moet een lijst van hoogstens {MAX_LOOK_EFFECTS} records zijn
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records een resultaat draagt hoogstens {MAX_RESULT_EFFECTS} effectrecords
|
||||
@msg this host takes no effects here deze host neemt hier geen effecten aan
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} een contour moet {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} zijn
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} een effect moet {{"id", "params"?, "visible"?}} zijn
|
||||
@msg an effect on a fill returns only `fills` een effect op een vulling geeft alleen `fills` terug
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7294,6 +7294,15 @@ axis Y Axis Oś Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given pominięto obiekt tylko do odczytu: zwróć go jako samo {{"id": …}} lub w postaci, w jakiej został przekazany
|
||||
@msg a string ciągiem znaków
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` obrys ma tylko `paint`, `width`, `join`, `cap` i `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` element malującego efektu dynamicznego ma tylko `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` i `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` obrys ma tylko `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` i `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` może mieć tylko wartość true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` dotyczy tylko efektu na żywo, który deklaruje `paintOutput`, z `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` musi być liczbą od 0 do 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} nieznany tryb mieszania; `blend` to jeden z {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` musi być tablicą najwyżej {MAX_LOOK_EFFECTS} rekordów
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records wynik zawiera najwyżej {MAX_RESULT_EFFECTS} rekordów efektów
|
||||
@msg this host takes no effects here ten host nie przyjmuje tu efektów
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} obrys musi mieć postać {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} efekt musi mieć postać {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` efekt wypełnienia zwraca tylko `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7340,6 +7340,15 @@ axis Y Axis Eixo Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given um objeto somente leitura foi omitido: retorne-o como {{"id": …}} sozinho ou como foi recebido
|
||||
@msg a string uma string
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` um traçado tem apenas `paint`, `width`, `join`, `cap` e `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` uma peça de um efeito dinâmico de pintura tem apenas `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` e `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` um traçado tem apenas `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` e `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` só pode ser true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` é só para um efeito dinâmico que declara `paintOutput`, com `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` deve ser um número de 0 a 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} modo de mesclagem desconhecido; `blend` é um de {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` deve ser uma lista de no máximo {MAX_LOOK_EFFECTS} registros
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records um resultado leva no máximo {MAX_RESULT_EFFECTS} registros de efeito
|
||||
@msg this host takes no effects here este host não aceita efeitos aqui
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} um traçado deve ser {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} um efeito deve ser {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` um efeito em um preenchimento retorna apenas `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7061,6 +7061,15 @@ axis Y Axis Ось Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given пропущен объект только для чтения: верните его как один {{"id": …}} или в том виде, в каком он был передан
|
||||
@msg a string строка
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` у обводки есть только `paint`, `width`, `join`, `cap` и `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` у части рисующего динамического эффекта есть только `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` и `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` у обводки есть только `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` и `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` может быть только true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` допустим только для динамического эффекта, который объявляет `paintOutput`, с `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` должно быть числом от 0 до 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} неизвестный режим наложения; `blend` принимает одно из значений {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` должен быть массивом не более чем из {MAX_LOOK_EFFECTS} записей
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records результат содержит не более {MAX_RESULT_EFFECTS} записей эффектов
|
||||
@msg this host takes no effects here этот хост здесь не принимает эффекты
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} обводка должна иметь вид {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} эффект должен иметь вид {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` эффект на заливке возвращает только `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7441,6 +7441,15 @@ axis Y Axis Y-axel
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given ett skrivskyddat objekt utelämnades: returnera det som enbart {{"id": …}} eller som det gavs
|
||||
@msg a string en sträng
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` en kontur har bara `paint`, `width`, `join`, `cap` och `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` en del av en målande live-effekt har bara `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` och `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` en kontur har bara `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` och `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` får bara vara true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` gäller bara en liveeffekt som anger `paintOutput`, med `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` måste vara ett tal från 0 till 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} okänt blandningsläge; `blend` är ett av {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` måste vara en lista med högst {MAX_LOOK_EFFECTS} poster
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records ett resultat har högst {MAX_RESULT_EFFECTS} effektposter
|
||||
@msg this host takes no effects here den här värden tar inte emot effekter här
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} en kontur måste vara {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} en effekt måste vara {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` en effekt på en fyllning returnerar bara `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7513,6 +7513,15 @@ axis Y Axis Y ekseni
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given salt okunur bir nesne atlandı: onu yalnızca {{"id": …}} olarak veya verildiği gibi döndürün
|
||||
@msg a string bir dize
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` bir konturda yalnızca `paint`, `width`, `join`, `cap` ve `miterLimit` bulunur
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` boyama türü canlı efektin bir parçasında yalnızca `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` ve `effects` bulunur
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` bir konturda yalnızca `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` ve `effects` bulunur
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` yalnızca true olabilir
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` yalnızca `paintOutput` bildiren, `api` 3 düzeyindeki canlı efekt içindir
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` 0 ile 1 arasında bir sayı olmalıdır
|
||||
@msg unknown blending mode; `blend` is one of {_1} bilinmeyen karışım modu; `blend` şunlardan biridir: {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` en fazla {MAX_LOOK_EFFECTS} kayıtlık bir dizi olmalıdır
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records bir sonuç en fazla {MAX_RESULT_EFFECTS} efekt kaydı taşır
|
||||
@msg this host takes no effects here bu ana bilgisayar burada efekt kabul etmez
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} bir kontur {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} biçiminde olmalıdır
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} bir efekt {{"id", "params"?, "visible"?}} biçiminde olmalıdır
|
||||
@msg an effect on a fill returns only `fills` dolgudaki bir efekt yalnızca `fills` döndürür
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7043,6 +7043,15 @@ axis Y Axis Вісь Y
|
||||
@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given пропущено об’єкт лише для читання: поверніть його як один {{"id": …}} або в тому вигляді, у якому його передано
|
||||
@msg a string рядок
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` обведення має лише `paint`, `width`, `join`, `cap` і `miterLimit`
|
||||
@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` частина малювального динамічного ефекту має лише `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` і `effects`
|
||||
@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` обведення має лише `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` і `effects`
|
||||
@msg `appearanceOutput` may only be true `appearanceOutput` може бути лише true
|
||||
@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` дозволено лише для динамічного ефекту, що оголошує `paintOutput`, з `api` 3
|
||||
@msg `opacity` must be a number from 0 to 1 `opacity` має бути числом від 0 до 1
|
||||
@msg unknown blending mode; `blend` is one of {_1} невідомий режим накладання; `blend` має одне зі значень {_1}
|
||||
@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` має бути масивом щонайбільше з {MAX_LOOK_EFFECTS} записів
|
||||
@msg a result carries at most {MAX_RESULT_EFFECTS} effect records результат містить щонайбільше {MAX_RESULT_EFFECTS} записів ефектів
|
||||
@msg this host takes no effects here цей хост тут не приймає ефектів
|
||||
@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} обведення має мати вигляд {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}}
|
||||
@msg an effect must be {{"id", "params"?, "visible"?}} ефект має мати вигляд {{"id", "params"?, "visible"?}}
|
||||
@msg an effect on a fill returns only `fills` ефект на заливці повертає лише `fills`
|
||||
|
||||
|
Can't render this file because it is too large.
|
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user