mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into feat/js-es2015-classes
This commit is contained in:
commit
6346157a3a
170 files changed
+9344
-1130
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:
|
||||
|
||||
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"
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -629,6 +629,15 @@ struct StartFile {
|
||||
record: StartRecord,
|
||||
}
|
||||
|
||||
impl Drop for StartFile {
|
||||
/// Frees the lock when the start releases the file. A child process that any thread starts holds
|
||||
/// a copy of the file's handle until it runs its program, and the lock is only freed by closing
|
||||
/// every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl StartFile {
|
||||
/// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is
|
||||
/// none or it can't be read). `Ok(None)` when another copy of the app holds it.
|
||||
|
||||
@@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
/// A log folder of its own for each test.
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -632,10 +630,23 @@ impl AsRef<std::path::Path> for TestDir {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
fn start_dir(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
/// A start that ends frees the start file even while another handle to it is open, as a child
|
||||
/// process that is starting holds one: the next start reads the file instead of taking it for
|
||||
/// another copy of the app that is starting.
|
||||
#[test]
|
||||
fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = start_dir("copy");
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the start holds the file");
|
||||
starting.ended();
|
||||
assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -661,7 +672,7 @@ fn issue_2243() -> Vec<Candidate> {
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let (dir, _spawns) = start_dir("crash");
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
@@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
/// an error, a restart on another adapter), leaves nothing out of the next.
|
||||
#[test]
|
||||
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
let (dir, _spawns) = start_dir("shown");
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
@@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let (dir, _spawns) = start_dir("listing");
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
@@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
/// start shows its first frame on the adapter that crashed, the adapter counts again.
|
||||
#[test]
|
||||
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
let (dir, _spawns) = start_dir("explicit");
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
@@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let (dir, _spawns) = start_dir("damaged");
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
|
||||
@@ -1034,19 +1034,5 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests only: while a test starts another program, the child briefly holds a copy of every file
|
||||
/// this process has open, until it runs that program. A file lock held through such a copy outlives
|
||||
/// its own handle, so a GPU start test that released the start file and opened it again found it
|
||||
/// still locked, as if another copy of the app were running, and failed. A test that starts a
|
||||
/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`].
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]).
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
mod tests;
|
||||
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
_lease: Lease,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
/// The profile's [`LEASE`], open and locked.
|
||||
struct Lease(File);
|
||||
|
||||
impl Lease {
|
||||
/// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it.
|
||||
fn take(root: &Path) -> io::Result<Option<Self>> {
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => Ok(Some(Self(lease))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
/// Frees the lease when the session ends, or when a session could not be started after the lock
|
||||
/// was taken. A child process that any thread starts holds a copy of the lease's handle until it
|
||||
/// runs its program, and the lock is only freed by closing every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
@@ -73,14 +99,13 @@ impl Session {
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let Some(lease) = Lease::take(root)? else { return Ok(None) };
|
||||
Self::record(lease, root, version, commit).map(Some)
|
||||
}
|
||||
|
||||
/// Write this launch's record while `lease` is held. On an error `lease` is dropped, which
|
||||
/// unlocks it.
|
||||
fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result<Self> {
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
@@ -90,7 +115,7 @@ impl Session {
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
Ok(Self { _lease: lease, path, own_record, previous_unclean })
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
@@ -258,6 +283,54 @@ mod tests {
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let first_copy = first._lease.0.try_clone().unwrap();
|
||||
first.complete().unwrap();
|
||||
let second = Session::begin(Some(&fixture.0), "second", None).unwrap();
|
||||
assert!(second.is_some(), "a completed session frees the lease");
|
||||
let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap());
|
||||
drop(second);
|
||||
assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease");
|
||||
drop((first_copy, second_copy));
|
||||
}
|
||||
|
||||
/// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a
|
||||
/// child process that is starting holds.
|
||||
fn locked_with_a_copy(root: &Path) -> (Lease, File) {
|
||||
let lease = Lease::take(root).unwrap().unwrap();
|
||||
let copy = lease.0.try_clone().unwrap();
|
||||
(lease, copy)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::create_dir(fixture.0.join(RECORD)).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record");
|
||||
std::fs::remove_dir(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
// A folder at the temporary file's name makes the write fail after the record was checked.
|
||||
let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id()));
|
||||
std::fs::create_dir(&temporary).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written");
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
std::fs::remove_dir(&temporary).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -145,6 +145,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
|
||||
// No test installs a launch's root in this process, so the settings folder stays the same here.
|
||||
assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others");
|
||||
install_fonts();
|
||||
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
|
||||
assert!(fonts.is_some(), "a home folder to keep the settings in");
|
||||
|
||||
@@ -457,10 +457,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
|
||||
/// process (nextest gives every test its own).
|
||||
/// Runs the test `name` of this module again in a child process of the test binary → whether
|
||||
/// this is that child. For a test that installs the process-wide root, which every test running
|
||||
/// beside it would then read as the settings folder.
|
||||
fn in_own_process(name: &str) -> bool {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return true;
|
||||
}
|
||||
// The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file.
|
||||
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
|
||||
let path = format!("{module}::{name}");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"{path} failed in its own process:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
/// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in
|
||||
/// a process of its own.
|
||||
#[test]
|
||||
fn the_installed_root_is_used_once_and_must_be_absolute() {
|
||||
if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") {
|
||||
return;
|
||||
}
|
||||
let dir = temp("installed-root");
|
||||
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
|
||||
install_data_root(dir.to_path_buf()).unwrap();
|
||||
|
||||
+110
-20
@@ -81,6 +81,11 @@ pub struct HitOptions {
|
||||
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
|
||||
/// hit the art on a layer whose Preview is off as painted, not in outline.
|
||||
pub ignore_layer_preview: bool,
|
||||
/// The selection tools: where a click hits nothing else, a closed path or compound path with
|
||||
/// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with
|
||||
/// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their
|
||||
/// outline only. [`hit_test`] and [`objects_at`] try every other object first.
|
||||
pub unfilled_interiors: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
@@ -94,6 +99,7 @@ impl Default for HitOptions {
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
@@ -417,11 +423,35 @@ impl Drop for DrawnOff {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a clipping path is being tested ([`InMask`]).
|
||||
static IN_MASK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone
|
||||
/// ([`takes_interior`]).
|
||||
struct InMask {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl InMask {
|
||||
fn set() -> Self {
|
||||
Self { was: IN_MASK.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InMask {
|
||||
fn drop(&mut self) {
|
||||
IN_MASK.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
let _mask = mask.then(InMask::set);
|
||||
f()
|
||||
}
|
||||
|
||||
@@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, pass, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break 'passes;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -980,7 +1016,18 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
return painted;
|
||||
}
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
/// One walk of [`hit_test_skipping`], with `opt` as given.
|
||||
fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
@@ -1524,7 +1571,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
hit_order(n, children, p).any(|i| {
|
||||
let _mask = (i == 0 && n.clips()).then(InMask::set);
|
||||
children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))
|
||||
})
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
@@ -1622,6 +1672,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1656,7 +1708,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if !near_decoration {
|
||||
return None;
|
||||
return inside();
|
||||
}
|
||||
}
|
||||
let bp = path.to_bezpath();
|
||||
@@ -1666,7 +1718,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
|
||||
return Some(HitKind::Fill);
|
||||
}
|
||||
None
|
||||
inside()
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
|
||||
@@ -1684,7 +1736,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
if n.appearance.has_visible_fill() {
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -1756,6 +1812,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths
|
||||
/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide.
|
||||
fn takes_interior(n: &Node, opt: HitOptions) -> bool {
|
||||
opt.unfilled_interiors
|
||||
&& !opt.outline
|
||||
&& !opt.path_only
|
||||
&& !IN_MASK.get()
|
||||
&& !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside
|
||||
/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths'
|
||||
/// fill does. Open subpaths are left out: they bound no area.
|
||||
fn closed_subpaths_at<'a>(paths: impl IntoIterator<Item = &'a PathData>, p: Point) -> BezPath {
|
||||
let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1;
|
||||
let mut bp = BezPath::new();
|
||||
for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) {
|
||||
for sp in pd.subpaths.iter().filter(|sp| sp.closed) {
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
|
||||
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
|
||||
/// stroke along its shape, a fill inside it except with Selection by Path Only.
|
||||
@@ -2032,13 +2112,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
|
||||
/// symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let walk = ArtWalk::open();
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
let pick = |opt: HitOptions| {
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
return None;
|
||||
}
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
|
||||
@@ -38,6 +38,168 @@ fn unfilled_interior_misses() {
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// The selection tools' options with unfilled closed paths hit inside.
|
||||
const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING };
|
||||
|
||||
/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer.
|
||||
fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId {
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let pts: Vec<Point> = points.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed));
|
||||
d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(INTERIORS), Some(frame));
|
||||
assert_eq!(at(SELECTING), None, "without the option, the interior misses");
|
||||
assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only");
|
||||
assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]);
|
||||
assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_is_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, false);
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None);
|
||||
}
|
||||
|
||||
/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit
|
||||
/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it.
|
||||
#[test]
|
||||
fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let dot = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(&d, 50.0), Some(dot));
|
||||
assert_eq!(at(&d, 20.0), Some(frame));
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]);
|
||||
// The topmost of two unfilled frames is hit inside both.
|
||||
let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true);
|
||||
assert_eq!(at(&d, 20.0), Some(inner));
|
||||
assert_eq!(at(&d, 5.0), Some(frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))];
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
|
||||
compound.appearance = look().into();
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(15.0), Some(id));
|
||||
assert_eq!(at(50.0), None, "in the hole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_and_clipping_paths_are_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let guide = stroked(&mut d, &FRAME, true);
|
||||
if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) {
|
||||
*g = true;
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide");
|
||||
// A clip group whose art covers only part of its unfilled clipping path.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(25.0), Some(art));
|
||||
assert_eq!(at(75.0), None, "inside the mask where no art paints");
|
||||
assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty());
|
||||
}
|
||||
|
||||
/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled
|
||||
/// compound clipping path are not.
|
||||
#[test]
|
||||
fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() {
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 2,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let repeat = |d: &mut Document, source: Node| {
|
||||
let r = d.alloc_id();
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] })))
|
||||
.unwrap();
|
||||
r
|
||||
};
|
||||
// Copies at 0..40 and 60..100.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look());
|
||||
let r = repeat(&mut d, frame);
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r));
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies");
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))];
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let r = repeat(&mut d, clip);
|
||||
assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art");
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints");
|
||||
}
|
||||
|
||||
/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what
|
||||
/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline.
|
||||
#[test]
|
||||
fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art());
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look());
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))];
|
||||
let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS);
|
||||
assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame");
|
||||
assert_eq!(at(20.0), Some(vec![1]), "inside the frame");
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
|
||||
@@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
|
||||
|
||||
static LOADER: OnceLock<Loader> = OnceLock::new();
|
||||
|
||||
std::thread_local! {
|
||||
/// Open checks use previews rather than loading placed documents for drawing.
|
||||
static PREVIEWS_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Restores whether only previews are used when an open check ends, including on unwind.
|
||||
struct PreviewsOnly(bool);
|
||||
|
||||
impl Drop for PreviewsOnly {
|
||||
fn drop(&mut self) {
|
||||
PREVIEWS_ONLY.with(|p| p.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an open check using placed documents' previews instead of loading their art on this
|
||||
/// thread. Nested checks keep the scope active until the outer check ends. This prevents an
|
||||
/// open check and drawing from recursively loading each other's nested files.
|
||||
pub fn with_previews<T>(check: impl FnOnce() -> T) -> T {
|
||||
let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true)));
|
||||
check()
|
||||
}
|
||||
|
||||
/// Register how files are read (the first registration stays).
|
||||
pub fn set_loader(l: Loader) {
|
||||
// Already set: the same loader, registered by another session.
|
||||
@@ -454,8 +476,12 @@ impl Cache {
|
||||
}
|
||||
|
||||
/// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a
|
||||
/// placed document from. `None` when it can't be read (or no loader is registered).
|
||||
/// placed document from. `None` when it can't be read, no loader is registered, or an open check
|
||||
/// uses [`with_previews`].
|
||||
pub fn read(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
|
||||
if PREVIEWS_ONLY.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
if let Some(e) = cache().get(&p.key, false, Some(bytes)) {
|
||||
return Some(e);
|
||||
}
|
||||
@@ -738,6 +764,22 @@ mod tests {
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// Nested open checks skip both new and cached art, and restore ordinary reads afterward.
|
||||
#[test]
|
||||
fn open_checks_leave_placed_documents_for_drawing_afterward() {
|
||||
set_loader(stub_loader);
|
||||
let p = placed("open-check-1");
|
||||
let bytes = Arc::new(b"leaf".to_vec());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
with_previews(|| {
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
});
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
}
|
||||
|
||||
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
|
||||
/// names its resources get.
|
||||
#[test]
|
||||
|
||||
@@ -122,7 +122,8 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF, and the work its import takes.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# The work `.ai` blends take to be checked and made live.
|
||||
# The work `.ai` blends take to be checked and made live, and how many included EPS open checks
|
||||
# an open performs.
|
||||
vectorcraft-eps = { workspace = true, features = ["work-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
|
||||
@@ -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
|
||||
)]
|
||||
|
||||
@@ -333,11 +333,18 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
|
||||
}
|
||||
|
||||
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
|
||||
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
|
||||
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
|
||||
/// of the drag.
|
||||
/// under it ([`reach_samples`]), besides the whole of each curved segment, which is measured once
|
||||
/// however many there are: a drag measures no more than this many pieces plus one for each curved
|
||||
/// segment of the paths it searches. Shared equally by the curved segments that come within its
|
||||
/// reach, it is enough to search 300,000 pt of curve within the default reach of the drag.
|
||||
const MAX_REACH_PIECES: usize = 1 << 17;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many pieces of curve [`reach_samples`] measured against a drag on this thread.
|
||||
static PIECES_MEASURED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The box around the control points of `s`, which holds all of `s`.
|
||||
fn control_box(s: CubicBez) -> Rect {
|
||||
Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3)
|
||||
@@ -529,13 +536,24 @@ fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize {
|
||||
/// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within
|
||||
/// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample
|
||||
/// out of reach; the others are halved until their control polygon is no longer than half the
|
||||
/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the
|
||||
/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach
|
||||
/// at its middle. Each piece measures only the stretches near
|
||||
/// reach, or until fewer than the two halves are left in this segment's `budget` or in `shared`,
|
||||
/// the pieces the whole drag may still measure past the first piece of each segment, and then give
|
||||
/// one sample: in reach at the piece's middle or at its place nearest the drag when either is in
|
||||
/// reach, otherwise out of reach at its middle. Both halves of a piece are taken from `budget` and
|
||||
/// from `shared` before either is measured, so a search measures no more than one piece besides
|
||||
/// what it takes from them. Each piece measures only the stretches near
|
||||
/// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag
|
||||
/// per halving, plus the stretches near each piece.
|
||||
fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) {
|
||||
*budget = budget.saturating_sub(1);
|
||||
fn reach_samples(
|
||||
c: CubicBez,
|
||||
(t0, t1): (f64, f64),
|
||||
(pts, of): (&[Point], &[usize]),
|
||||
radius: f64,
|
||||
(budget, shared): (&mut usize, &mut usize),
|
||||
out: &mut Vec<(f64, bool)>,
|
||||
) {
|
||||
#[cfg(test)]
|
||||
PIECES_MEASURED.set(PIECES_MEASURED.get() + 1);
|
||||
let s = c.subsegment(t0..t1);
|
||||
let mid = 0.5 * (t0 + t1);
|
||||
let near = stretches_near(pts, of, control_box(s), radius);
|
||||
@@ -544,7 +562,7 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
return;
|
||||
}
|
||||
let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3);
|
||||
if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 {
|
||||
if len <= (radius / 2.0).max(1e-3) || *budget < 2 || *shared < 2 || mid <= t0 || mid >= t1 {
|
||||
// The piece's middle, or the place on it nearest the drag when the middle is out of reach.
|
||||
let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius {
|
||||
(mid, true)
|
||||
@@ -555,8 +573,10 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
out.push(sample);
|
||||
return;
|
||||
}
|
||||
reach_samples(c, (t0, mid), (pts, &near), radius, budget, out);
|
||||
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
|
||||
*budget -= 2;
|
||||
*shared -= 2;
|
||||
reach_samples(c, (t0, mid), (pts, &near), radius, (&mut *budget, &mut *shared), out);
|
||||
reach_samples(c, (mid, t1), (pts, &near), radius, (budget, shared), out);
|
||||
}
|
||||
|
||||
/// `sp` cut where the reach of the drag crosses its curved segments, and whether each
|
||||
@@ -565,8 +585,11 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
|
||||
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
|
||||
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
|
||||
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
|
||||
fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<bool>) {
|
||||
/// the reach of the drag ([`reach_samples`]): each curved segment is measured whole, and then up
|
||||
/// to `share` more pieces of it are measured while the drag's `shared` pieces last, so the segments
|
||||
/// in reach share the search equally whatever order they come in, and a segment searched after
|
||||
/// the pieces run out is still found where its middle or its place nearest the drag is in reach.
|
||||
fn mark_reached(sp: &SubPath, reach: &DragReach, (share, shared): (usize, &mut usize)) -> (SubPath, Vec<bool>) {
|
||||
let (pts, radius) = (reach.pts, reach.radius);
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect();
|
||||
@@ -578,7 +601,7 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<
|
||||
let c = sp.segment(i);
|
||||
let (mut samples, mut budget) = (vec![], share);
|
||||
let near = reach.near_rect(control_box(c.subsegment(0.0..1.0)));
|
||||
reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples);
|
||||
reach_samples(c, (0.0, 1.0), (pts, &near), radius, (&mut budget, &mut *shared), &mut samples);
|
||||
// Stretches of samples alike, in order: (in reach, first, last).
|
||||
let mut runs: Vec<(bool, usize, usize)> = vec![];
|
||||
for (k, s) in samples.iter().enumerate() {
|
||||
@@ -623,15 +646,16 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<
|
||||
|
||||
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
|
||||
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
|
||||
/// that anchor's place (VectorCraft's own rule).
|
||||
fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
/// that anchor's place (VectorCraft's own rule). `search` is each curved segment's share of the
|
||||
/// drag's search and the pieces the drag has left ([`mark_reached`]).
|
||||
fn smooth_subpath(sp: &SubPath, reach: &DragReach, search: (usize, &mut usize), tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
if sp.anchors.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let radius = reach.radius;
|
||||
let near = &|q: Point| reach.in_reach(q, 0.0);
|
||||
// A drag along a segment smooths it even when its anchors are out of reach.
|
||||
let (sp, marked) = mark_reached(sp, reach, share);
|
||||
let (sp, marked) = mark_reached(sp, reach, search);
|
||||
let sp = &sp;
|
||||
if !marked.iter().any(|m| *m) {
|
||||
return None;
|
||||
@@ -948,15 +972,17 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
paths.push((id, path_of(&st.doc, id)?.0));
|
||||
}
|
||||
let reach = DragReach::new(&pts, radius);
|
||||
// Each curved segment in reach gets the same share of the search, whatever order they come in.
|
||||
// Each curved segment in reach gets the same share of the search, whatever order they come in,
|
||||
// and all of them together measure no more than `MAX_REACH_PIECES` pieces past their first.
|
||||
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum();
|
||||
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
for (id, pd) in paths {
|
||||
let mut changed = false;
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) {
|
||||
.map(|sp| match smooth_subpath(sp, &reach, (share, &mut shared), tol, sigma) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
@@ -1304,19 +1330,106 @@ mod tests {
|
||||
assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring());
|
||||
}
|
||||
|
||||
/// How many pieces `f` makes [`reach_samples`] measure on this thread.
|
||||
fn pieces_measured(f: impl FnOnce()) -> usize {
|
||||
let before = PIECES_MEASURED.get();
|
||||
f();
|
||||
PIECES_MEASURED.get() - before
|
||||
}
|
||||
|
||||
/// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more
|
||||
/// pieces than the budget it is given, and a search with none left gives one sample.
|
||||
/// than one piece besides the drag's `MAX_REACH_PIECES`, counting the pieces it halves as well
|
||||
/// as those it samples, and a search with none of the drag's pieces left measures the curve
|
||||
/// once and gives one sample, whatever share of its own it has.
|
||||
#[test]
|
||||
fn searching_a_segment_under_a_drag_stays_within_its_budget() {
|
||||
let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0));
|
||||
let pts: Vec<Point> = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect();
|
||||
let all = drag_stretches(&pts);
|
||||
let mut budget = MAX_REACH_PIECES;
|
||||
let (mut budget, mut shared) = (MAX_REACH_PIECES, MAX_REACH_PIECES);
|
||||
let (mut first, mut second) = (vec![], vec![]);
|
||||
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first);
|
||||
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second);
|
||||
assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len());
|
||||
assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample");
|
||||
let measured = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut budget, &mut shared), &mut first));
|
||||
assert!(measured <= MAX_REACH_PIECES + 1, "{measured} pieces measured");
|
||||
assert!(first.len() <= measured && first.len() > 1, "{} samples", first.len());
|
||||
assert!(shared < 2, "{shared} pieces left");
|
||||
let mut fresh = MAX_REACH_PIECES;
|
||||
let again = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut fresh, &mut shared), &mut second));
|
||||
assert_eq!((again, second.len()), (1, 1), "the drag's pieces are spent, so the next search gives one sample");
|
||||
}
|
||||
|
||||
/// One curved segment `w` pt wide from `(x, y)`, bowed `h` pt up.
|
||||
fn bow((x, y): (f64, f64), w: f64, h: f64) -> CubicBez {
|
||||
CubicBez::new(Point::new(x, y), Point::new(x + w / 3.0, y + h), Point::new(x + 2.0 * w / 3.0, y + h), Point::new(x + w, y))
|
||||
}
|
||||
|
||||
/// An open subpath of the curved segments `segs`, each starting where the one before ends.
|
||||
fn chain(segs: &[CubicBez]) -> SubPath {
|
||||
let mut anchors: Vec<Anchor> = vec![];
|
||||
for s in segs {
|
||||
match anchors.last_mut() {
|
||||
Some(last) => *last = Anchor::with_handles(s.p0, last.h_in, s.p1),
|
||||
None => anchors.push(Anchor::with_handles(s.p0, s.p0, s.p1)),
|
||||
}
|
||||
anchors.push(Anchor::with_handles(s.p3, s.p2, s.p3));
|
||||
}
|
||||
SubPath::new(anchors, false)
|
||||
}
|
||||
|
||||
/// A drag along two subpaths of 21,845 curved segments 100 pt long each, which share the search
|
||||
/// three pieces to a segment, and past a third of 1,000 curved segments far from the drag: every
|
||||
/// segment is measured whole and the whole drag measures no more than `MAX_REACH_PIECES` pieces
|
||||
/// past those, though each segment in reach would halve its pieces while its share lasts. Each
|
||||
/// segment in reach, the last one included, is halved once with its share of three, so the
|
||||
/// segments searched first leave the later ones their share.
|
||||
#[test]
|
||||
fn a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each() {
|
||||
let row = |(x, y): (f64, f64), n: u32| chain(&(0..n).map(|i| bow((x + f64::from(i) * 100.0, y), 100.0, 8.0)).collect::<Vec<_>>());
|
||||
let subs = [row((0.0, 0.0), 21_845), row((3_000_000.0, 0.0), 21_845), row((0.0, 1e6), 1000)];
|
||||
let pts = [Point::new(-10.0, 0.0), Point::new(6_000_000.0, 0.0)];
|
||||
let segments: usize = subs.iter().map(SubPath::segment_count).sum();
|
||||
assert_eq!(segments, 2 * 21_845 + 1000);
|
||||
let reach = DragReach::new(&pts, 12.0);
|
||||
let in_reach = segments_in_reach(&PathData::new(subs.to_vec()), &reach);
|
||||
assert_eq!(in_reach, 2 * 21_845, "the far segments are not counted");
|
||||
let share = (MAX_REACH_PIECES / in_reach).max(1);
|
||||
assert_eq!(share, 3);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
let mut marks = vec![];
|
||||
let measured = pieces_measured(|| {
|
||||
for sp in &subs {
|
||||
marks.push(mark_reached(sp, &reach, (share, &mut shared)).1);
|
||||
}
|
||||
});
|
||||
assert!(measured >= segments && measured <= segments + MAX_REACH_PIECES, "{measured} pieces measured for {segments} segments");
|
||||
assert_eq!((measured, shared), (segments + 2 * in_reach, MAX_REACH_PIECES - 2 * in_reach), "every segment in reach is halved once");
|
||||
assert!(marks[0].iter().all(|m| *m), "the first path's anchors are all on the drag");
|
||||
}
|
||||
|
||||
/// More than `MAX_REACH_PIECES` short curved segments in reach are each measured once, and a
|
||||
/// segment searched after the drag's pieces are spent is still found in reach where only a
|
||||
/// narrow stretch of it, away from its middle, comes near the drag.
|
||||
#[test]
|
||||
fn every_curved_segment_is_searched_after_the_drags_pieces_run_out() {
|
||||
let n = 140_000;
|
||||
let tiny = chain(&(0..n).map(|i| bow((f64::from(i) * 4.0, 0.0), 4.0, 1.0)).collect::<Vec<_>>());
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(f64::from(n) * 4.0, 0.0)];
|
||||
let reach = DragReach::new(&pts, 12.0);
|
||||
let share = (MAX_REACH_PIECES / segments_in_reach(&PathData::single(tiny.clone()), &reach).max(1)).max(1);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
let measured = pieces_measured(|| {
|
||||
mark_reached(&tiny, &reach, (share, &mut shared));
|
||||
});
|
||||
assert_eq!(measured, 140_000, "each segment is measured whole once");
|
||||
// An arch 1,000 pt wide and 300 pt high, with the drag on it a quarter of the way along.
|
||||
let arch = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 400.0), Point::new(1000.0, 400.0), Point::new(1000.0, 0.0));
|
||||
let sp = chain(&[arch]);
|
||||
let hit = [arch.eval(0.25)];
|
||||
assert!(dist_to_polyline(&hit, arch.eval(0.5)) > 12.0, "the arch's middle is out of reach");
|
||||
let mut spent = 0;
|
||||
let (out, marked) = mark_reached(&sp, &DragReach::new(&hit, 12.0), (MAX_REACH_PIECES, &mut spent));
|
||||
assert_eq!(out.anchors.len(), 3, "{out:?}");
|
||||
assert_eq!(marked, vec![false, true, false]);
|
||||
assert!(out.anchors[1].p.distance(hit[0]) <= 12.0, "{out:?}");
|
||||
}
|
||||
|
||||
/// A small piece of curve is measured only against the few stretches of a drag of 100,000
|
||||
@@ -1384,14 +1497,14 @@ mod tests {
|
||||
assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures");
|
||||
let share = (MAX_REACH_PIECES / in_reach).max(1);
|
||||
let mut got = None;
|
||||
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share)));
|
||||
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, (share, &mut { MAX_REACH_PIECES }))));
|
||||
assert!(marks < 100_000, "{marks} measures");
|
||||
let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0);
|
||||
let smoothed = smooth_subpath(&sp, &reach, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0);
|
||||
assert!(smoothed.is_some());
|
||||
let all = linear(&pts, 12.0);
|
||||
assert_eq!(segments_in_reach(&pd, &all), in_reach);
|
||||
assert_eq!(Some(mark_reached(&sp, &all, share)), got);
|
||||
assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed);
|
||||
assert_eq!(Some(mark_reached(&sp, &all, (share, &mut { MAX_REACH_PIECES }))), got);
|
||||
assert_eq!(smooth_subpath(&sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0), smoothed);
|
||||
}
|
||||
|
||||
/// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer
|
||||
@@ -1444,10 +1557,20 @@ mod tests {
|
||||
let in_reach = segments_in_reach(&pd, &all);
|
||||
assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
|
||||
assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
assert_eq!(
|
||||
mark_reached(sp, &grid, (share, &mut { MAX_REACH_PIECES })),
|
||||
mark_reached(sp, &all, (share, &mut { MAX_REACH_PIECES })),
|
||||
"path {k}, reach {radius}, drag {:?}",
|
||||
pts.first()
|
||||
);
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let want = smooth_subpath(sp, &all, share, 2.5, sigma);
|
||||
assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
let want = smooth_subpath(sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma);
|
||||
assert_eq!(
|
||||
smooth_subpath(sp, &grid, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma),
|
||||
want,
|
||||
"path {k}, reach {radius}, drag {:?}",
|
||||
pts.first()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,9 +403,8 @@ impl DocSettings {
|
||||
if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn {
|
||||
self.rows = 0;
|
||||
}
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
// While rows are set, `grid_columns` gives the columns they make; the stored columns stay as
|
||||
// they were given, and are the ones a later layout without rows uses.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ type PlacedPages = Vec<(u32, bool, vectorcraft_doc::PageBox)>;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many placed PDF or `.ai` pages [`page_fonts`] read on this thread.
|
||||
/// Tests: how many placed PDF, `.ai` or EPS pages [`page_fonts`] read on this thread.
|
||||
pub(crate) static PAGES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many linked `.vectorcraft` files had their preview and PDF read on this thread,
|
||||
/// to keep them in the rewritten copy.
|
||||
@@ -196,16 +196,41 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
/// The fonts of the type on `pages` of the PDF, `.ai` or EPS file `name` (`bytes`, found at
|
||||
/// `path`), and on the placed documents that art holds (an EPS file whose bytes a legacy `.ai` or
|
||||
/// EPS file includes), [`MAX_NESTED_PAGES`] deep; none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
nested_page_fonts(name, bytes, path, pages, 0)
|
||||
}
|
||||
|
||||
/// The most placed documents [`page_fonts`] reads inside one another.
|
||||
const MAX_NESTED_PAGES: usize = 8;
|
||||
|
||||
/// [`page_fonts`], `depth` placed documents in.
|
||||
fn nested_page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages, depth: usize) -> BTreeSet<super::fonts::UsedFont> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
if super::place::document::is_pdf(name, bytes) {
|
||||
if super::place::document::is_pdf(name, bytes) || super::place::document::is_postscript(bytes) {
|
||||
for &(page, bounding, page_box) in pages {
|
||||
#[cfg(test)]
|
||||
PAGES_READ.with(|c| c.set(c.get() + 1));
|
||||
if let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) {
|
||||
fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes));
|
||||
let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) else { continue };
|
||||
fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes));
|
||||
if depth + 1 >= MAX_NESTED_PAGES {
|
||||
continue;
|
||||
}
|
||||
let mut inner = Vec::new();
|
||||
let patterns = a.doc.patterns.iter().flat_map(|p| p.art.iter().map(|n| &**n));
|
||||
for n in a.doc.layers.iter().map(|l| &**l).chain(a.doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(&a.nodes) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind {
|
||||
inner.push(p.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
for p in inner {
|
||||
// Only the bytes the art keeps: its own file isn't looked for.
|
||||
let Some(blob) = a.doc.images.get(&p.key).filter(|b| !b.is_proxy()) else { continue };
|
||||
fonts.extend(nested_page_fonts(p.link.name(), &blob.bytes, &p.link.path, &vec![(p.page(), p.bounding, p.page_box)], depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,7 +344,7 @@ impl<'a> Collector<'a> {
|
||||
// Different linked documents can reuse the same stale absolute path yet
|
||||
// resolve it to distinct local assets. Keep a mapping per document.
|
||||
let mut local = BTreeMap::<String, Copied>::new();
|
||||
// The fonts of the type on the PDF and `.ai` pages placed linked.
|
||||
// The fonts of the type on the PDF, `.ai` and EPS pages placed linked.
|
||||
let mut placed_fonts = BTreeSet::new();
|
||||
let mut placed = BTreeMap::<String, PlacedPages>::new();
|
||||
let linked_files = |doc: &Document| match lookup {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file
|
||||
//! from a file, with `link`): one locked object showing an artboard of the document, a page of the
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`].
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`]. An EPS file whose bytes a `.ai` file's editing
|
||||
//! data includes opens as one too, read from those bytes.
|
||||
//!
|
||||
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
|
||||
//! art it shows is read from them the way placing the file without Link reads it
|
||||
@@ -223,6 +224,27 @@ impl Drop for Reading {
|
||||
}
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// How many placed documents [`read_document`] is reading inside one another on this thread.
|
||||
static DRAWING: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A placed document being read for drawing ([`DRAWING`]): the count goes down when this goes.
|
||||
struct Drawing;
|
||||
|
||||
impl Drawing {
|
||||
/// `None` when [`MAX_NESTED_READS`] are being read.
|
||||
fn enter() -> Option<Self> {
|
||||
DRAWING.with(|d| (d.get() < MAX_NESTED_READS).then(|| d.set(d.get() + 1))).map(|()| Drawing)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Drawing {
|
||||
fn drop(&mut self) {
|
||||
DRAWING.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads).
|
||||
fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
|
||||
let mut children: Vec<Arc<Node>> = nodes.into_iter().map(Arc::new).collect();
|
||||
@@ -234,11 +256,22 @@ fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
|
||||
|
||||
/// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents
|
||||
/// ([`vectorcraft_doc::placed_document::set_loader`]).
|
||||
/// `None` past [`MAX_NESTED_READS`] placed documents read inside one another: opening a file can
|
||||
/// draw the placed documents in it, whose files can place others.
|
||||
pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
let _drawing = Drawing::enter()?;
|
||||
#[cfg(test)]
|
||||
DOCUMENT_READS.with(|n| n.set(n.get() + 1));
|
||||
let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, "draw").ok()?;
|
||||
Some((a.doc, group(a.nodes, a.clip), a.frame))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// Placed documents read for drawing on this thread, for tests that count work.
|
||||
pub(crate) static DOCUMENT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `p`'s file read again, while it is the file it was read from (how the document model gets it
|
||||
/// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]).
|
||||
pub(crate) fn read_file_again(p: &PlacedDocument) -> Option<Vec<u8>> {
|
||||
|
||||
+218
-10
@@ -207,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).
|
||||
@@ -341,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 {
|
||||
@@ -523,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.
|
||||
@@ -543,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)
|
||||
@@ -934,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());
|
||||
@@ -946,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)? {
|
||||
@@ -964,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)
|
||||
}
|
||||
|
||||
@@ -1025,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,
|
||||
@@ -1081,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) {
|
||||
@@ -1190,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())
|
||||
@@ -1387,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));
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1115,6 +1115,82 @@ fn package_reads_no_placed_pdf_page_without_copy_fonts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Copy Fonts on, Package reads the type of a placed EPS file whose bytes a `.ai` file's
|
||||
/// editing data included, as it reads a placed PDF page's.
|
||||
#[test]
|
||||
fn package_reads_a_placed_eps_files_type_for_copy_fonts() {
|
||||
use cmd::package::PAGES_READ;
|
||||
use vectorcraft_testkit::ai;
|
||||
let dir = Folder::new("package-placed-eps-fonts");
|
||||
let eps =
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n";
|
||||
let src = dir.file("art/shape.eps");
|
||||
write(&src, eps.as_bytes());
|
||||
let src = src.replace('\\', "/");
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n({src})`\n%%BeginDocument: {src}\n{eps}\n%%EndDocument\n~\n%AI5_EndPlace\n"
|
||||
);
|
||||
let doc_path = dir.file("poster.ai");
|
||||
let page = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET";
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)).as_bytes(), page));
|
||||
let mut s = session();
|
||||
open(&mut s, &doc_path);
|
||||
let mut placed = 0;
|
||||
s.doc().unwrap().doc.visit_placed(|_, _| placed += 1);
|
||||
assert_eq!(placed, 1);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let before = PAGES_READ.with(std::cell::Cell::get);
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(PAGES_READ.with(std::cell::Cell::get) - before, 1, "{r}");
|
||||
let listed = |r: &Value| r["fonts"].as_u64().unwrap_or(0) + r["skippedFonts"].as_array().map_or(0, |a| a.len() as u64);
|
||||
assert_eq!(listed(&r), 1, "the type's font: {r}");
|
||||
|
||||
// Type only in an EPS file that the placed one, a legacy-format file, includes in turn.
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let typed =
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Courier findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n";
|
||||
let inner = format!("[1 0 0 1 0 0] 0 0 60 60 (inner.eps) `\n%%BeginDocument: inner.eps\n{typed}%%EndDocument\n~\n");
|
||||
let outer = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n\
|
||||
%%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\
|
||||
{inner}LB\n%AI5_EndLayer--\nshowpage\n%%EOF\n"
|
||||
);
|
||||
write(&dir.file("art/shape.eps"), outer.as_bytes());
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page));
|
||||
open(&mut s, &doc_path);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out2"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(listed(&r), 1, "the inner file's font: {r}");
|
||||
|
||||
// The included file is only in a pattern definition, outside the page's nodes.
|
||||
let pattern = format!("%AI3_BeginPattern: (Type)\n(Type) 0 0 60 60\n0 A\n0 Xw\n{inner}E\n%AI3_EndPattern\n");
|
||||
let outer = outer.replace(&inner, "").replace("%AI5_BeginLayer", &format!("{pattern}%AI5_BeginLayer"));
|
||||
let a = cmd::place::document::document_art("shape.eps", outer.as_bytes(), Some(&src), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap();
|
||||
let pattern = a.doc.pattern("Type").expect("the pattern definition is read");
|
||||
let mut placements = 0;
|
||||
for n in &pattern.art {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| {
|
||||
assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)), "the type is only in the included file");
|
||||
if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind {
|
||||
placements += 1;
|
||||
let blob = &a.doc.images[&p.key];
|
||||
assert!(!blob.is_proxy());
|
||||
assert_eq!(blob.bytes.as_slice(), typed.as_bytes());
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(placements, 1, "the pattern holds the included file");
|
||||
for n in &a.nodes {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_))));
|
||||
}
|
||||
write(&dir.file("art/shape.eps"), outer.as_bytes());
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page));
|
||||
open(&mut s, &doc_path);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out3"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(listed(&r), 1, "the pattern's included file's font: {r}");
|
||||
}
|
||||
|
||||
/// `dir/art/badge.ai`, saved without its PDF part, its art placing each of `pics` (600 × 300 px,
|
||||
/// with a 2×1 preview) → its path.
|
||||
fn ai_placing(dir: &Folder, pics: &[&str]) -> String {
|
||||
|
||||
@@ -934,6 +934,127 @@ fn an_ai_file_that_places_itself_opens() {
|
||||
assert_eq!(found, [at], "{r}");
|
||||
}
|
||||
|
||||
/// A placed EPS file whose bytes a `.ai` file's editing data includes (between `%%BeginDocument:`
|
||||
/// and `%%EndDocument`) opens as a placed document of those bytes: it draws its art with its file
|
||||
/// missing, and its file found unchanged is neither missing nor modified. A native save keeps the
|
||||
/// bytes, so the copy reopens and draws without the file.
|
||||
#[test]
|
||||
fn a_placed_eps_file_included_in_an_ai_files_editing_data_draws_without_its_file() {
|
||||
use vectorcraft_testkit::ai;
|
||||
let dir = Folder::new("placed-eps-in-ai");
|
||||
// The file draws red and the page blue, so each check shows which one drew.
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor\n0 0 60 60 rectfill\n%%EOF\n";
|
||||
let (red, blue) = ([255, 0, 0], [0, 0, 255]);
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n(/no/such/folder/src/shape.eps)`\n\
|
||||
%%BeginDocument: /no/such/folder/src/shape.eps\n{eps}\n%%EndDocument\n%AI17_Begin_Content_if_version_gt:24 12\n\
|
||||
%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"
|
||||
);
|
||||
let doc_path = dir.file("poster.ai");
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &place));
|
||||
write(&doc_path, &ai::ai(data.as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
let shown = |s: &Session| {
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true);
|
||||
let [r, g, b, _] = img.pixel(50, 50);
|
||||
[r, g, b]
|
||||
};
|
||||
let one = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut found = vec![];
|
||||
d.visit_placed(|n, p| found.push((n.id, p.clone())));
|
||||
let [(id, p)] = &found[..] else { panic!("one placed document: {found:?}") };
|
||||
(*id, p.clone(), d.images[&p.key].clone())
|
||||
};
|
||||
let mut s = session();
|
||||
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("shape.eps"), "{r}");
|
||||
let (id, p, blob) = one(&s);
|
||||
assert_eq!((blob.bytes.as_slice(), blob.mime.as_str()), (eps.as_bytes(), "application/postscript"));
|
||||
assert_eq!(p.link.relative.as_deref(), Some("src/shape.eps"));
|
||||
let at = bounds(&s, id);
|
||||
assert!((at.x0 - 20.0).abs() < 0.01 && (at.y0 - 20.0).abs() < 0.01 && (at.width() - 60.0).abs() < 0.01, "{at:?}");
|
||||
assert!(near(shown(&s), red), "its art draws: {:?}", shown(&s));
|
||||
|
||||
write(&dir.file("src/shape.eps"), eps.as_bytes());
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
|
||||
assert!(near(shown(&s), red));
|
||||
|
||||
let copy = dir.file("copy.vectorcraft");
|
||||
save(&mut s, ©);
|
||||
std::fs::remove_file(dir.file("src/shape.eps")).unwrap();
|
||||
open(&mut s, ©);
|
||||
let (_, _, blob) = one(&s);
|
||||
assert_eq!(blob.bytes.as_slice(), eps.as_bytes(), "the bytes are saved");
|
||||
assert!(near(shown(&s), red), "and draw: {:?}", shown(&s));
|
||||
|
||||
// A file named as PostScript of another kind, or with a name that doesn't say, draws the same.
|
||||
for name in ["shape.ps", "shape", "shape.dat"] {
|
||||
let named = place.replace("shape.eps", name);
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &named)).as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
open(&mut s, &doc_path);
|
||||
let (_, p, blob) = one(&s);
|
||||
assert_eq!((p.link.name(), blob.mime.as_str()), (name, "application/postscript"));
|
||||
assert!(near(shown(&s), red), "{name} draws: {:?}", shown(&s));
|
||||
}
|
||||
|
||||
// Bytes that can't be read leave the placed file unread: the file is read from its PDF part,
|
||||
// and the object comes in as what the page draws there.
|
||||
let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, broken))).as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert!(near(shown(&s), blue), "the page's art: {:?} {r}", shown(&s));
|
||||
}
|
||||
|
||||
/// A synthetic EPS file that includes another placed EPS file, `depth` levels deep.
|
||||
fn nested_included_eps(depth: usize) -> String {
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let mut eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n10 20 40 30 rectfill\n%%EOF\n".to_string();
|
||||
for _ in 0..depth {
|
||||
eps = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\
|
||||
%%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\
|
||||
[1 0 0 1 0 0] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\nLB\n%AI5_EndLayer--\nshowpage\n%%EOF\n"
|
||||
);
|
||||
}
|
||||
eps
|
||||
}
|
||||
|
||||
/// Open checks and drawing must not recursively multiply each other's work.
|
||||
#[test]
|
||||
fn placed_eps_files_included_open_work_is_bounded() {
|
||||
let dir = Folder::new("placed-eps-open-work");
|
||||
let path = dir.file("deep.eps");
|
||||
write(&path, nested_included_eps(12).as_bytes());
|
||||
let mut s = session();
|
||||
let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get);
|
||||
let checks = vectorcraft_eps::included_eps_reads();
|
||||
open(&mut s, &path);
|
||||
let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get) - drawings;
|
||||
let checks = vectorcraft_eps::included_eps_reads() - checks;
|
||||
eprintln!("included EPS work: {drawings} drawing reads, {checks} open checks");
|
||||
// At most 8 drawing loads, each with at most 8 parses for checks, plus the outer import's 8.
|
||||
// Repeated structural reads share completed checks within each chain.
|
||||
assert!(drawings <= 8, "{drawings} drawing reads, {checks} open checks");
|
||||
assert!(checks <= 8 * 8 + 8, "{drawings} drawing reads, {checks} open checks");
|
||||
assert!(drawings > 0 && checks > 0, "both read paths were exercised");
|
||||
}
|
||||
|
||||
/// A legacy-format file (version 7 specification §16) placing an EPS file whose bytes it includes,
|
||||
/// which is such a file in turn, 300 deep: it opens, reading a bounded number of them.
|
||||
#[test]
|
||||
fn placed_eps_files_included_300_deep_open() {
|
||||
let dir = Folder::new("placed-eps-300-deep");
|
||||
let path = dir.file("deep.eps");
|
||||
write(&path, nested_included_eps(300).as_bytes());
|
||||
let mut s = session();
|
||||
open(&mut s, &path);
|
||||
let mut placed = 0;
|
||||
s.doc().unwrap().doc.visit_placed(|_, _| placed += 1);
|
||||
assert_eq!(placed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() {
|
||||
let dir = Folder::new("placed-ai-linked");
|
||||
|
||||
@@ -8032,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"));
|
||||
|
||||
@@ -52,6 +52,9 @@ fn a_click_outside_an_outside_stroke_selects_it() {
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 20, "align": "outside"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// Object Selection by Path Only: the inside of the unfilled square takes no click of its own,
|
||||
// so only the stroke is tested.
|
||||
s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap();
|
||||
// 0.8 × the weight outside the path: past where a centred stroke (plus the tolerance) reaches.
|
||||
assert_eq!(click(&mut s, 84.0, 200.0), [r]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
@@ -59,6 +62,9 @@ fn a_click_outside_an_outside_stroke_selects_it() {
|
||||
s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach");
|
||||
// With it off, a click inside the unfilled square selects it (#9175).
|
||||
s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap();
|
||||
assert_eq!(click(&mut s, 116.0, 200.0), [r]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4950,6 +4950,37 @@ proptest! {
|
||||
survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose placed EPS files have their bytes included between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` (one on `%_` lines, one with a nested document and counted data in it),
|
||||
/// damaged, opened and drawn: their bytes are read as an EPS file when drawn.
|
||||
#[test]
|
||||
fn ai_placed_eps_files_with_included_bytes_never_panic(
|
||||
cut in 0usize..4_000,
|
||||
edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', '`', '~', 'E', 'D'])), 0..12),
|
||||
) {
|
||||
use vectorcraft_testkit::ai;
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 40\n%%EndComments\n0 0 1 setrgbcolor\n0 0 60 40 rectfill\n%%EOF\n";
|
||||
let nested = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n%%BeginDocument: c.eps\nnewpath\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n";
|
||||
let place = |path: &str, matrix: &str, doc: &str| {
|
||||
format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n{matrix} 0 0 60 40 4 4 0\n({path})`\n%%BeginDocument: {path}\n{doc}\n%%EndDocument\n\
|
||||
%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"
|
||||
)
|
||||
};
|
||||
let hidden: String = place("/tmp/b.eps", "[1 0 0 1 20 20]", eps).lines().map(|l| format!("%_{l}\n")).collect();
|
||||
let body = format!("{}{hidden}{}", place("/tmp/a.eps", "[1 0 0 1 20 20]", eps), place("/tmp/c.eps", "[1 0 0 1 0 0]", nested));
|
||||
let fixture = ai::editing_data(200.0, 100.0, &ai::layer("L", &body));
|
||||
// A session reads placed documents' files when they are drawn.
|
||||
let _ = vectorcraft_engine::Session::new();
|
||||
let whole = vectorcraft_engine::cmd::fileio::load("x.ai", &ai::ai(fixture.as_bytes(), "0 0 1 rg 20 20 60 40 re f"));
|
||||
let mut placed = 0;
|
||||
whole.iter().for_each(|l| l.doc.visit_placed(|_, _| placed += 1));
|
||||
prop_assert!(placed == 3 && fixture.len() < 4_000, "{placed} placed documents, {} bytes: {:?}", fixture.len(), whole.map(|l| l.warnings));
|
||||
let text = mutate_text(&fixture, cut, &edits);
|
||||
let file = ai::ai(text.as_bytes(), "0 0 1 rg 20 20 60 40 re f");
|
||||
survive("hostile .ai placed EPS files with included bytes", || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type
|
||||
/// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai`
|
||||
/// writer writes them) is damaged: read from its editing data alone and beside a page.
|
||||
@@ -6390,6 +6421,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
|
||||
"\n%%BeginData: 14 Binary Bytes\n",
|
||||
"\n%%BeginBinary: 99999999999\n",
|
||||
"\n%%BeginData: 3 Hex Lines\n",
|
||||
// A placed EPS file's bytes included in the data: one drawn, one with a box it can't
|
||||
// take, one on `%_` lines.
|
||||
"\n%%BeginDocument: a.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n0 0 1 setrgbcolor 0 0 9 9 rectfill\n%%EndDocument\n",
|
||||
"\n%%BeginDocument: a.eps\n%!PS\n%%BoundingBox: 0 0 1e308 -5\n%%EndDocument\n",
|
||||
"\n%_%%BeginDocument: a.eps\n%_%!PS\n%_0 0 9 9 rectfill\n%_%%EndDocument\n",
|
||||
"[1 0 0 1 0 0] 0 0 1e308 1e308 4 4 0 (a.eps) `",
|
||||
"\n%AI5_EndPlace\n",
|
||||
"Xm",
|
||||
"50 -50 -100 -100 5000 -2000 Xm",
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -9,7 +9,8 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only).
|
||||
# `vectorcraft_eps::blend_work` and `vectorcraft_eps::included_eps_reads` for other crates' tests
|
||||
# (dev-dependencies only).
|
||||
work-count = []
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -280,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result<Rect, String> {
|
||||
Ok(Rect::new(0.0, 0.0, urx - llx, ury - lly))
|
||||
}
|
||||
|
||||
/// An EPS or PostScript file's bounding box (`%%HiResBoundingBox` when it has one) in its own
|
||||
/// space, as `[llx, lly, urx, ury]`, read from its comments; `None` without one.
|
||||
pub(crate) fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> {
|
||||
Dsc::read(program(bytes).ok()?).bbox
|
||||
}
|
||||
|
||||
/// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data`
|
||||
/// (else what its page prints, as any EPS).
|
||||
pub fn import_with(bytes: &[u8], editing_data: bool) -> Result<Imported, String> {
|
||||
|
||||
@@ -62,12 +62,12 @@ pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color,
|
||||
read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
BLEND_BUDGET, LINKED_PREVIEWS, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with,
|
||||
parsed_type_color, read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
palette, read_beside, read_in, symbols, variables,
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedEps, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes,
|
||||
graphic_styles, palette, read_beside, read_in, symbols, variables,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use style::ART_STYLE_PARSES;
|
||||
|
||||
@@ -59,6 +59,9 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str {
|
||||
pub(super) const MAX_PENDING: usize = 64;
|
||||
/// The most envelopes and warped text objects one import draws to check; more keep their drawn art.
|
||||
pub(crate) const MAX_CHECKED: usize = 256;
|
||||
/// The most comparisons with pages those checks make in one import, one for each page an object
|
||||
/// is on ([`drawn_alike`]); an object that needs more keeps its drawn art.
|
||||
pub(crate) const MAX_PAGE_COMPARISONS: usize = 4 * MAX_CHECKED;
|
||||
/// The most strokes with dashes aligned to corners one import draws to check against their drawn
|
||||
/// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks.
|
||||
pub(crate) const MAX_DASH_CHECKS: usize = 256;
|
||||
@@ -664,13 +667,31 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt
|
||||
}
|
||||
|
||||
/// The differences from their drawn art that the live envelopes and warped type of one import may
|
||||
/// add up to, as shares of the page drawn as the page check draws it: half of what that check allows
|
||||
/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so they never make the file open from its PDF part
|
||||
/// instead.
|
||||
/// add up to on each page the art may be compared with, as shares of that page drawn as the page
|
||||
/// check draws it: half of what that check allows ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]),
|
||||
/// so they never make the file open from its PDF part instead. Each page has its own share.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Spent {
|
||||
pub(super) any: f64,
|
||||
pub(super) solid: f64,
|
||||
/// Each page with the shares of it spent so far: of pixels that differ at all, and of those
|
||||
/// whose neighbors all differ too.
|
||||
pub(super) pages: Vec<(Rect, f64, f64)>,
|
||||
/// How many comparisons with pages have been made ([`MAX_PAGE_COMPARISONS`]).
|
||||
pub(super) compared: usize,
|
||||
}
|
||||
|
||||
impl Spent {
|
||||
/// The shares of `page` spent so far.
|
||||
pub(super) fn on(&self, page: Rect) -> (f64, f64) {
|
||||
self.pages.iter().find(|(p, ..)| *p == page).map_or((0.0, 0.0), |&(_, any, solid)| (any, solid))
|
||||
}
|
||||
|
||||
/// Set the shares of `page` spent so far.
|
||||
fn set(&mut self, page: Rect, any: f64, solid: f64) {
|
||||
match self.pages.iter_mut().find(|(p, ..)| *p == page) {
|
||||
Some(spent) => *spent = (page, any, solid),
|
||||
None => self.pages.push((page, any, solid)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A text object read with a Warp.
|
||||
@@ -738,7 +759,8 @@ pub struct WarpedType {
|
||||
pub(super) envelopes: Vec<TypedEnvelope>,
|
||||
pub(super) checks: usize,
|
||||
pub(super) spent: Spent,
|
||||
pub(super) page: Option<Rect>,
|
||||
/// The pages the art may be compared with, each with its own share of the budget ([`Spent`]).
|
||||
pub(super) pages: Vec<Rect>,
|
||||
/// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too.
|
||||
pub(super) type_clips: HashMap<NodeId, NodeId>,
|
||||
/// The envelopes of type that may open live in layers built without a page, by their place
|
||||
@@ -884,7 +906,7 @@ impl WarpedType {
|
||||
let (id, layer) = (doc.alloc_id(), doc.alloc_id());
|
||||
let mut plain = art.clone();
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
let page = self.page.filter(|_| shown.contains(&drawn));
|
||||
let pages: Vec<Rect> = if shown.contains(&drawn) { self.pages.clone() } else { vec![] };
|
||||
let mut alike = None;
|
||||
// In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again
|
||||
// moved onto that art ([`moved_onto`]), after every other way.
|
||||
@@ -917,7 +939,7 @@ impl WarpedType {
|
||||
let shared = Shared { patterns: &doc.patterns, images: &doc.images };
|
||||
let mut live_one = envelope.clone();
|
||||
(live_one.visible, live_one.opacity) = (true, 1.0);
|
||||
if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) {
|
||||
if drawn_alike(&live_one, &plain, layer, &shared, &pages, &mut self.spent) {
|
||||
alike = Some(envelope);
|
||||
break;
|
||||
}
|
||||
@@ -942,7 +964,8 @@ impl WarpedType {
|
||||
/// budget has no check left for) with that look: `made` gives the text object a slot became. A
|
||||
/// frame in `threaded` stays type, since the frames of a thread share one story. A replaced
|
||||
/// object's box goes back into the comparisons with the page (out of `restyled`), and only what
|
||||
/// `doc` shows counts against the page's share of the budget. Returns how many were replaced.
|
||||
/// `doc` shows counts against the share of the budget of each page it is on. Returns how many
|
||||
/// were replaced.
|
||||
pub(crate) fn settle(
|
||||
self,
|
||||
doc: &mut Document,
|
||||
@@ -950,7 +973,7 @@ impl WarpedType {
|
||||
threaded: &BTreeSet<NodeId>,
|
||||
restyled: &mut Vec<Rect>,
|
||||
) -> usize {
|
||||
let Self { looks, mut checks, mut spent, page, .. } = self;
|
||||
let Self { looks, mut checks, mut spent, pages, .. } = self;
|
||||
let mut shown_ids = BTreeSet::new();
|
||||
doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids));
|
||||
let mut replaced = 0;
|
||||
@@ -965,7 +988,8 @@ impl WarpedType {
|
||||
let (mut shown, mut plain) = (text.clone(), look.clone());
|
||||
(shown.visible, shown.opacity) = (true, 1.0);
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
alike = warped_alike(&shown, &plain, layer, &shared, page.filter(|_| shown_ids.contains(&id)), &mut spent);
|
||||
let on: &[Rect] = if shown_ids.contains(&id) { &pages } else { &[] };
|
||||
alike = warped_alike(&shown, &plain, layer, &shared, on, &mut spent);
|
||||
}
|
||||
if alike {
|
||||
continue;
|
||||
@@ -1032,23 +1056,24 @@ pub(super) fn warps(appearance: &Appearance) -> bool {
|
||||
}
|
||||
|
||||
/// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the
|
||||
/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the
|
||||
/// file has one), they differ little enough that with the differences in `spent` the page check
|
||||
/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a
|
||||
/// layer id no other node has.
|
||||
pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
|
||||
alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent)
|
||||
/// pixels either inks differ and fewer still where a whole patch differs, and, on each of `pages`
|
||||
/// they are on (the pages the art may be compared with), they differ little enough that with the
|
||||
/// differences `spent` holds for that page the page check still takes the layers' art (they are
|
||||
/// added to `spent` when they do on every one). Both are drawn on `layer`, a layer id no other node
|
||||
/// has.
|
||||
pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool {
|
||||
alike_within(live, drawn, live.visual_bounds(), layer, shared, pages, spent)
|
||||
}
|
||||
|
||||
/// [`drawn_alike`] for type under a Warp, compared over all that its effects draw, which can reach
|
||||
/// past its own box.
|
||||
pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
|
||||
pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool {
|
||||
let reach = vectorcraft_render::effect_bounds(&alone(live, layer, shared).symbol_boxes(), live);
|
||||
alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, page, spent)
|
||||
alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, pages, spent)
|
||||
}
|
||||
|
||||
/// [`drawn_alike`], with `live` measured as `reach`.
|
||||
fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
|
||||
fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool {
|
||||
// Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted):
|
||||
// both draw nothing, so they draw alike and add nothing to what the page check sees. Their
|
||||
// shapes aren't compared. Art that paints, however faintly, is compared as before.
|
||||
@@ -1069,21 +1094,31 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, s
|
||||
if share(solid) > MAX_SOLID || share(any) > MAX_ANY {
|
||||
return false;
|
||||
}
|
||||
let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true };
|
||||
// Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the
|
||||
// page's longer side).
|
||||
let on_page = region.intersect(page);
|
||||
let scale = compare_scale(page);
|
||||
if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 {
|
||||
return true;
|
||||
let mut added = vec![];
|
||||
for &page in pages.iter().filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) {
|
||||
// Only what is on the page counts, drawn as the page check draws it (about 400 pixels along
|
||||
// the page's longer side).
|
||||
let on_page = region.intersect(page);
|
||||
let scale = compare_scale(page);
|
||||
if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 {
|
||||
continue;
|
||||
}
|
||||
if spent.compared >= MAX_PAGE_COMPARISONS {
|
||||
return false;
|
||||
}
|
||||
spent.compared += 1;
|
||||
let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false };
|
||||
let pixels = (page.width() * scale * page.height() * scale).max(1.0);
|
||||
let (was_any, was_solid) = spent.on(page);
|
||||
let (any, solid) = (was_any + any as f64 / pixels, was_solid + solid as f64 / pixels);
|
||||
if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 {
|
||||
return false;
|
||||
}
|
||||
added.push((page, any, solid));
|
||||
}
|
||||
let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false };
|
||||
let pixels = (page.width() * scale * page.height() * scale).max(1.0);
|
||||
let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels);
|
||||
if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 {
|
||||
return false;
|
||||
for (page, any, solid) in added {
|
||||
spent.set(page, any, solid);
|
||||
}
|
||||
*spent = Spent { any, solid };
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1161,7 +1196,7 @@ mod tests {
|
||||
#[test]
|
||||
fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() {
|
||||
let shared = Shared { patterns: &[], images: &BTreeMap::new() };
|
||||
let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default());
|
||||
let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, &[], &mut Spent::default());
|
||||
let (none, other_none) = (square_node(1, None), square_node(2, None));
|
||||
assert!(alike(&none, &other_none));
|
||||
let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02)));
|
||||
@@ -1169,6 +1204,22 @@ mod tests {
|
||||
assert!(!alike(&none, &square_node(2, Some(1.0))));
|
||||
}
|
||||
|
||||
/// Each page an object is on takes one of the import's comparisons with pages. With none left,
|
||||
/// art on a page keeps its drawn art, and art on no page needs none.
|
||||
#[test]
|
||||
fn comparisons_with_pages_stop_at_their_limit() {
|
||||
let shared = Shared { patterns: &[], images: &BTreeMap::new() };
|
||||
let (live, drawn) = (square_node(1, Some(1.0)), square_node(2, Some(1.0)));
|
||||
let (page, other) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
let mut spent = Spent { compared: MAX_PAGE_COMPARISONS - 2, ..Default::default() };
|
||||
assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[page, other], &mut spent));
|
||||
assert_eq!(spent.compared, MAX_PAGE_COMPARISONS);
|
||||
assert!(!drawn_alike(&live, &drawn, NodeId(999), &shared, &[page], &mut spent));
|
||||
let off = Rect::new(500.0, 500.0, 600.0, 600.0);
|
||||
assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[off], &mut spent));
|
||||
assert_eq!(spent.compared, MAX_PAGE_COMPARISONS);
|
||||
}
|
||||
|
||||
/// "AVA" at 40 points, at (10, 60).
|
||||
fn type_node(id: u64, style: CharStyle) -> Node {
|
||||
Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style }))))
|
||||
|
||||
@@ -57,8 +57,13 @@
|
||||
//! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and
|
||||
//! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`,
|
||||
//! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before
|
||||
//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document
|
||||
//! that doesn't end leave the placed file unread.
|
||||
//! the path. A placed EPS file whose bytes are included between `%%BeginDocument:` and
|
||||
//! `%%EndDocument` (DSC 3.0 p. 68) is a placed document that keeps those bytes and draws them,
|
||||
//! its file found or not; its box is the
|
||||
//! file's bounding box, which the matrix takes from the file's own space (y up) into art space,
|
||||
//! as in the version 7 form.
|
||||
//! Operands of any other shape, a second `` ` `` before `~` or an included document that
|
||||
//! doesn't end leave the placed file unread.
|
||||
//! - Art with an appearance the format can't write as plain art (several fills or strokes,
|
||||
//! effects, brushes) comes first as that look, drawn (a group, or an image where an effect
|
||||
//! rasterizes it), then the object itself on `%_`
|
||||
@@ -148,22 +153,27 @@ mod raster;
|
||||
mod types;
|
||||
|
||||
pub(crate) use art::join_and;
|
||||
use art::preview_png;
|
||||
use art::{included_document, preview_png};
|
||||
pub use document::{
|
||||
BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette,
|
||||
symbols, variables,
|
||||
};
|
||||
pub(crate) use document::{slot_frame, slot_of};
|
||||
use graph::Graph;
|
||||
#[cfg(test)]
|
||||
pub(crate) use on_path::on_path_measured;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ops::array_slots;
|
||||
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list};
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::with_image_limits;
|
||||
pub(crate) use types::BLEND_BUDGET;
|
||||
pub(crate) use types::LINKED_PREVIEWS;
|
||||
pub(crate) use types::MAX_NODES;
|
||||
pub use types::PlacedPage;
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, MAX_PLACED_DOCUMENT, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
#[cfg(test)]
|
||||
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
|
||||
pub use types::{PlacedEps, PlacedPage};
|
||||
pub(super) use types::{blend_mode, blend_name};
|
||||
|
||||
#[path = "legacy_text.rs"]
|
||||
@@ -212,6 +222,8 @@ pub struct Structure {
|
||||
pub placed_elsewhere: Vec<(NodeId, Affine)>,
|
||||
/// The placed files that are pages of PDF or `.ai` files.
|
||||
pub placed_pages: Vec<PlacedPage>,
|
||||
/// Included EPS files whose previews wait for variable binding before conversion.
|
||||
pub placed_eps: Vec<PlacedEps>,
|
||||
/// The live envelopes read from the editing data, by id, with the drawn art each took the place
|
||||
/// of: the importer puts that art back when the layers with the envelopes don't draw as the page.
|
||||
pub envelopes_drawn: Vec<(NodeId, Node)>,
|
||||
@@ -472,6 +484,10 @@ struct BrushesKept {
|
||||
bending: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
/// What the pages the art may be compared with are worked out from: the move into the document,
|
||||
/// the number of artboards, the first artboard and the art's bounding box.
|
||||
type PageSources = (Option<Affine>, usize, Option<Rect>, Option<Rect>);
|
||||
|
||||
struct Reader<'a> {
|
||||
lex: Lexer<'a>,
|
||||
stack: Vec<V>,
|
||||
@@ -604,6 +620,8 @@ struct Reader<'a> {
|
||||
envelope_checks: usize,
|
||||
/// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]).
|
||||
envelope_spent: super::envelope::Spent,
|
||||
/// [`Self::pages_in_doc`] as last worked out, with what it was worked out from.
|
||||
page_cache: Option<(PageSources, Arc<[Rect]>)>,
|
||||
/// How many more strokes with dashes aligned to corners this import may draw to check
|
||||
/// ([`super::MAX_DASH_CHECKS`]).
|
||||
dash_checks: usize,
|
||||
@@ -667,6 +685,8 @@ struct Reader<'a> {
|
||||
placed_elsewhere: Vec<(NodeId, Affine)>,
|
||||
/// See [`Structure::placed_pages`].
|
||||
placed_pages: Vec<PlacedPage>,
|
||||
/// See [`Structure::placed_eps`].
|
||||
placed_eps: Vec<PlacedEps>,
|
||||
unread_elsewhere: Vec<(NodeId, Rect)>,
|
||||
/// CMYK samples converted, by value.
|
||||
cmyk_cache: HashMap<[u8; 4], [u8; 3]>,
|
||||
@@ -877,6 +897,7 @@ impl<'a> Reader<'a> {
|
||||
envelopes: Vec::new(),
|
||||
envelope_checks: super::envelope::MAX_CHECKED,
|
||||
envelope_spent: super::envelope::Spent::default(),
|
||||
page_cache: None,
|
||||
dash_checks: super::MAX_DASH_CHECKS,
|
||||
defs_only: false,
|
||||
warped_type: Vec::new(),
|
||||
@@ -901,6 +922,7 @@ impl<'a> Reader<'a> {
|
||||
placeholders: vec![],
|
||||
placed_elsewhere: vec![],
|
||||
placed_pages: vec![],
|
||||
placed_eps: vec![],
|
||||
placed_tails: vec![],
|
||||
unread_elsewhere: vec![],
|
||||
mesh: None,
|
||||
@@ -939,6 +961,15 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The line end just before `doc`, an included document the lexer has just read: the one that
|
||||
/// ends its `%%BeginDocument:` line. `None` when `doc` isn't in the data read so far.
|
||||
fn line_end_before(&self, doc: &[u8]) -> Option<&'static [u8]> {
|
||||
let read = self.lex.slice(0, self.lex.offset());
|
||||
let at = doc.as_ptr().addr().checked_sub(read.as_ptr().addr())?;
|
||||
let before = read.get(..at)?;
|
||||
[&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| before.ends_with(e))
|
||||
}
|
||||
|
||||
fn run(&mut self) -> Result<(), String> {
|
||||
while let Some(t) = self.lex.next_token() {
|
||||
if self.done {
|
||||
@@ -961,11 +992,14 @@ impl<'a> Reader<'a> {
|
||||
p.preview = preview_png(d);
|
||||
}
|
||||
}
|
||||
// A placed file's document, included whole: its art isn't read here. When no
|
||||
// `%%EndDocument` ends it, the placed file isn't read.
|
||||
// A placed file's document, included whole: its art isn't read here, its bytes are
|
||||
// kept for the placed file. When no `%%EndDocument` ends it, the placed file isn't
|
||||
// read.
|
||||
Tok::Document(d) => {
|
||||
let sep = d.and_then(|d| self.line_end_before(d));
|
||||
if let Some(p) = self.place.as_mut() {
|
||||
p.broken |= d.is_none();
|
||||
p.document = d.filter(|d| d.len() <= MAX_PLACED_DOCUMENT).map(|d| included_document(d, hidden, sep));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,88 @@ use super::containers::close;
|
||||
use super::document::TEXT_SLOT;
|
||||
use super::raster::{self, Limits, Shape};
|
||||
use super::types::{
|
||||
FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS,
|
||||
MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail,
|
||||
EPS_MIME, FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE,
|
||||
MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedEps, PlacedPage, PlacedTail,
|
||||
};
|
||||
use super::{
|
||||
Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node,
|
||||
NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps,
|
||||
};
|
||||
use vectorcraft_doc::links::missing_placeholder;
|
||||
use vectorcraft_doc::PlacedDocument;
|
||||
use vectorcraft_doc::links::{hash_bytes, missing_placeholder};
|
||||
use vectorcraft_doc::placed_document::key_for;
|
||||
use vectorcraft_pdf::is_postscript;
|
||||
|
||||
/// Open-check results by content and nesting depth: the remaining depth changes their warnings.
|
||||
type EpsChecks = Vec<((String, usize), Option<Vec<String>>)>;
|
||||
|
||||
/// The most open-check results kept during one outer check; no file bytes are retained.
|
||||
const MAX_EPS_CHECKS: usize = 64;
|
||||
|
||||
std::thread_local! {
|
||||
/// How many included EPS files [`readable_eps`] is reading inside one another on this thread.
|
||||
static READING_EPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Checks completed during this thread's outer check, including files that do not read.
|
||||
static EPS_CHECKS: std::cell::RefCell<EpsChecks> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// An included EPS file being read by [`readable_eps`] ([`READING_EPS`]): the count goes down when
|
||||
/// this goes.
|
||||
struct ReadingEps;
|
||||
|
||||
impl ReadingEps {
|
||||
/// `None` when 8 are being read.
|
||||
fn enter() -> Option<Self> {
|
||||
READING_EPS.with(|d| (d.get() < 8).then(|| d.set(d.get() + 1))).map(|()| Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReadingEps {
|
||||
fn drop(&mut self) {
|
||||
READING_EPS.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
if READING_EPS.with(std::cell::Cell::get) == 0 {
|
||||
EPS_CHECKS.with_borrow_mut(Vec::clear);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The warnings of reading `bytes` as an EPS file, the way a placed document's art is read from
|
||||
/// them (art left out after an operator that isn't read, for one); `None` when they don't read.
|
||||
/// Past 8 included files read inside one another they count as readable without warnings; drawing
|
||||
/// reads a bounded number of them in turn. The check uses previews for placed documents, so
|
||||
/// drawing does not start another chain of checks inside this one. Repeated structural reads
|
||||
/// share completed checks at the same depth until the outer check ends.
|
||||
fn readable_eps(bytes: &[u8]) -> Option<Vec<String>> {
|
||||
let key = (hash_bytes(bytes), READING_EPS.with(std::cell::Cell::get));
|
||||
if let Some(warnings) = EPS_CHECKS.with_borrow(|c| c.iter().find(|(k, _)| *k == key).map(|(_, warnings)| warnings.clone())) {
|
||||
return warnings;
|
||||
}
|
||||
let Some(_reading) = ReadingEps::enter() else { return Some(vec![]) };
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
crate::INCLUDED_EPS_READS.with(|n| n.set(n.get() + 1));
|
||||
let warnings = vectorcraft_doc::placed_document::with_previews(|| {
|
||||
crate::import_names(bytes, true, false, crate::NameEncoding::default()).ok().map(|r| r.warnings)
|
||||
});
|
||||
EPS_CHECKS.with_borrow_mut(|c| {
|
||||
if c.len() >= MAX_EPS_CHECKS {
|
||||
c.remove(0);
|
||||
}
|
||||
c.push((key, warnings.clone()));
|
||||
});
|
||||
warnings
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
/// Do the bytes `eps` of an included EPS file read ([`readable_eps`])? When they do, what reading
|
||||
/// them warns of is a warning of this file's too.
|
||||
fn read_included(&mut self, eps: &[u8]) -> bool {
|
||||
let Some(warnings) = readable_eps(eps) else { return false };
|
||||
for w in warnings {
|
||||
self.warn(&format!("a placed EPS file: {w}"));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A text object (`/AI11Text`): an empty group standing for it, named after its story.
|
||||
pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> {
|
||||
if self.pattern.is_some() {
|
||||
@@ -838,8 +909,9 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that
|
||||
/// shows the preview the data keeps of it, as a linked image whose file is missing does. One
|
||||
/// without a preview, a path or a matrix isn't read.
|
||||
/// shows the preview the data keeps of it, as a linked image whose file is missing does. An EPS
|
||||
/// file whose bytes the data includes becomes a placed document of them ([`Self::placed_eps`]).
|
||||
/// One without a preview or those bytes, a path or a matrix isn't read.
|
||||
pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> {
|
||||
// Where a symbol's art puts a placed file's pixels isn't known.
|
||||
if self.symbol.is_some() {
|
||||
@@ -847,11 +919,43 @@ impl<'a> Reader<'a> {
|
||||
self.left_out_of_symbol();
|
||||
return Ok(());
|
||||
}
|
||||
let mut deferred = None;
|
||||
let (m, b, path, png, w, h, folder) = match self.place.take() {
|
||||
Some(Place { broken: true, .. }) => {
|
||||
self.unreadable("placed files", hidden);
|
||||
return Ok(());
|
||||
}
|
||||
Some(Place { matrix: Some(m), bounds: Some(b), path, document: Some(eps), preview, folder, .. })
|
||||
// A file without a bounding box of its own has its art read on a page of another
|
||||
// size, which the placed box can't be matched to.
|
||||
// One named `.ai` or `.ait` is read with the artboard its header gives rather than
|
||||
// its bounding box, so it isn't read either. Bytes that don't read as an EPS file
|
||||
// leave it as a placed file without them: its preview, or an unread one.
|
||||
if !path.is_empty()
|
||||
&& !ai_named(&path)
|
||||
&& is_postscript(&eps)
|
||||
// A native document's artboard, rather than its bounding box, frames what the loader reads.
|
||||
&& !native_eps(&eps)
|
||||
&& crate::dcs::read(&eps).is_none()
|
||||
&& sane(b)
|
||||
&& b.width() > 0.0
|
||||
&& b.height() > 0.0
|
||||
&& eps_box(&eps).is_some()
|
||||
&& self.read_included(&eps) =>
|
||||
{
|
||||
let Some((placed, blob)) = self.placed_eps(m, path.clone(), eps, folder.clone(), hidden) else { return Ok(()) };
|
||||
if let Some((png, w, h)) = preview {
|
||||
// No image variable binds pattern or brush art, which a reader of its own
|
||||
// reads: there the placed document goes in at once.
|
||||
if self.pattern.is_some() {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
deferred = Some((placed, blob));
|
||||
(m, b, path, png, w, h, folder)
|
||||
} else {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
}
|
||||
Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => {
|
||||
(m, b, path, png, w, h, folder)
|
||||
}
|
||||
@@ -902,6 +1006,10 @@ impl<'a> Reader<'a> {
|
||||
.filter(|a| a.as_coeffs().iter().all(|v| v.is_finite()));
|
||||
let xf = self.space() * m * over_file;
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
// An included EPS file is still read when its preview can't be placed.
|
||||
if let Some((placed, blob)) = deferred {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
self.unreadable("placed files", hidden);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -911,7 +1019,11 @@ impl<'a> Reader<'a> {
|
||||
let key = linked_key(&blob, &path);
|
||||
let fresh = !self.doc.images.contains_key(&key);
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
self.warn(LINKED_PREVIEWS);
|
||||
// An included EPS file shows its preview only when an image variable binds it, which the
|
||||
// importer notes then.
|
||||
if deferred.is_none() {
|
||||
self.warn(LINKED_PREVIEWS);
|
||||
}
|
||||
let id = NodeId(self.doc.peek_next_id());
|
||||
if let Some(shift) = elsewhere
|
||||
&& self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE
|
||||
@@ -928,7 +1040,11 @@ impl<'a> Reader<'a> {
|
||||
self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth });
|
||||
let mut link = LinkInfo::new(path);
|
||||
link.relative = folder.and_then(|f| relative_path(&f, link.name()));
|
||||
self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)
|
||||
self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)?;
|
||||
if let Some((placed, blob)) = deferred {
|
||||
self.placed_eps.push(PlacedEps { id, placed, blob });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The dictionary `o` after the placed file just read: with a page or a box in it, that file is
|
||||
@@ -962,6 +1078,54 @@ impl<'a> Reader<'a> {
|
||||
self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size });
|
||||
}
|
||||
|
||||
/// The placed EPS file at `path` whose bytes `eps` the data includes, its box (in its own space,
|
||||
/// y up: the bounding box its comments give, [`eps_box`], which its art is read in) taken into
|
||||
/// art space by `m`: a placed document showing that box, which keeps the bytes and draws them
|
||||
/// whether or not its file is found. Its link has the size and hash of those bytes, so a file
|
||||
/// found unchanged isn't reported as modified. The placed document has no preview, so a save
|
||||
/// keeps the bytes. Not read without that box.
|
||||
fn placed_eps(&mut self, m: Affine, path: String, eps: Vec<u8>, folder: Option<String>, hidden: bool) -> Option<(PlacedDocument, ImageBlob)> {
|
||||
let Some(b) = eps_box(&eps) else {
|
||||
self.unreadable("placed files", hidden);
|
||||
return None;
|
||||
};
|
||||
// The placed document's box runs down from the file's top left corner.
|
||||
let xf = self.space() * m * Affine::new([1.0, 0.0, 0.0, -1.0, b.x0, b.y1]);
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
self.unreadable("placed files", hidden);
|
||||
return None;
|
||||
}
|
||||
let hash = hash_bytes(&eps);
|
||||
let key = key_for(&hash, 1, false, PageBox::Crop);
|
||||
let mut link = LinkInfo::new(path);
|
||||
link.relative = folder.and_then(|f| relative_path(&f, link.name()));
|
||||
(link.page, link.size, link.hash) = (Some(1), u64::try_from(eps.len()).ok(), Some(hash));
|
||||
let blob = ImageBlob { mime: EPS_MIME.into(), bytes: Arc::new(eps), proxy: None, file_font: Default::default() };
|
||||
let placed = PlacedDocument {
|
||||
link,
|
||||
key,
|
||||
bounding: false,
|
||||
page_box: PageBox::Crop,
|
||||
width: b.width(),
|
||||
height: b.height(),
|
||||
xf,
|
||||
placement: Default::default(),
|
||||
};
|
||||
Some((placed, blob))
|
||||
}
|
||||
|
||||
/// `placed` ([`Self::placed_eps`]) added as an object, its bytes `blob` kept under its key.
|
||||
/// Placements of the same bytes share one blob.
|
||||
fn add_placed_eps(&mut self, placed: PlacedDocument, blob: ImageBlob, hidden: bool) -> Result<(), String> {
|
||||
self.doc.images.entry(placed.key.clone()).or_insert(blob);
|
||||
let gs = self.gs.clone();
|
||||
let mut node = self.new_node(NodeKind::PlacedDocument(Box::new(placed)), &gs);
|
||||
node.opacity = gs.opacity;
|
||||
node.blend = gs.blend;
|
||||
node.knockout_shape = gs.knockout_shape;
|
||||
self.add(node, hidden)
|
||||
}
|
||||
|
||||
pub(super) fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) && self.warnings.len() < 64 {
|
||||
self.warnings.push(w.to_string());
|
||||
@@ -1083,6 +1247,65 @@ fn placed_crop(v: f64) -> Option<(bool, PageBox)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of a placed file the data includes (`doc`: between the `%%BeginDocument:` line and
|
||||
/// the `%%EndDocument` one), as the file has them: on `%_` lines (`hidden`) without the `%_` that
|
||||
/// starts each line, then without a line end the data adds before `%%EndDocument` after the file's
|
||||
/// own last one. A single line end at the end is the file's own. The line end added is `sep`, the
|
||||
/// one the data ends its `%%BeginDocument:` line with, when the bytes end with it; otherwise the
|
||||
/// last line end they end with. An LF `sep` after a CR isn't taken apart from it when the file's
|
||||
/// first line ends with CRLF: that CRLF is one line end of the file's.
|
||||
pub(super) fn included_document(doc: &[u8], hidden: bool, sep: Option<&[u8]>) -> Vec<u8> {
|
||||
let mut out = if hidden { unhidden(doc) } else { doc.to_vec() };
|
||||
let eol = |b: &[u8]| b.ends_with(b"\r") || b.ends_with(b"\n");
|
||||
let first_eol = out.iter().position(|&b| b == b'\r' || b == b'\n').and_then(|i| out.get(i..i + 2));
|
||||
let crlf_file = first_eol == Some(b"\r\n") && out.ends_with(b"\r\n");
|
||||
let added = sep
|
||||
.filter(|s| out.ends_with(s) && !(crlf_file && *s == b"\n"))
|
||||
.or_else(|| [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| out.ends_with(e)))
|
||||
.map(|e| out.len() - e.len());
|
||||
if let Some(n) = added.filter(|&n| out.get(..n).is_some_and(eol)) {
|
||||
out.truncate(n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bounding box an EPS file's comments give (`%%HiResBoundingBox` when it has one), in its
|
||||
/// own space; `None` without one, or when it is empty or out of range.
|
||||
fn eps_box(eps: &[u8]) -> Option<Rect> {
|
||||
let [x0, y0, x1, y1] = crate::import::bounding_box(eps)?;
|
||||
Some(Rect::new(x0, y0, x1, y1)).filter(|r| sane(*r) && r.width() > 0.0 && r.height() > 0.0)
|
||||
}
|
||||
|
||||
/// Does `eps` have a native document's begin comment line, without reading that document?
|
||||
fn native_eps(eps: &[u8]) -> bool {
|
||||
eps.split(|b| *b == b'\r' || *b == b'\n')
|
||||
.any(|line| line.strip_prefix(crate::BEGIN_DATA.as_bytes()).is_some_and(|name| name.trim_ascii() == crate::NATIVE.as_bytes()))
|
||||
}
|
||||
|
||||
/// Does the file name at the end of `path` (`/` or `\` separators) end in `.ai` or `.ait`, any case?
|
||||
fn ai_named(path: &str) -> bool {
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("ai") || ext.eq_ignore_ascii_case("ait"))
|
||||
}
|
||||
|
||||
/// `doc` without the `%_` that starts each of its lines.
|
||||
fn unhidden(doc: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(doc.len());
|
||||
let mut line_start = true;
|
||||
let mut i = 0;
|
||||
while let Some(&b) = doc.get(i) {
|
||||
if line_start && doc.get(i..i + 2) == Some(b"%_") {
|
||||
i += 2;
|
||||
line_start = false;
|
||||
continue;
|
||||
}
|
||||
out.push(b);
|
||||
line_start = b == b'\r' || b == b'\n';
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A placed file's path relative to the document's folder (`/` separators): its relative `folder`
|
||||
/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the
|
||||
/// document's own folder). `None` when the folder is absolute or holds control characters, or
|
||||
@@ -1155,3 +1378,36 @@ pub(crate) fn join_and(items: &[&str]) -> String {
|
||||
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ReadingEps, readable_eps};
|
||||
|
||||
/// Check results keep their warnings and failures, respect depth, and expire with the outer check.
|
||||
#[test]
|
||||
fn included_eps_checks_keep_the_depth_limit_and_expire() {
|
||||
let eps = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor 0 0 60 60 rectfill nosuchoperator\n%%EOF\n";
|
||||
{
|
||||
let _outer = ReadingEps::enter().unwrap();
|
||||
let warnings = readable_eps(eps).unwrap();
|
||||
assert!(!warnings.is_empty(), "a partly read file still passes, with warnings");
|
||||
let reads = crate::included_eps_reads();
|
||||
assert_eq!(readable_eps(eps).unwrap(), warnings);
|
||||
assert_eq!(crate::included_eps_reads(), reads, "the repeated check did not parse again");
|
||||
let limits: Vec<_> = std::iter::from_fn(ReadingEps::enter).collect();
|
||||
assert!(!limits.is_empty());
|
||||
assert!(readable_eps(eps).unwrap().is_empty(), "past the depth limit, warnings are not read");
|
||||
drop(limits);
|
||||
assert_eq!(readable_eps(eps).unwrap(), warnings, "the deeper check did not replace the cached warnings");
|
||||
let broken = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
assert!(readable_eps(broken).is_none());
|
||||
let reads = crate::included_eps_reads();
|
||||
assert!(readable_eps(broken).is_none());
|
||||
assert_eq!(crate::included_eps_reads(), reads, "a repeated failed check did not parse again");
|
||||
}
|
||||
let _outer = ReadingEps::enter().unwrap();
|
||||
let reads = crate::included_eps_reads();
|
||||
assert!(readable_eps(eps).is_some());
|
||||
assert!(crate::included_eps_reads() > reads, "the outer check's results were discarded");
|
||||
}
|
||||
}
|
||||
@@ -917,6 +917,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let Some(p) = self.envelopes.pop() else { return };
|
||||
let scale = self.space_scale();
|
||||
let pages = self.pages_in_doc();
|
||||
let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last());
|
||||
let Some(drawn) = drawn else {
|
||||
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
|
||||
@@ -959,8 +960,7 @@ impl<'a> Reader<'a> {
|
||||
(shown.visible, shown.opacity) = (true, 1.0);
|
||||
let mut plain = drawn.clone();
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
let page = self.page_in_doc();
|
||||
let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent);
|
||||
let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent);
|
||||
// In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked
|
||||
// again moved onto that art.
|
||||
if !alike
|
||||
@@ -969,7 +969,7 @@ impl<'a> Reader<'a> {
|
||||
{
|
||||
self.envelope_checks -= 1;
|
||||
(envelope.kind, shown.kind) = (kind.clone(), kind);
|
||||
alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent);
|
||||
alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent);
|
||||
}
|
||||
if !alike {
|
||||
self.warn(crate::import::ai::envelope::DRAWN);
|
||||
|
||||
@@ -55,6 +55,22 @@ impl AiArtboard {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pages the art may be compared with in the document's space, art space being moved there by
|
||||
/// `to_doc` (none before the art starts): each of `artboards` (else `first`, the first artboard),
|
||||
/// then `art_box`, the art's bounding box. A page that is an earlier one to half a point is left out.
|
||||
fn pages_of(to_doc: Option<Affine>, artboards: &[AiArtboard], first: Option<Rect>, art_box: Option<Rect>) -> Vec<Rect> {
|
||||
let Some(to_doc) = to_doc else { return vec![] };
|
||||
let boards: Vec<Rect> = if artboards.is_empty() { first.into_iter().collect() } else { artboards.iter().map(|b| b.rect).collect() };
|
||||
let mut pages: Vec<Rect> = vec![];
|
||||
for page in boards.into_iter().chain(art_box).map(|r| to_doc.transform_rect_bbox(r)) {
|
||||
let same = |p: &Rect| [p.x0 - page.x0, p.y0 - page.y0, p.x1 - page.x1, p.y1 - page.y1].iter().all(|d| d.abs() <= 0.5);
|
||||
if !pages.iter().any(same) {
|
||||
pages.push(page);
|
||||
}
|
||||
}
|
||||
pages
|
||||
}
|
||||
|
||||
/// The number of entry `key` in `o` when it is written as one finite number of the type `ty`
|
||||
/// (`/Int`, `/Real`, `/Bool`; a whole number unless `/Real`), else `None`.
|
||||
fn typed(o: &Obj, key: &str, ty: &str) -> Option<f64> {
|
||||
@@ -923,10 +939,21 @@ impl<'a> Reader<'a> {
|
||||
self.artboards.first().map(|b| b.rect).or(self.cropmarks).or_else(|| self.sized_board())
|
||||
}
|
||||
|
||||
/// The page the art is compared with in the document's space, once the art has started.
|
||||
pub(super) fn page_in_doc(&self) -> Option<Rect> {
|
||||
let board = self.first_board().or_else(|| self.bbox_board())?;
|
||||
Some(self.to_doc?.transform_rect_bbox(board))
|
||||
/// Every page the art may be compared with, in the document's space, once the art has started:
|
||||
/// each artboard (else the first artboard [`Self::first_board`] gives), since a page of a file's
|
||||
/// PDF part can show any of them, and the art's bounding box ([`Self::bbox_board`]), which a page
|
||||
/// cropped to the art and the page of the legacy format show ([`pages_of`]). Worked out again
|
||||
/// only when the artboards, the art's box or the move into the document have changed.
|
||||
pub(super) fn pages_in_doc(&mut self) -> Arc<[Rect]> {
|
||||
let sources = (self.to_doc, self.artboards.len(), self.first_board(), self.bbox_board());
|
||||
if let Some((from, pages)) = &self.page_cache
|
||||
&& *from == sources
|
||||
{
|
||||
return pages.clone();
|
||||
}
|
||||
let pages: Arc<[Rect]> = pages_of(sources.0, &self.artboards, sources.2, sources.3).into();
|
||||
self.page_cache = Some((sources, pages.clone()));
|
||||
pages
|
||||
}
|
||||
|
||||
/// The page of a file that says nothing of its artboard (the legacy format as other apps write
|
||||
@@ -1239,8 +1266,8 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let to_doc = self.ensure_space();
|
||||
let artboard = self.first_board();
|
||||
// Before the artboards are taken below: the page is the first artboard's.
|
||||
let page = self.page_in_doc();
|
||||
// Before the artboards are taken below: the pages are the artboards' and the art's box.
|
||||
let pages = self.pages_in_doc();
|
||||
self.check_symbols();
|
||||
self.order_symbols();
|
||||
drop_commented_copies(&mut self.doc.layers, &self.hidden_ids);
|
||||
@@ -1441,13 +1468,14 @@ impl<'a> Reader<'a> {
|
||||
placeholders: self.placeholders,
|
||||
placed_elsewhere: self.placed_elsewhere,
|
||||
placed_pages: self.placed_pages,
|
||||
placed_eps: self.placed_eps,
|
||||
envelopes_drawn: self.envelopes_drawn,
|
||||
warped_type: super::super::envelope::WarpedType {
|
||||
looks: self.warped_type,
|
||||
envelopes: self.typed_envelopes,
|
||||
checks: self.envelope_checks,
|
||||
spent: self.envelope_spent,
|
||||
page,
|
||||
pages: pages.to_vec(),
|
||||
alone: None,
|
||||
type_clips: self.type_clips,
|
||||
},
|
||||
|
||||
@@ -123,6 +123,18 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many paths and objects the records on this thread have measured.
|
||||
static MEASURED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// [`MEASURED`] of this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn on_path_measured() -> u64 {
|
||||
MEASURED.get()
|
||||
}
|
||||
|
||||
/// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record.
|
||||
pub(super) fn apply(doc: &mut Document, found: &OnPath) {
|
||||
if found.records.is_empty() {
|
||||
@@ -174,11 +186,15 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap<NodeId, Vec<usize>
|
||||
if !tried.insert(g.id) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
MEASURED.set(MEASURED.get() + 1);
|
||||
attachable_path(children.iter().find(|c| c.id == path)?)?;
|
||||
let mut members = Vec::with_capacity(placed.len());
|
||||
for (id, place, angle) in placed {
|
||||
// The frame the object is drawn in: turned by its angle (the document's y points down)
|
||||
// about the center of its bounds.
|
||||
#[cfg(test)]
|
||||
MEASURED.set(MEASURED.get() + 1);
|
||||
let center = doc.node_at(place)?.geometric_bounds()?.center();
|
||||
members.push(Member { id, frame: Affine::rotate_about(angle, center), angle });
|
||||
}
|
||||
|
||||
@@ -9,6 +9,29 @@ use super::{
|
||||
use vectorcraft_doc::{ArrowAlign, Arrowhead};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The operand stack slots that `[` and `]` have looked at on this thread, to find the open
|
||||
/// `[` or to take an array's items: their work.
|
||||
static ARRAY_SLOTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// The point-to-segment distances [`draws_look_outline`] has worked out on this thread.
|
||||
static OUTLINE_PAIRS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// [`ARRAY_SLOTS`] of this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn array_slots() -> u64 {
|
||||
ARRAY_SLOTS.get()
|
||||
}
|
||||
|
||||
/// Count `slots` that `[` or `]` looked at in [`ARRAY_SLOTS`]; nothing outside tests.
|
||||
fn array_slots_looked_at(slots: usize) {
|
||||
#[cfg(test)]
|
||||
ARRAY_SLOTS.set(ARRAY_SLOTS.get().saturating_add(u64::try_from(slots).unwrap_or(u64::MAX)));
|
||||
#[cfg(not(test))]
|
||||
let _ = slots;
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
// ---- operators -------------------------------------------------------------------------
|
||||
|
||||
@@ -16,11 +39,13 @@ impl<'a> Reader<'a> {
|
||||
// The innermost `[` still on the stack (the stack is cut back by operators).
|
||||
let mut at = self.stack.len();
|
||||
while let Some(m) = self.marks.pop() {
|
||||
array_slots_looked_at(1);
|
||||
if matches!(self.stack.get(m), Some(V::Mark)) {
|
||||
at = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
array_slots_looked_at(self.stack.len() - at);
|
||||
let items: Vec<V> = self.stack.split_off(at).into_iter().skip(1).collect();
|
||||
self.push(V::Arr(items))
|
||||
}
|
||||
@@ -172,6 +197,7 @@ impl<'a> Reader<'a> {
|
||||
"[" => {
|
||||
// Drop marks that operators have taken off, so `marks` is the open nesting.
|
||||
while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) {
|
||||
array_slots_looked_at(1);
|
||||
self.marks.pop();
|
||||
}
|
||||
// Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack.
|
||||
@@ -787,7 +813,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let space = self.space();
|
||||
self.note_brushes_kept();
|
||||
let page = self.page_in_doc();
|
||||
let pages = self.pages_in_doc();
|
||||
let Some(f) = self.frames.last_mut() else { return };
|
||||
let n = f.children.len();
|
||||
let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else {
|
||||
@@ -873,7 +899,8 @@ impl<'a> Reader<'a> {
|
||||
let layer = self.doc.alloc_id();
|
||||
let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images };
|
||||
let shown = !hidden && object.visible && look.visible;
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent)
|
||||
let on: &[Rect] = if shown { &pages } else { &[] };
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, on, &mut self.envelope_spent)
|
||||
};
|
||||
alike.then_some(ap)
|
||||
}
|
||||
@@ -885,7 +912,7 @@ impl<'a> Reader<'a> {
|
||||
let layer = self.doc.alloc_id();
|
||||
let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images };
|
||||
let mut spent = crate::import::ai::envelope::Spent::default();
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent)
|
||||
look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, &[], &mut spent)
|
||||
};
|
||||
alike.then_some(ap)
|
||||
}
|
||||
@@ -1314,7 +1341,7 @@ fn look_alike(
|
||||
hidden: bool,
|
||||
layer: NodeId,
|
||||
shared: &crate::import::ai::envelope::Shared<'_>,
|
||||
page: Option<Rect>,
|
||||
pages: &[Rect],
|
||||
spent: &mut crate::import::ai::envelope::Spent,
|
||||
) -> bool {
|
||||
let mut live = object.clone();
|
||||
@@ -1329,7 +1356,7 @@ fn look_alike(
|
||||
for n in [&mut live, &mut plain] {
|
||||
(n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal);
|
||||
}
|
||||
crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent)
|
||||
crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, pages, spent)
|
||||
}
|
||||
|
||||
/// Does `appearance` stroke with dashes aligned to corners and path ends?
|
||||
@@ -1635,7 +1662,13 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo
|
||||
/// projection onto it) is taken from `budget`: `false` once that runs out.
|
||||
fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
|
||||
let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT);
|
||||
let close = |p: kurbo::Point| {
|
||||
b.iter().any(|t| {
|
||||
#[cfg(test)]
|
||||
OUTLINE_PAIRS.set(OUTLINE_PAIRS.get() + 1);
|
||||
t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT
|
||||
})
|
||||
};
|
||||
for s in a {
|
||||
let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil();
|
||||
let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 };
|
||||
@@ -2019,7 +2052,8 @@ mod tests {
|
||||
|
||||
/// The outline check works from one budget for the object: a look of the outline drawn twice
|
||||
/// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn
|
||||
/// look instead of comparing every copy.
|
||||
/// look instead of comparing every copy, having worked out no more distances than the budget
|
||||
/// holds.
|
||||
#[test]
|
||||
fn the_outline_check_has_one_budget_for_the_object() {
|
||||
let zig = vectorcraft_doc::Effect {
|
||||
@@ -2035,10 +2069,17 @@ mod tests {
|
||||
let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect();
|
||||
Node::group(NodeId(2), drawn)
|
||||
};
|
||||
assert!(draws_look_outline(&object, &appearance, &look(2)));
|
||||
let started = std::time::Instant::now();
|
||||
assert!(!draws_look_outline(&object, &appearance, &look(5_000)));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
// Whether the object draws `look`, and how many distances the check worked out.
|
||||
let check = |look: &Node| {
|
||||
let before = OUTLINE_PAIRS.get();
|
||||
let drawn = draws_look_outline(&object, &appearance, look);
|
||||
(drawn, OUTLINE_PAIRS.get() - before)
|
||||
};
|
||||
let (drawn, two) = check(&look(2));
|
||||
assert!(drawn);
|
||||
let (drawn, many) = check(&look(5_000));
|
||||
assert!(many <= u64::try_from(MAX_OUTLINE_PAIRS).unwrap(), "5,000 copies: {many} distances; 2 copies: {two}");
|
||||
assert!(!drawn);
|
||||
}
|
||||
|
||||
/// The outline check reshapes the object as it is drawn, its effects working from its bounds
|
||||
|
||||
@@ -312,6 +312,9 @@ pub(super) struct Place {
|
||||
pub(super) folder: Option<String>,
|
||||
/// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end.
|
||||
pub(super) folder_at: Option<usize>,
|
||||
/// The file's bytes, when the data includes them between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]).
|
||||
pub(super) document: Option<Vec<u8>>,
|
||||
/// Its `` ` `` was read.
|
||||
pub(super) ticked: bool,
|
||||
/// It began on a `%_` line, in a hidden object or on a layer that doesn't show.
|
||||
@@ -361,8 +364,26 @@ pub struct PlacedPage {
|
||||
pub size: (f64, f64),
|
||||
}
|
||||
|
||||
/// An included EPS whose linked preview becomes a placed document after variable binding.
|
||||
#[derive(Debug)]
|
||||
pub struct PlacedEps {
|
||||
/// The linked image.
|
||||
pub id: NodeId,
|
||||
/// The document that replaces the image unless an image variable binds it.
|
||||
pub placed: vectorcraft_doc::PlacedDocument,
|
||||
/// The EPS bytes stored under the placed document's key only when it replaces the image.
|
||||
pub blob: vectorcraft_doc::ImageBlob,
|
||||
}
|
||||
|
||||
/// The largest placed file kept from the bytes the data includes (the largest file File › Place
|
||||
/// reads).
|
||||
pub(super) const MAX_PLACED_DOCUMENT: usize = 256 << 20;
|
||||
|
||||
/// The type a placed EPS file's bytes are stored with.
|
||||
pub(super) const EPS_MIME: &str = "application/postscript";
|
||||
|
||||
/// What the open result says of placed files: they show the preview the file keeps of them.
|
||||
pub(super) const LINKED_PREVIEWS: &str =
|
||||
pub(crate) const LINKED_PREVIEWS: &str =
|
||||
"linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel";
|
||||
|
||||
/// What the open result says of linked images the data keeps no pixels of (`XF`): they show a
|
||||
|
||||
@@ -12,7 +12,9 @@ use super::*;
|
||||
|
||||
/// [`super::read`] as an EPS reads it.
|
||||
fn read(data: &[u8]) -> Result<Structure, String> {
|
||||
super::read(data, true)
|
||||
let mut r = super::read(data, true)?;
|
||||
super::super::native::placed_documents(&mut r.doc, &[], &r.placed_eps);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Editing data: header comments (crop marks 0 0 200 100), then `body`.
|
||||
@@ -3495,6 +3497,178 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() {
|
||||
assert_eq!(relative_of(&cut), None);
|
||||
}
|
||||
|
||||
/// An EPS file of `w` × `h` points filled red, its lines ended by `eol`.
|
||||
fn red_eps(w: u32, h: u32, eol: &str) -> Vec<u8> {
|
||||
format!("%!PS-Adobe-3.0 EPSF-3.0{eol}%%BoundingBox: 0 0 {w} {h}{eol}%%EndComments{eol}1 0 0 setrgbcolor{eol}0 0 {w} {h} rectfill{eol}%%EOF{eol}")
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// `data` with the first `from` in it replaced by `to`.
|
||||
fn splice(data: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
|
||||
let at = data.windows(from.len()).position(|w| w == from).unwrap();
|
||||
[&data[..at], to, &data[at + from.len()..]].concat()
|
||||
}
|
||||
|
||||
/// [`placed`]'s file with the placed file `/old/place/src/shape.eps` in the box 0 0 80 50, in the
|
||||
/// folder `src/`, without a preview, and `doc` included between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` in place of `%%IncludeFile:` (`%%FileType: 0`).
|
||||
fn placed_eps_file(doc: &[u8]) -> Vec<u8> {
|
||||
let data = placed(true, "[5 0 0 -5 0 200]", "/old/place/src/shape.eps", None, "");
|
||||
let data = splice(&data, b"10 20 14 22 4 4 0", b"0 0 80 50 4 4 0");
|
||||
let data = splice(&data, b"\r()\r", b"\r(src/)\r");
|
||||
let data = splice(&data, b"%%FileType: 1", b"%%FileType: 0");
|
||||
let included = [&b"%%BeginDocument: /old/place/src/shape.eps\r"[..], doc, b"\r%%EndDocument\r"].concat();
|
||||
splice(&data, b"%%IncludeFile:/old/place/src/shape.eps\r", &included)
|
||||
}
|
||||
|
||||
/// The one placed document of `data`, with the blob its key names.
|
||||
fn one_placed(data: &[u8]) -> (Node, vectorcraft_doc::PlacedDocument, vectorcraft_doc::ImageBlob, Structure) {
|
||||
let r = read(data).unwrap();
|
||||
let a = art(&r.doc);
|
||||
let [n] = &a[..] else { panic!("one object: {a:?}") };
|
||||
let NodeKind::PlacedDocument(p) = &n.kind else { panic!("a placed document: {:?}", n.kind) };
|
||||
let blob = r.doc.images[&p.key].clone();
|
||||
((**n).clone(), (**p).clone(), blob, r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_whose_bytes_the_data_includes_is_a_placed_document_of_them() {
|
||||
let eps = red_eps(80, 50, "\n");
|
||||
let (_, p, blob, r) = one_placed(&placed_eps_file(&eps));
|
||||
assert_eq!(*blob.bytes, eps, "the file's own bytes, without the line end the data adds");
|
||||
assert_eq!((blob.mime.as_str(), blob.proxy.is_none()), ("application/postscript", true));
|
||||
assert_eq!((p.link.path.as_str(), p.link.relative.as_deref()), ("/old/place/src/shape.eps", Some("src/shape.eps")));
|
||||
assert_eq!((p.link.page, p.link.size, p.link.hash.clone()), (Some(1), Some(eps.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&eps))));
|
||||
assert_eq!((p.width, p.height, p.bounding, p.page_box), (80.0, 50.0, false, vectorcraft_doc::PageBox::Crop));
|
||||
assert!(r.unread.is_empty() && r.hidden_unread.is_empty() && r.unread_elsewhere.is_empty(), "{:?}", r.unread);
|
||||
assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{:?}", r.warnings);
|
||||
// The matrix takes the file's own space (y up) into art space; the box's top left corner is the
|
||||
// file's (0, 50).
|
||||
let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]);
|
||||
for (corner, file) in [((0.0, 0.0), (0.0, 50.0)), ((80.0, 50.0), (80.0, 0.0)), ((80.0, 0.0), (80.0, 50.0))] {
|
||||
let (got, want) = (p.xf * Point::from(corner), r.to_doc * m * Point::from(file));
|
||||
assert!((got - want).hypot() < 1e-9, "{corner:?}: {got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_with_included_bytes_and_a_preview_keeps_only_the_bytes() {
|
||||
let eps = red_eps(80, 50, "\n");
|
||||
let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat();
|
||||
let section =
|
||||
[&b"%AI17_Begin_Content_if_version_gt:24 5\r%AI26_BeginPlacedObjectPreview\r"[..], &preview, b"\r%AI26_EndPlacedObjectPreview\r"].concat();
|
||||
let data = splice(&placed_eps_file(&eps), b"%AI17_Begin_Content_if_version_gt:24 5\r", §ion);
|
||||
// The placed document has no preview, so a save keeps its bytes.
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!((&*blob.bytes, blob.proxy.is_none()), (&eps, true));
|
||||
// The same bytes placed twice share the blob.
|
||||
let one = placed_eps_file(&eps);
|
||||
let (from, to) = (|d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(), b"%AI5_EndPlace\r");
|
||||
let first = &one[from(&one, b"%AI5_BeginPlace")..from(&one, to) + to.len()];
|
||||
let twice = splice(&data, b"%AI5_BeginPlace", &[first, b"%AI5_BeginPlace"].concat());
|
||||
let r = read(&twice).unwrap();
|
||||
let a = art(&r.doc);
|
||||
let keys: Vec<_> = a.iter().filter_map(|n| if let NodeKind::PlacedDocument(p) = &n.kind { Some(p.key.clone()) } else { None }).collect();
|
||||
assert!(keys.len() == 2 && keys[0] == keys[1], "{keys:?}");
|
||||
assert!(r.doc.images[&keys[0]].proxy.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_files_box_is_its_high_resolution_bounding_box() {
|
||||
let eps = splice(&red_eps(80, 50, "\n"), b"%%EndComments", b"%%HiResBoundingBox: 0.5 0.5 79.5 49.5\n%%EndComments");
|
||||
let (_, p, _, r) = one_placed(&placed_eps_file(&eps));
|
||||
assert_eq!((p.width, p.height), (79.0, 49.0));
|
||||
// The box's top left corner is the file's (0.5, 49.5), where the matrix puts it.
|
||||
let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]);
|
||||
let (got, want) = (p.xf * Point::ZERO, r.to_doc * m * Point::new(0.5, 49.5));
|
||||
assert!((got - want).hypot() < 1e-9, "{got:?} {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_files_box_with_its_corners_reversed_leaves_it_unread() {
|
||||
let data = splice(&placed_eps_file(&red_eps(80, 50, "\n")), b"0 0 80 50 4 4 0", b"80 50 0 0 4 4 0");
|
||||
let r = read(&data).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_included_eps_files_own_last_line_end_is_kept() {
|
||||
// The data's line end after the file's own is taken off; a single one is the file's.
|
||||
let (lf, crlf) = ("%!PS\n%%BoundingBox: 0 0 80 50\n%%EOF\n", "%!PS\r\n%%BoundingBox: 0 0 80 50\r\n%%EOF\r\n");
|
||||
for (eps, written) in [(lf, format!("{lf}\r")), (lf, lf.to_string()), (crlf, format!("{crlf}\r\n"))] {
|
||||
let data = splice(&placed_eps_file(b"%!@@"), b"%!@@\r%%EndDocument", format!("{written}%%EndDocument").as_bytes());
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), eps, "{written:?}");
|
||||
}
|
||||
// The line end added is the one the `%%BeginDocument:` line ends with: an LF after a file whose
|
||||
// lines end with CR isn't read as a CRLF of the file's.
|
||||
let data =
|
||||
splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", b"shape.eps\n%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r\n%%EndDocument");
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), "%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r");
|
||||
// A file whose lines end with CRLF, included as it is after an LF: its last CRLF is its own.
|
||||
let data = splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", format!("shape.eps\n{crlf}%%EndDocument").as_bytes());
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), crlf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_on_commented_lines_keeps_its_bytes() {
|
||||
let eps = red_eps(80, 50, "\r");
|
||||
let hidden = hide_placed(&placed_eps_file(&eps));
|
||||
let (_, _, blob, _) = one_placed(&hidden);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the `%_` that starts each line taken off");
|
||||
// The line end added before `%%EndDocument` on a `%_` line of its own.
|
||||
let (_, _, blob, _) = one_placed(&splice(&hidden, b"%%EOF\r\r%_%%EndDocument", b"%%EOF\r%_\r%_%%EndDocument"));
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the added line end taken off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_included_postscript_file_named_as_an_ai_file_stays_unread() {
|
||||
// Read through its name with the artboard its header gives, not the box the placed one shows.
|
||||
for name in ["shape.ai", "SHAPE.AIT"] {
|
||||
let mut data = placed_eps_file(&red_eps(80, 50, "\n"));
|
||||
while data.windows(9).any(|w| w == b"shape.eps") {
|
||||
data = splice(&data, b"shape.eps", name.as_bytes());
|
||||
}
|
||||
let r = read(&data).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{name}: {:?}", art(&r.doc));
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{name}: {:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_eps_with_a_native_document_leaves_the_placed_file_unread() {
|
||||
// Even unreadable native data leaves the file unread: the loader can read an artboard
|
||||
// larger than the EPS bounding box, which would shrink and offset the art when placed.
|
||||
for eol in ["\n", "\r", "\r\n"] {
|
||||
let section = format!("%VectorCraft_BeginData: native \t{eol}%unreadable native data{eol}%VectorCraft_EndData{eol}%%EOF");
|
||||
let eps = splice(&red_eps(80, 50, eol), b"%%EOF", section.as_bytes());
|
||||
let r = read(&placed_eps_file(&eps)).unwrap();
|
||||
assert!(
|
||||
!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))),
|
||||
"included EPS with a native document must stay on the fallback path"
|
||||
);
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_bytes_that_arent_an_eps_file_leave_the_placed_file_unread() {
|
||||
// A DCS file, which the placed document reader doesn't read (File › Place makes it a linked
|
||||
// image), stays unread too.
|
||||
let dcs = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%PlateFile: (Black) EPS Local pic.K\n%%EndComments\n%%EOF\n";
|
||||
// An EPS file without a bounding box, whose art is read on a page of another size, stays unread.
|
||||
let boxless = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n1 0 0 setrgbcolor\n0 0 80 50 rectfill\n%%EOF\n";
|
||||
// An EPS file whose program doesn't read draws nothing, so it stays unread too.
|
||||
let broken = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 80 50\n%%EndComments\n0 0 80 50 nosuchoperator\n%%EOF\n";
|
||||
for bytes in [&b"hello\rworld"[..], dcs, boxless, broken] {
|
||||
let r = read(&placed_eps_file(bytes)).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc));
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_placed_file_ended_by_comment_stays_hidden() {
|
||||
let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, ""));
|
||||
@@ -3588,6 +3762,7 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> {
|
||||
NodeKind::Group { .. } => "group",
|
||||
NodeKind::Path { .. } => "path",
|
||||
NodeKind::Image(_) => "image",
|
||||
NodeKind::PlacedDocument(_) => "placed",
|
||||
_ => "other",
|
||||
})
|
||||
.collect()
|
||||
@@ -3596,13 +3771,16 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> {
|
||||
#[test]
|
||||
fn version7_placed_file_included_whole_is_read() {
|
||||
// The included document's operators, a `~`, a nested document and counted data in it aren't
|
||||
// the editing data's.
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\
|
||||
// the editing data's (the file defines them, so its program reads).
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n/frobnicate {} def /~ {} def\n1 0 0 setrgbcolor frobnicate ~\n\
|
||||
%%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n";
|
||||
let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n");
|
||||
let r = placed_read7(true, &body).unwrap();
|
||||
assert_eq!(art_kinds(&r.doc), ["path"]);
|
||||
assert_unread(&r, "placed files");
|
||||
// A placed document of the file's bytes.
|
||||
assert_eq!(art_kinds(&r.doc), ["placed"]);
|
||||
let NodeKind::PlacedDocument(p) = &art(&r.doc)[0].kind else { panic!() };
|
||||
assert_eq!(r.doc.images[&p.key].bytes.as_slice(), eps.as_bytes());
|
||||
assert!(r.unread.is_empty(), "{:?}", r.unread);
|
||||
// One that doesn't end leaves the layer without its end.
|
||||
let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n");
|
||||
assert!(placed_read7(true, &cut).is_err());
|
||||
@@ -6440,13 +6618,16 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds
|
||||
/// of thousands of them look at no more than four slots each.
|
||||
#[test]
|
||||
fn closing_brackets_without_their_opening_dont_rescan_the_stack() {
|
||||
let n = 200_000;
|
||||
let body = format!("{}\n{}\n", "1 ".repeat(n), "] ".repeat(n));
|
||||
let started = std::time::Instant::now();
|
||||
let before = read::array_slots();
|
||||
let _ = read(stream(&layer(&body)).as_bytes());
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
|
||||
let slots = read::array_slots() - before;
|
||||
assert!(slots <= 4 * u64::try_from(n).unwrap(), "{n} brackets looked at {slots} slots");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9395,24 +9576,35 @@ fn warped_type_gets_what_the_envelopes_left_of_the_budget() {
|
||||
let exact = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat))));
|
||||
let beside = format!("{RED}{}f\n", rect_path(40.5, 20.0, 160.5, 80.0));
|
||||
let shifted = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &beside)));
|
||||
let page = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
for r in [&exact, &shifted] {
|
||||
assert_eq!(r.warped_type.checks, super::envelope::MAX_CHECKED - 1);
|
||||
assert!(r.warped_type.page.is_some());
|
||||
assert_eq!(r.warped_type.pages, [page]);
|
||||
}
|
||||
live_envelope(&art(&shifted.doc)[0]);
|
||||
assert!(shifted.warped_type.spent.any > exact.warped_type.spent.any);
|
||||
assert!(shifted.warped_type.spent.on(page).0 > exact.warped_type.spent.on(page).0);
|
||||
}
|
||||
|
||||
/// In a file with an artboard list, warped type is held to the first artboard, not to the crop marks.
|
||||
/// In a file with an artboard list, warped type is held to every artboard, not to the crop marks.
|
||||
#[test]
|
||||
fn warped_type_is_held_to_the_first_artboard() {
|
||||
fn warped_type_is_held_to_every_artboard() {
|
||||
let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\
|
||||
%_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\
|
||||
%_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_; ,\n\
|
||||
%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n";
|
||||
let r = read_ok(&format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0)))));
|
||||
assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 300.0, 200.0));
|
||||
assert_eq!(r.warped_type.page, Some(Rect::new(0.0, 0.0, 300.0, 200.0)));
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 300.0, 200.0), Rect::new(400.0, 200.0, 600.0, 350.0)]);
|
||||
}
|
||||
|
||||
/// Artboards that are an earlier one to half a point, and an art box that is one of them, add no
|
||||
/// page of their own.
|
||||
#[test]
|
||||
fn pages_that_repeat_an_artboard_are_held_once() {
|
||||
let boards = boards_at(&[[0.0, 0.0, 200.0, 100.0], [0.2, 0.0, 200.0, 100.3], [0.0, 0.0, 200.0, 100.0], [300.0, 0.0, 400.0, 100.0]]);
|
||||
let data = format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0))));
|
||||
let r = read(stream_with_header("%%HiResBoundingBox: 300 0 400 100.4\n", &data).as_bytes()).unwrap();
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 200.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0)]);
|
||||
}
|
||||
|
||||
/// Type whose Warp is hidden draws no warp, so it stays type even with no check left.
|
||||
@@ -9454,17 +9646,39 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() {
|
||||
w.look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10 - i as u64), vec![Arc::new(w.look.clone()), mark.clone()]);
|
||||
}
|
||||
let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None };
|
||||
let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0));
|
||||
let page = Rect::new(0.0, 60.0, 60.0, 100.0);
|
||||
let settle = |w: &super::envelope::WarpedLook, spent| {
|
||||
let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() };
|
||||
let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, pages: vec![page], ..Default::default() };
|
||||
warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![])
|
||||
};
|
||||
let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 };
|
||||
let spent = || super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() };
|
||||
assert_eq!(settle(&looks[1], Default::default()), 0);
|
||||
assert_eq!(settle(&looks[1], spent()), 1);
|
||||
assert_eq!(settle(&looks[0], spent()), 0);
|
||||
}
|
||||
|
||||
/// Each page the art may be compared with has its own share of the budget: warped type on the
|
||||
/// second page spends that page's share, whatever is left of the first page's.
|
||||
#[test]
|
||||
fn warped_type_on_a_later_page_spends_that_pages_share_of_the_budget() {
|
||||
use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE};
|
||||
let (doc, mut looks) = warped_type_doc(2);
|
||||
// The second object shows. Its look draws a little more than it.
|
||||
let mark = read_ok(&layer(&format!("{RED}{}f\n", rect_path(2.0, 2.0, 2.6, 2.6))));
|
||||
let mark = art(&mark.doc)[0].clone();
|
||||
let w = looks.remove(1);
|
||||
let look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10), vec![Arc::new(w.look.clone()), mark]);
|
||||
let (first, second) = (Rect::new(200.0, 0.0, 260.0, 40.0), Rect::new(0.0, 60.0, 60.0, 100.0));
|
||||
let settle = |spent| {
|
||||
let looks = vec![super::envelope::WarpedLook { slot: w.slot, look: look.clone(), left_out: None }];
|
||||
let warped = super::envelope::WarpedType { looks, checks: 1, spent, pages: vec![first, second], ..Default::default() };
|
||||
warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![])
|
||||
};
|
||||
let full = |page| super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() };
|
||||
assert_eq!(settle(full(first)), 0);
|
||||
assert_eq!(settle(full(second)), 1);
|
||||
}
|
||||
|
||||
/// An envelope that comes out close to its drawn art, but with more of the page differing than the
|
||||
/// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100
|
||||
/// page), keeps the drawn art, so the file still opens from its layers.
|
||||
@@ -9479,6 +9693,58 @@ fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() {
|
||||
assert_eq!(r.warnings, [super::envelope::DRAWN]);
|
||||
}
|
||||
|
||||
/// The document data of artboards in art space, each `[x0, y0, x1, y1]`.
|
||||
fn boards_at(boards: &[[f64; 4]]) -> String {
|
||||
let boards: String = boards
|
||||
.iter()
|
||||
.map(|[x0, y0, x1, y1]| {
|
||||
format!("%_/Dictionary :\n%_{x0} {y1} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{x1} {y0} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n")
|
||||
})
|
||||
.collect();
|
||||
format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n")
|
||||
}
|
||||
|
||||
/// The envelope of [`an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it`] on the
|
||||
/// second artboard, the first a strip along the top that it doesn't reach: a page of the second
|
||||
/// artboard can be compared with the layers, so it is held to that page and keeps its drawn art.
|
||||
/// One that draws as its drawn art opens live there.
|
||||
#[test]
|
||||
fn an_envelope_on_a_later_artboard_that_differs_over_its_page_keeps_its_drawn_art() {
|
||||
let boards = boards_at(&[[0.0, 98.0, 20.0, 100.0], [0.0, 0.0, 200.0, 100.0]]);
|
||||
let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0));
|
||||
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted);
|
||||
let r = read_ok(&format!("{boards}{}", layer(&body)));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}");
|
||||
assert_eq!(r.warnings, [super::envelope::DRAWN]);
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]);
|
||||
let flat = vectorcraft_doc::live::EnvelopeKind::Mesh {
|
||||
rows: 1,
|
||||
cols: 1,
|
||||
points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)],
|
||||
handles: vec![],
|
||||
};
|
||||
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat));
|
||||
let r = read_ok(&format!("{boards}{}", layer(&body)));
|
||||
live_envelope(&art(&r.doc)[0]);
|
||||
}
|
||||
|
||||
/// The same envelope on no artboard, inside the art's bounding box: a page cropped to the art
|
||||
/// shows it, so it is held to that page too.
|
||||
#[test]
|
||||
fn an_envelope_off_the_artboards_that_differs_over_the_arts_box_keeps_its_drawn_art() {
|
||||
let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0));
|
||||
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted);
|
||||
let data = format!("{}{}", boards_at(&[[0.0, 98.0, 20.0, 100.0]]), layer(&body));
|
||||
let r = read(stream_with_header("%%HiResBoundingBox: 0 0 200 100\n", &data).as_bytes()).unwrap();
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}");
|
||||
assert_eq!(r.warnings, [super::envelope::DRAWN]);
|
||||
assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]);
|
||||
}
|
||||
|
||||
/// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which
|
||||
/// the page's art replaces.
|
||||
#[test]
|
||||
@@ -10833,9 +11099,9 @@ fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() {
|
||||
}
|
||||
|
||||
/// The path and objects of a group are measured once however many records name it: a thousand
|
||||
/// copies of a record open about as fast as one copy followed by 999 records whose path id is
|
||||
/// missing, when the group opens live, when its long path has no length, and when its first object
|
||||
/// is a group of many paths and its last object has no bounds.
|
||||
/// copies of a record measure as many paths and objects as one copy followed by 999 records whose
|
||||
/// path id is missing, when the group opens live, when its long path has no length, and when its
|
||||
/// first object is a group of many paths and its last object has no bounds.
|
||||
#[test]
|
||||
fn repeated_objects_on_path_records_dont_measure_the_objects_again() {
|
||||
use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record};
|
||||
@@ -10860,23 +11126,18 @@ fn repeated_objects_on_path_records_dont_measure_the_objects_again() {
|
||||
let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000");
|
||||
let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]);
|
||||
let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]);
|
||||
let time = |data: &str| {
|
||||
let started = std::time::Instant::now();
|
||||
let measure = |data: &str| {
|
||||
let before = read::on_path_measured();
|
||||
let doc = read_ok(&format!("{data}{}", layer(&group))).doc;
|
||||
let elapsed = started.elapsed();
|
||||
let measured = read::on_path_measured() - before;
|
||||
let g = art(&doc)[0].clone();
|
||||
assert_eq!(g.children().unwrap().len(), n, "{why}");
|
||||
assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}");
|
||||
elapsed
|
||||
measured
|
||||
};
|
||||
// The fastest of three runs each, taken in turn, so that other tests running at the same
|
||||
// time weigh on both.
|
||||
let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX);
|
||||
for _ in 0..3 {
|
||||
fastest_one = fastest_one.min(time(&one));
|
||||
fastest_many = fastest_many.min(time(&many));
|
||||
}
|
||||
assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}");
|
||||
let (measured_one, measured_many) = (measure(&one), measure(&many));
|
||||
assert!(measured_one > 0, "{why}");
|
||||
assert_eq!(measured_many, measured_one, "{why}: 1000 copies measured {measured_many} times, one copy {measured_one}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,12 @@ struct Gathered {
|
||||
chars: HashMap<char, usize>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread.
|
||||
static COMPARED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl FileFontGlyphs {
|
||||
/// The font of `family` and `style` (made with `info` the first time): its index.
|
||||
pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize {
|
||||
@@ -59,6 +65,10 @@ impl FileFontGlyphs {
|
||||
let mut new: HashMap<char, &FileGlyph> = HashMap::new();
|
||||
for g in glyphs {
|
||||
let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied());
|
||||
#[cfg(test)]
|
||||
if kept.is_some() {
|
||||
COMPARED.set(COMPARED.get() + 1);
|
||||
}
|
||||
match kept {
|
||||
Some(k) if k.outline != g.outline || k.advance != g.advance => return false,
|
||||
Some(_) => {}
|
||||
@@ -178,15 +188,16 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A long string of one character compares each glyph with that character's once, not with
|
||||
/// every one before it: a quarter of a million of them fit at once.
|
||||
/// every one before it: a quarter of a million of them fit at once, with fewer comparisons
|
||||
/// than glyphs.
|
||||
#[test]
|
||||
fn a_long_string_of_one_character_fits_in_linear_time() {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut g = FileFontGlyphs::default();
|
||||
let f = g.font("F", "Regular", FileFontInfo::default);
|
||||
tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok();
|
||||
});
|
||||
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true));
|
||||
let n = 250_000;
|
||||
let mut g = FileFontGlyphs::default();
|
||||
let f = g.font("F", "Regular", FileFontInfo::default);
|
||||
let before = COMPARED.get();
|
||||
assert!(g.fits(f, &vec![glyph('A'); n]));
|
||||
let compared = COMPARED.get() - before;
|
||||
assert!(compared < u64::try_from(n).unwrap(), "{n} glyphs: {compared} comparisons");
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ mod slots;
|
||||
#[cfg(test)]
|
||||
pub(crate) use build::READ_AFRESH;
|
||||
#[cfg(test)]
|
||||
pub(super) use build::placed_documents;
|
||||
#[cfg(test)]
|
||||
use build::{Frame, MADE, prune_unseen};
|
||||
pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -334,6 +334,7 @@ pub(super) fn build_weighing(
|
||||
placeholders,
|
||||
placed_elsewhere,
|
||||
placed_pages,
|
||||
placed_eps,
|
||||
envelopes_drawn,
|
||||
styles_read,
|
||||
text_paints,
|
||||
@@ -644,33 +645,50 @@ pub(super) fn build_weighing(
|
||||
}
|
||||
doc.limit_depth_noting(&mut notes);
|
||||
bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes);
|
||||
placed_documents(&mut doc, &placed_pages);
|
||||
if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) {
|
||||
notes.push(ai::LINKED_PREVIEWS.to_string());
|
||||
}
|
||||
if small.is_some() {
|
||||
scale_read_document(&mut doc, unit, styles_read, symbols_own_size);
|
||||
}
|
||||
Ok((doc, notes))
|
||||
}
|
||||
|
||||
/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed
|
||||
/// documents of their page and box, over the same place, each showing the same preview until its
|
||||
/// file is read. An image bound to an image variable stays a linked image, the object an image
|
||||
/// variable binds.
|
||||
fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) {
|
||||
if pages.is_empty() {
|
||||
return;
|
||||
/// The linked images of `pages` and included `eps` still in `doc`, opacity-mask art included, as placed
|
||||
/// documents of their page and box. PDF pages keep their previews, and EPS files keep their included
|
||||
/// bytes. An image bound to an image variable stays a linked image, the object an image variable binds.
|
||||
/// Returns whether an included EPS file stays a linked image that way, showing its preview.
|
||||
pub(in crate::import) fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage], eps: &[ai::PlacedEps]) -> bool {
|
||||
if pages.is_empty() && eps.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let vars = &doc.variables;
|
||||
let image_bound = |id: &NodeId| {
|
||||
vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image)))
|
||||
};
|
||||
let pages: std::collections::HashMap<NodeId, ai::PlacedPage> = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect();
|
||||
let previews = eps.iter().any(|p| image_bound(&p.id));
|
||||
let eps: std::collections::HashMap<NodeId, &ai::PlacedEps> = eps.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, p)).collect();
|
||||
for layer in &mut doc.layers {
|
||||
to_placed_documents(Arc::make_mut(layer), &pages);
|
||||
to_placed_documents(Arc::make_mut(layer), &pages, &eps, &mut doc.images);
|
||||
}
|
||||
previews
|
||||
}
|
||||
|
||||
/// [`placed_documents`] in `n` and everything in it.
|
||||
fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap<NodeId, ai::PlacedPage>) {
|
||||
fn to_placed_documents(
|
||||
n: &mut Node,
|
||||
pages: &std::collections::HashMap<NodeId, ai::PlacedPage>,
|
||||
eps: &std::collections::HashMap<NodeId, &ai::PlacedEps>,
|
||||
images: &mut std::collections::BTreeMap<String, vectorcraft_doc::ImageBlob>,
|
||||
) {
|
||||
if let Some(eps) = eps.get(&n.id)
|
||||
&& let NodeKind::Image(im) = &n.kind
|
||||
&& im.link.is_some()
|
||||
{
|
||||
images.entry(eps.placed.key.clone()).or_insert_with(|| eps.blob.clone());
|
||||
n.kind = NodeKind::PlacedDocument(Box::new(eps.placed.clone()));
|
||||
}
|
||||
// A box too small to take the image's pixels to (its transform not finite) keeps the linked image.
|
||||
if let Some(page) = pages.get(&n.id)
|
||||
&& let NodeKind::Image(im) = &n.kind
|
||||
@@ -694,10 +712,10 @@ fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap<NodeId, a
|
||||
n.kind = NodeKind::PlacedDocument(Box::new(placed));
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
to_placed_documents(Arc::make_mut(&mut m.art), pages);
|
||||
to_placed_documents(Arc::make_mut(&mut m.art), pages, eps, images);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
to_placed_documents(Arc::make_mut(c), pages);
|
||||
to_placed_documents(Arc::make_mut(c), pages, eps, images);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1905,11 +1923,12 @@ fn outside_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(N
|
||||
}
|
||||
|
||||
/// Where the placed files that show in `nodes` are: the linked images the editing data's reader
|
||||
/// makes of them.
|
||||
/// makes of them, and the placed documents it makes of the EPS files whose bytes it includes.
|
||||
fn placed_files(nodes: &[Arc<Node>], out: &mut Vec<Rect>) {
|
||||
for n in nodes.iter().filter(|n| n.visible) {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()),
|
||||
NodeKind::PlacedDocument(_) => out.extend(n.visual_bounds()),
|
||||
_ => {
|
||||
if let Some(c) = n.children() {
|
||||
placed_files(c, out);
|
||||
|
||||
@@ -56,6 +56,19 @@ fn tree(nodes: &[Arc<Node>]) -> String {
|
||||
nodes.iter().map(one).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Placed EPS files drawn as the app draws them: the art of the file read as it opens, in its
|
||||
/// bounding box (the engine registers the app's own loader).
|
||||
fn draw_placed_eps() {
|
||||
fn load(_: &vectorcraft_doc::PlacedDocument, bytes: &[u8]) -> Option<(vectorcraft_doc::Document, Node, Rect)> {
|
||||
let mut doc = import(bytes).ok()?.document;
|
||||
let frame = doc.artboards.first()?.rect;
|
||||
let layers = std::mem::take(&mut doc.layers);
|
||||
let children = layers.iter().flat_map(|l| l.children().map(|c| c.to_vec()).unwrap_or_default()).collect();
|
||||
Some((doc, Node::new(vectorcraft_doc::NodeId(0), NodeKind::Group { children, clip: false }), frame))
|
||||
}
|
||||
vectorcraft_doc::placed_document::set_loader(load);
|
||||
}
|
||||
|
||||
fn read(header: &str, ugroup: &str, body: &str) -> (String, Vec<String>) {
|
||||
let r = import(&ai(header, ugroup, body)).unwrap();
|
||||
(tree(r.document.layers[0].children().unwrap()), r.warnings)
|
||||
@@ -424,9 +437,10 @@ fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboar
|
||||
}
|
||||
|
||||
/// A placed EPS in the legacy format (version 7 specification §16, no `%AI5_BeginPlace`), its file
|
||||
/// included whole: the layers come in, the placed file as the art the page draws in its box.
|
||||
/// included whole: the layers come in, the placed file as a placed document of its bytes in its box.
|
||||
#[test]
|
||||
fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
|
||||
draw_placed_eps();
|
||||
// `` ` `` takes the file's user space into the page's (`concat`); `~` restores it.
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\
|
||||
/` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
@@ -440,14 +454,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
|
||||
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Back"], "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert_eq!(tree(art), "p g[p]", "{:?}", r.warnings);
|
||||
let NodeKind::PlacedDocument(p) = &art[1].kind else { panic!("{}: {:?}", tree(art), r.warnings) };
|
||||
assert_eq!(r.document.images[&p.key].bytes.as_slice(), eps.as_bytes(), "the file's bytes");
|
||||
assert_eq!(p.link.path, "art.eps");
|
||||
// The file's box, moved by the matrix: 20 40 60 70 on the page, y up.
|
||||
let bounds = art[1].geometric_bounds().unwrap();
|
||||
assert!(
|
||||
(bounds.x0 - 20.0).abs() < 0.01 && (bounds.y0 - 30.0).abs() < 0.01 && (bounds.x1 - 60.0).abs() < 0.01 && (bounds.y1 - 60.0).abs() < 0.01,
|
||||
"{bounds:?}"
|
||||
);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A legacy file whose placed EPS file, included whole, has type: the page's type is the placed
|
||||
/// file's, so the layers come in with it as a placed document.
|
||||
#[test]
|
||||
fn a_legacy_file_with_a_placed_eps_with_type_comes_in_through_its_layers() {
|
||||
draw_placed_eps();
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\
|
||||
/` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\
|
||||
/Helvetica findfont 12 scalefont setfont 15 30 moveto (Hi) show\n%%EOF\n";
|
||||
let placed = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n");
|
||||
let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} {placed}LB\n%AI5_EndLayer--\n", tri(10));
|
||||
let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog"));
|
||||
let r = import(file.as_bytes()).unwrap();
|
||||
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Back"], "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert!(matches!(art[1].kind, NodeKind::PlacedDocument(_)), "{}: {:?}", tree(art), r.warnings);
|
||||
}
|
||||
|
||||
/// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then
|
||||
|
||||
@@ -8358,6 +8358,119 @@ fn a_placed_pdf_page_bound_to_an_image_variable_stays_a_linked_image() {
|
||||
assert_eq!(d.variables.objects_of("v_file"), [n.id], "{notes:?}");
|
||||
}
|
||||
|
||||
/// An included EPS keeps its linked preview and binding when an image variable binds it.
|
||||
#[test]
|
||||
fn a_placed_eps_with_a_preview_preserves_its_image_variable_binding() {
|
||||
use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node};
|
||||
let declared = vec![xml_node(
|
||||
1,
|
||||
"variable",
|
||||
XmlValue::Str(""),
|
||||
&[("trait", XmlValue::Str("fileref")), ("varName", XmlValue::Unicode("v_file")), ("docRef", XmlValue::Raw("/XMLUIDREF : (eps) ;"))],
|
||||
&[],
|
||||
)];
|
||||
let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]);
|
||||
let library = variable_library_data(&xml_element("variableSets", &[], &[set]));
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n";
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\
|
||||
%%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n\
|
||||
%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n\
|
||||
%_/ArtDictionary :\n%_/XMLUID : (eps) ; (AI10_ArtUID) ,\n%_;\n%_\n",
|
||||
"\x7f\0\0\0".repeat(4)
|
||||
);
|
||||
let art = layer("Jig", true, &place);
|
||||
let (bound, notes) = crate::ai_alone(&private(&native(&(library + &art)))).unwrap();
|
||||
let n = &bound.layers[0].children().unwrap()[0];
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) };
|
||||
assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps");
|
||||
assert_eq!((im.width, im.height), (2, 2));
|
||||
assert_eq!(bound.images[&im.key].mime, "image/png");
|
||||
assert!(bound.images.values().all(|b| b.mime != "application/postscript"));
|
||||
assert_eq!(bound.variables.objects_of("v_file"), [n.id], "{notes:?}");
|
||||
assert!(!notes.iter().any(|n| n.contains("variable bindings")), "{notes:?}");
|
||||
assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "the preview it shows is noted: {notes:?}");
|
||||
let (unbound, notes) = crate::ai_alone(&private(&native(&art))).unwrap();
|
||||
assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "it draws its bytes: {notes:?}");
|
||||
let converted = &unbound.layers[0].children().unwrap()[0];
|
||||
assert_eq!(converted.id, n.id);
|
||||
let NodeKind::PlacedDocument(p) = &converted.kind else { panic!("{:?} {notes:?}", converted.kind) };
|
||||
assert_eq!(&*unbound.images[&p.key].bytes, eps.as_bytes());
|
||||
assert!(unbound.images[&p.key].proxy.is_none());
|
||||
}
|
||||
|
||||
/// What reading an included EPS file warns of, such as art left out, is in the open result.
|
||||
#[test]
|
||||
fn a_placed_eps_read_in_part_warns_of_what_it_leaves_out() {
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 30 30 rectfill\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
let own = crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).unwrap().warnings;
|
||||
assert!(!own.is_empty(), "the file read alone warns");
|
||||
for place in [placed_eps_with_preview(eps), placed_eps_with_preview(eps).replace(&placed_eps_preview(), "")] {
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap();
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
assert!(matches!(n.kind, NodeKind::PlacedDocument(_)), "{:?} {notes:?}", n.kind);
|
||||
for w in &own {
|
||||
assert!(notes.contains(&format!("a placed EPS file: {w}")), "{w}: {notes:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An unreadable included EPS keeps the preview that the linked image can show.
|
||||
#[test]
|
||||
fn a_placed_eps_with_an_unreadable_program_keeps_its_preview() {
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
assert!(crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).is_err());
|
||||
let place = placed_eps_with_preview(eps);
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap();
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) };
|
||||
assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps");
|
||||
assert_eq!((im.width, im.height), (2, 2));
|
||||
let preview = &d.images[&im.key];
|
||||
assert_eq!(preview.mime, "image/png");
|
||||
assert_eq!(preview.proxy.as_deref(), Some(&*preview.bytes));
|
||||
assert!(d.images.values().all(|b| b.mime != "application/postscript"));
|
||||
assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}");
|
||||
}
|
||||
|
||||
/// A pattern's included EPS keeps its bytes without waiting for image variable binding.
|
||||
#[test]
|
||||
fn a_placed_eps_with_a_preview_in_a_pattern_keeps_its_bytes() {
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n";
|
||||
let place = placed_eps_with_preview(eps);
|
||||
let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{place}E\n%AI3_EndPattern\n");
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap();
|
||||
let art = &d.pattern("Pic").unwrap().art;
|
||||
assert_eq!(art.len(), 1, "{art:?} {notes:?}");
|
||||
let NodeKind::PlacedDocument(p) = &art[0].kind else { panic!("{art:?} {notes:?}") };
|
||||
assert_eq!(&*d.images[&p.key].bytes, eps.as_bytes());
|
||||
assert_eq!(d.images[&p.key].mime, "application/postscript");
|
||||
assert!(d.images[&p.key].proxy.is_none());
|
||||
assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}");
|
||||
|
||||
// One whose bytes can't be read keeps its preview there too.
|
||||
let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 nosuchoperator\n%%EOF\n";
|
||||
let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{}E\n%AI3_EndPattern\n", placed_eps_with_preview(broken));
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap();
|
||||
let art = &d.pattern("Pic").unwrap().art;
|
||||
assert!(matches!(&art[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.is_some())), "{art:?} {notes:?}");
|
||||
assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}");
|
||||
}
|
||||
|
||||
/// A placed EPS file at `/files/shape.eps` whose bytes `eps` the data includes, with a 2 × 2 preview.
|
||||
fn placed_eps_with_preview(eps: &str) -> String {
|
||||
format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\
|
||||
%%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n{}~\n%AI5_EndPlace\n",
|
||||
placed_eps_preview()
|
||||
)
|
||||
}
|
||||
|
||||
/// The 2 × 2 preview of [`placed_eps_with_preview`].
|
||||
fn placed_eps_preview() -> String {
|
||||
format!("%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n", "\x7f\0\0\0".repeat(4))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_placed_file_goes_where_it_draws_closer_to_the_page() {
|
||||
// A 2 × 2 placed file (a small logo on a large page) whose box corner the matrix takes to
|
||||
|
||||
@@ -61,6 +61,18 @@ pub use print::{PrintFonts, PrintJob, PrintPage, print};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
std::thread_local! {
|
||||
/// Included EPS files parsed by open checks on this thread.
|
||||
pub(crate) static INCLUDED_EPS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Included EPS files parsed by open checks on this thread, for tests that count work instead of timing it.
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
pub fn included_eps_reads() -> usize {
|
||||
INCLUDED_EPS_READS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The PostScript language level the file needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Level {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only.
|
||||
|
||||
use super::{arg, constructor, create_at, data, method, native, new_array};
|
||||
use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes};
|
||||
use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES};
|
||||
use crate::interp::{Hint, Interp, JsResult};
|
||||
use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown};
|
||||
use crate::value::{Str, Value};
|
||||
@@ -90,11 +90,12 @@ fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -
|
||||
fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let key = interp.to_str(&arg(args, 0))?;
|
||||
let units = crate::string_builtins::flat_charged(interp, &key)?;
|
||||
crate::string_builtins::charge_units(interp, units.len())?;
|
||||
if let Some(v) = interp.symbols.registry.get(&*units) {
|
||||
return Ok(v.clone());
|
||||
}
|
||||
let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len()));
|
||||
let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?;
|
||||
crate::string_builtins::charge_units(interp, units.len())?;
|
||||
let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, REGISTRY_ENTRY_BYTES)?;
|
||||
interp.symbols.registry.insert(units, Value::Symbol(sym.clone()));
|
||||
Ok(Value::Symbol(sym))
|
||||
}
|
||||
|
||||
@@ -554,6 +554,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.
|
||||
@@ -1241,7 +1251,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));
|
||||
|
||||
@@ -945,16 +945,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);
|
||||
|
||||
@@ -86,7 +86,8 @@
|
||||
//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a
|
||||
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
|
||||
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
|
||||
//! entry counts against the heap limit.
|
||||
//! entry counts against the heap limit. Registry lookups and insertions take fuel for the key's
|
||||
//! code units, and a registered description shares the key's existing buffer.
|
||||
//!
|
||||
//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section
|
||||
//! 25.6, <https://262.ecma-international.org/11.0/#sec-promise-objects>): the constructor, `then`,
|
||||
@@ -129,6 +130,7 @@ mod number;
|
||||
mod number_builtins;
|
||||
mod parser;
|
||||
mod realm;
|
||||
mod reflect;
|
||||
mod regexp;
|
||||
mod regexp_builtins;
|
||||
mod regexp_vm;
|
||||
@@ -151,12 +153,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};
|
||||
|
||||
@@ -311,6 +314,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");
|
||||
}
|
||||
@@ -57,6 +57,34 @@ fn symbol_for_and_key_for_use_the_registry() {
|
||||
throws("Symbol.for(Symbol())", "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_registry_hashing_charges_flat_keys_on_hits_and_misses() {
|
||||
for hit in [false, true] {
|
||||
let mut realm = es2015(Limits::default());
|
||||
let key = "x".repeat(32_768);
|
||||
assert_eq!(realm.run(&format!("var registryKey = '{key}';")), Ok(JsValue::Undefined));
|
||||
if hit {
|
||||
assert_eq!(realm.run("typeof Symbol.for(registryKey)"), Ok(JsValue::String("symbol".into())));
|
||||
}
|
||||
realm.set_limits(Limits { fuel: 500, ..Limits::default() });
|
||||
assert!(matches!(realm.run("Symbol.for(registryKey)"), Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. })), "hit={hit}");
|
||||
realm.set_limits(Limits { fuel: 10_000, ..Limits::default() });
|
||||
assert_eq!(realm.run("Symbol.for(registryKey) === Symbol.for(registryKey)"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_registry_keeps_a_flat_key_buffer_only_once() {
|
||||
let mut realm = es2015(Limits::default());
|
||||
let key = "x".repeat(32_768);
|
||||
assert_eq!(realm.run(&format!("var sharedKey = '{key}';")), Ok(JsValue::Undefined));
|
||||
let used = realm.collect_garbage();
|
||||
let room = crate::heap::SYMBOL_BYTES + crate::symbol::REGISTRY_ENTRY_BYTES + 4_096;
|
||||
realm.set_limits(Limits { heap_bytes: used + room, ..Limits::default() });
|
||||
assert_eq!(realm.run("var registered = Symbol.for(sharedKey); Symbol.keyFor(registered) === sharedKey"), Ok(JsValue::Bool(true)));
|
||||
assert!(realm.collect_garbage() <= used + room);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_conversion_of_a_symbol_throws_a_type_error() {
|
||||
throws("Symbol() + ''", "TypeError");
|
||||
|
||||
+28
-13
@@ -1037,31 +1037,46 @@ fn promise_builtins_run() {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global
|
||||
/// `print` that collects its output; an `async` test passes when it prints
|
||||
/// `Test262:AsyncTestComplete`.
|
||||
#[test]
|
||||
fn promise_async_completion_requires_an_exact_print_argument() {
|
||||
assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true).is_err());
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true).is_err());
|
||||
assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true).is_ok());
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_async_failure_checks_each_print_argument() {
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true).is_err());
|
||||
assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true).is_ok());
|
||||
}
|
||||
|
||||
/// Runs one Promise test with a global `print` that collects every argument. An `async` test
|
||||
/// needs an exact `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix.
|
||||
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> {
|
||||
let options = Options { es2015: true, ..Options::default() };
|
||||
let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
|
||||
let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let out = printed.clone();
|
||||
realm.define_function("print", move |args| {
|
||||
let line = match args.first() {
|
||||
Some(JsValue::String(s)) => s.clone(),
|
||||
Some(other) => format!("{other:?}"),
|
||||
None => String::new(),
|
||||
};
|
||||
out.borrow_mut().push_str(&line);
|
||||
out.borrow_mut().push('\n');
|
||||
let mut printed = out.borrow_mut();
|
||||
for arg in args {
|
||||
printed.push(match arg {
|
||||
JsValue::String(s) => s.clone(),
|
||||
other => format!("{other:?}"),
|
||||
});
|
||||
}
|
||||
Ok(JsValue::Undefined)
|
||||
});
|
||||
let result = realm.run(script);
|
||||
if asynchronous && result.is_ok() && negative_type.is_none() {
|
||||
let printed = printed.borrow();
|
||||
return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") {
|
||||
return if printed.iter().any(|arg| arg == "Test262:AsyncTestComplete")
|
||||
&& !printed.iter().any(|arg| arg.starts_with("Test262:AsyncTestFailure"))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("printed {:?}", printed.trim()))
|
||||
Err(format!("printed {printed:?}"))
|
||||
};
|
||||
}
|
||||
match (result, negative_type) {
|
||||
|
||||
@@ -1942,6 +1942,32 @@ fn selection_preferences_apply_to_pointer_gestures() {
|
||||
assert_eq!(click(&mut s, 7, 250.0, json!({})), json!([front]), "the path does");
|
||||
}
|
||||
|
||||
/// A Selection tool click inside a closed shape with no fill selects it (#9175), and with Object
|
||||
/// Selection by Path Only on it selects nothing.
|
||||
#[test]
|
||||
fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() {
|
||||
let mut s = server();
|
||||
let r = call(
|
||||
&mut s,
|
||||
1,
|
||||
"draw_shape",
|
||||
json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100, "fill": "none", "stroke": "#000000"}),
|
||||
);
|
||||
let id = serde_json::from_str::<Value>(&text_of(&r)).unwrap()["id"].as_u64().unwrap();
|
||||
let click = |s: &mut Server, n: u64| {
|
||||
let r = call(s, n, "run_command", json!({"command": "select.none", "params": {}}));
|
||||
assert_eq!(r["isError"], false, "{r}");
|
||||
let events = json!([{"kind": "down", "x": 150, "y": 150}, {"kind": "up", "x": 150, "y": 150}]);
|
||||
let r = call(s, n + 1, "pointer_gesture", json!({"tool": "selection", "events": events}));
|
||||
assert_eq!(r["isError"], false, "{r}");
|
||||
serde_json::from_str::<Value>(&text_of(&r)).unwrap()["selection"].clone()
|
||||
};
|
||||
assert_eq!(click(&mut s, 2), json!([id]));
|
||||
let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}}));
|
||||
assert_eq!(r["isError"], false, "{r}");
|
||||
assert_eq!(click(&mut s, 5), json!([]), "path only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_gesture_forwards_backquote_on_each_event() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -1998,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",
|
||||
@@ -2016,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",
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
+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]
|
||||
|
||||
@@ -672,6 +672,9 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO
|
||||
/// linear part. With `brush` true, the members of a group or layer are measured with the room
|
||||
/// their brushed strokes leave for brush art ([`member_cull_bounds`]).
|
||||
fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: bool) -> Option<Rect> {
|
||||
// A layer is measured in the mode its Layer Options draw it in, as the renderer measures the
|
||||
// members of a group or layer without effects ([`crate::Renderer::bounds_of`]).
|
||||
let _mode = crate::placed_document::enter_layer(n);
|
||||
let inner = |c: &Node| cull_bounds_in(symbols, c, after_reshape, false);
|
||||
let member = |c: &Node| member_cull_bounds(symbols, c, after_reshape, brush);
|
||||
// The art that a group's or layer's crop marks or Vector Halftone draw holds its members. The
|
||||
|
||||
@@ -7,22 +7,18 @@ use super::{
|
||||
use crate::kept_paths::{self, KeptPath};
|
||||
use crate::node_checks::{holds_measured_three_d, measures_three_d};
|
||||
use crate::placed_document::{InMode, LayerMode, enter_layer};
|
||||
use vectorcraft_doc::placed_document::crossed;
|
||||
|
||||
/// The key of `a`'s cull bounds in [`Renderer::geom`]: its address, and in its lowest bits what the
|
||||
/// bounds depend on besides `a`. For a layer that is the mode its sublayers are measured in
|
||||
/// ([`LayerMode`], [`enter_layer`]); for an object other than a path, whether placed documents are
|
||||
/// crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the art its effects make from a
|
||||
/// placed document in it is the crossed box then. A node's address is aligned to 8 bytes, so no
|
||||
/// other node has that key.
|
||||
/// bounds depend on besides `a`. For an object other than a path that is the mode it is measured in
|
||||
/// ([`LayerMode`]): it sets the mode of the layers in it ([`enter_layer`]), a group's included, and
|
||||
/// whether placed documents are crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the
|
||||
/// art its effects make from a placed document in it is the crossed box then. Placed documents are
|
||||
/// crossed only in a mode. A node's address is aligned to 8 bytes, so no other node has that key.
|
||||
fn geom_key(a: &Node) -> usize {
|
||||
let at = std::ptr::from_ref(a) as usize;
|
||||
match a.kind {
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => at,
|
||||
NodeKind::Layer { .. } => {
|
||||
at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2)
|
||||
}
|
||||
_ => at | usize::from(crossed()),
|
||||
_ => at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -335,6 +335,57 @@ fn outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview
|
||||
assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a sublayer whose Preview is off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_is_measured_again_when_show_images_in_outline_mode_changes_for_a_sublayer_in_it() {
|
||||
// As above, in a sublayer whose Preview is off, held in a group. With Show Images in Outline
|
||||
// Mode the file that can't be read draws nothing; turned off, the sublayer draws the moved box
|
||||
// crossed, and the same renderer measures the group again.
|
||||
let mut d = doc_with("outline-cull-2", b"bad");
|
||||
let params = serde_json::json!({"moveV": 40});
|
||||
d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let placed = d.remove(NodeId(50)).unwrap();
|
||||
let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1));
|
||||
if let NodeKind::Layer { children, preview, .. } = &mut sub.kind {
|
||||
children.push(placed);
|
||||
*preview = false;
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::group(NodeId(91), vec![Arc::new(sub)])).unwrap();
|
||||
let view = Affine::translate((0.0, -55.0));
|
||||
let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
d.setup.outline_images = true;
|
||||
r.render(&d, 100, 100, view, &preview);
|
||||
d.setup.outline_images = false;
|
||||
let crossed = r.render(&d, 100, 100, view, &preview);
|
||||
assert!(crossed.pixel(30, 5)[0] < 200, "the moved box is drawn crossed");
|
||||
assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, view, &preview).pixels, "as a new renderer draws it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_with_a_drop_shadow_measures_a_sublayer_in_it_in_the_sublayers_own_mode() {
|
||||
// As above, in a sublayer whose Preview is off, held in a group with a Drop Shadow effect: the
|
||||
// sublayer draws the moved box crossed, and the group's cull bounds reach it.
|
||||
let mut d = doc_with("outline-cull-3", b"bad");
|
||||
let params = serde_json::json!({"moveV": 40});
|
||||
d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let placed = d.remove(NodeId(50)).unwrap();
|
||||
let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1));
|
||||
if let NodeKind::Layer { children, preview, .. } = &mut sub.kind {
|
||||
children.push(placed);
|
||||
*preview = false;
|
||||
}
|
||||
let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 0, "opacity": 0});
|
||||
let mut g = Node::group(NodeId(91), vec![Arc::new(sub)]);
|
||||
g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true });
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, g).unwrap();
|
||||
let view = Affine::translate((0.0, -55.0));
|
||||
let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let r = Renderer::new().render(&d, 100, 100, view, &preview);
|
||||
assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a group with a drop shadow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_in_outline_mode_redraws_where_the_effects_move_the_crossed_box() {
|
||||
// A file that can't be read, in the box (10, 10)–(90, 50): a Transform effect added to it moves
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -18,7 +18,12 @@
|
||||
//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at
|
||||
//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the
|
||||
//! segments the circle touches get an anchor point at each touch, which splits them without changing
|
||||
//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none.
|
||||
//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. With the
|
||||
//! `askRadius` option on, a click on the second segment (not a drag, which sets the radius itself)
|
||||
//! opens the [`RADIUS_DIALOG`] instead of drawing: it starts at the radius of the circle found and
|
||||
//! draws the circle of the radius typed ([`radius_circle`]); the first segment stays picked until it
|
||||
//! does. While the dialog is open, an edit to either segment leaves it without a circle
|
||||
//! ([`segments_unchanged`]).
|
||||
//!
|
||||
//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`;
|
||||
//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the
|
||||
@@ -29,11 +34,12 @@
|
||||
//! within the selection tolerance, as a click on a path picks it, and that is also the least reach
|
||||
//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default
|
||||
//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and
|
||||
//! `snapWithoutGuides` is on.
|
||||
//! `snapWithoutGuides` is on. `askRadius` (above) and `autoUpdateDefault`, which makes the radius
|
||||
//! given in the dialog the tool's `radius`, are off by default.
|
||||
|
||||
use kurbo::{CubicBez, ParamCurveNearest, Shape};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_doc::{Document, NodeId};
|
||||
use vectorcraft_geom::{BezPath, ParamCurve, Point};
|
||||
use vectorcraft_pathops::addons::pathtools::{SegmentCircle, circles_of_radius, circles_through};
|
||||
|
||||
@@ -53,6 +59,9 @@ const STEP_PX: f64 = 4.0;
|
||||
const SLOW: f64 = 0.1;
|
||||
/// The note shown over a second segment that gives no circle.
|
||||
pub const NO_CIRCLE: &str = "No tangent circle here";
|
||||
/// The dialog a click on the second segment opens with `askRadius` on: its parameters hold the two
|
||||
/// segments, the click and the circle found ([`radius_circle`]).
|
||||
pub const RADIUS_DIALOG: &str = "tangentCircleRadius";
|
||||
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
|
||||
const RED: [u8; 3] = [0xe0, 0x3c, 0x3c];
|
||||
const GREY: [u8; 3] = [0x80, 0x80, 0x80];
|
||||
@@ -77,7 +86,7 @@ pub const SNAP_PX: f64 = 3.0;
|
||||
/// The snapping tolerance the `snapTolerance` option takes (screen pixels).
|
||||
pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0);
|
||||
/// The option keys that are true or false.
|
||||
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"];
|
||||
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides", "askRadius", "autoUpdateDefault"];
|
||||
|
||||
/// A segment under the pointer: where on it, and the segment itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -124,6 +133,10 @@ pub struct TangentCircleTool {
|
||||
/// The snapping tolerance (screen pixels), and whether the tool snaps with Smart Guides off.
|
||||
snap_px: f64,
|
||||
snap_without_guides: bool,
|
||||
/// Whether a click on the second segment asks for the radius (`askRadius`), and whether the
|
||||
/// radius given there becomes `radius` (`autoUpdateDefault`, which the dialog reads).
|
||||
ask_radius: bool,
|
||||
auto_update: bool,
|
||||
first: Option<Pick>,
|
||||
hover: Option<Pick>,
|
||||
press: Option<Press>,
|
||||
@@ -153,6 +166,8 @@ impl Default for TangentCircleTool {
|
||||
color: 0,
|
||||
snap_px: SNAP_PX,
|
||||
snap_without_guides: true,
|
||||
ask_radius: false,
|
||||
auto_update: false,
|
||||
first: None,
|
||||
hover: None,
|
||||
press: None,
|
||||
@@ -193,10 +208,24 @@ fn pick_at(cx: &ToolContext, p: Point, reach: f64) -> Option<Pick> {
|
||||
Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve })
|
||||
}
|
||||
|
||||
/// A segment's place in the document: its path, subpath and index.
|
||||
type Place = (NodeId, usize, usize);
|
||||
|
||||
impl Pick {
|
||||
fn place(&self) -> Place {
|
||||
(self.id, self.subpath, self.segment)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's segment at `pick` as it is now: none when its path, subpath or segment is gone.
|
||||
fn segment_now(cx: &ToolContext, pick: &Pick) -> Option<CubicBez> {
|
||||
let sp = cx.doc.node(pick.id)?.path_data()?.subpaths.get(pick.subpath)?;
|
||||
(pick.segment < sp.segment_count()).then(|| sp.segment(pick.segment))
|
||||
segment_at(cx.doc, pick.place())
|
||||
}
|
||||
|
||||
/// The segment of `doc` at `place`: none when its path, subpath or segment is gone.
|
||||
fn segment_at(doc: &Document, (id, subpath, segment): Place) -> Option<CubicBez> {
|
||||
let sp = doc.node(id)?.path_data()?.subpaths.get(subpath)?;
|
||||
(segment < sp.segment_count()).then(|| sp.segment(segment))
|
||||
}
|
||||
|
||||
/// Whether the document's segment at `pick` still has the shape it had when it was picked.
|
||||
@@ -207,17 +236,31 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool {
|
||||
/// The segments a circle may touch when `second` is picked: it and the segments on either side of
|
||||
/// it, without `first`. None when `second` is the first segment again.
|
||||
fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
|
||||
second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect()
|
||||
second_set_at(cx.doc, first.place(), second.place())
|
||||
}
|
||||
|
||||
/// [`second_set`] for the segments of `doc` at `first` and `second`.
|
||||
fn second_set_at(doc: &Document, first: Place, second: Place) -> Vec<CubicBez> {
|
||||
second_segments_at(doc, first, second).into_iter().map(|(_, c)| c).collect()
|
||||
}
|
||||
|
||||
/// [`second_set`] with each segment's index on the second pick's subpath.
|
||||
fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> {
|
||||
if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) {
|
||||
second_segments_at(cx.doc, first.place(), second.place())
|
||||
}
|
||||
|
||||
/// [`second_segments`] for the segments of `doc` at `first` and `second`.
|
||||
fn second_segments_at(doc: &Document, first: Place, second: Place) -> Vec<(usize, CubicBez)> {
|
||||
if first == second {
|
||||
return vec![];
|
||||
}
|
||||
let Some(sp) = cx.doc.node(second.id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(second.subpath)) else { return vec![] };
|
||||
let (id, subpath, i) = second;
|
||||
let Some(sp) = doc.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(subpath)) else { return vec![] };
|
||||
// A subpath edited down to no segments (while the radius dialog is open) has nothing to touch.
|
||||
let n = sp.segment_count();
|
||||
let i = second.segment;
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
let mut indices = vec![i];
|
||||
if i > 0 || sp.closed {
|
||||
indices.push((i + n - 1) % n);
|
||||
@@ -227,7 +270,7 @@ fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize,
|
||||
}
|
||||
indices.sort_unstable();
|
||||
indices.dedup();
|
||||
let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k;
|
||||
let is_first = |k: usize| first == (id, subpath, k);
|
||||
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect()
|
||||
}
|
||||
|
||||
@@ -325,6 +368,93 @@ fn segment_path(c: &CubicBez) -> BezPath {
|
||||
bp
|
||||
}
|
||||
|
||||
fn point_json(p: Point) -> Value {
|
||||
json!([p.x, p.y])
|
||||
}
|
||||
|
||||
fn curve_json(c: &CubicBez) -> Value {
|
||||
json!([point_json(c.p0), point_json(c.p1), point_json(c.p2), point_json(c.p3)])
|
||||
}
|
||||
|
||||
/// A finite point written by [`point_json`].
|
||||
fn point_of(v: &Value) -> Option<Point> {
|
||||
let [x, y] = v.as_array()?.as_slice() else { return None };
|
||||
let p = Point::new(x.as_f64()?, y.as_f64()?);
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
}
|
||||
|
||||
/// A segment written by [`curve_json`].
|
||||
fn curve_of(v: &Value) -> Option<CubicBez> {
|
||||
let [a, b, c, d] = v.as_array()?.as_slice() else { return None };
|
||||
Some(CubicBez::new(point_of(a)?, point_of(b)?, point_of(c)?, point_of(d)?))
|
||||
}
|
||||
|
||||
fn place_json((id, subpath, segment): Place) -> Value {
|
||||
json!([id.0, subpath, segment])
|
||||
}
|
||||
|
||||
/// A place written by [`place_json`].
|
||||
fn place_of(v: &Value) -> Option<Place> {
|
||||
let [id, subpath, segment] = v.as_array()?.as_slice() else { return None };
|
||||
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok());
|
||||
Some((NodeId(id.as_u64()?), index(subpath)?, index(segment)?))
|
||||
}
|
||||
|
||||
/// The [`RADIUS_DIALOG`]'s parameters for circle `c`, found by a click at `at` on `first` and on
|
||||
/// `picked`, whose segments a circle may touch are `second`, which `points` (from [`draw`]) draws:
|
||||
/// the segments and their places, the click, the circle's radius and points, and the tolerance
|
||||
/// [`draw`] checked them with.
|
||||
fn dialog_params(first: &Pick, picked: &Pick, second: &[CubicBez], at: Point, c: &SegmentCircle, points: &Value, tol: f64) -> Value {
|
||||
json!({
|
||||
"first": curve_json(&first.curve),
|
||||
"second": second.iter().map(curve_json).collect::<Vec<_>>(),
|
||||
"places": [place_json(first.place()), place_json(picked.place())],
|
||||
"at": point_json(at),
|
||||
"radius": c.circle.radius,
|
||||
"points": points,
|
||||
"tol": tol,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the segments the [`RADIUS_DIALOG`] opened with parameters `p` holds are still those of
|
||||
/// `doc`: false when a path was edited or removed since the click, in another document, or for
|
||||
/// parameters the tool did not write.
|
||||
pub fn segments_unchanged(doc: &Document, p: &Value) -> bool {
|
||||
let check = || -> Option<bool> {
|
||||
let [first, second] = p.get("places")?.as_array()?.as_slice() else { return None };
|
||||
let (first, second) = (place_of(first)?, place_of(second)?);
|
||||
let second_then: Vec<CubicBez> = p.get("second")?.as_array()?.iter().map(curve_of).collect::<Option<_>>()?;
|
||||
Some(segment_at(doc, first)? == curve_of(p.get("first")?)? && second_then == second_set_at(doc, first, second))
|
||||
};
|
||||
check() == Some(true)
|
||||
}
|
||||
|
||||
/// The `shape.circleThroughPoints` parameters that draw the circle of `radius` the [`RADIUS_DIALOG`]
|
||||
/// opened with parameters `p` gives: at the radius the click found, the circle found; at any other,
|
||||
/// the circle of `radius` touching the second segments nearest the click, anywhere along the first
|
||||
/// segment (as with Shift). None for a radius that is not a finite number above 0, when no circle of
|
||||
/// that radius can be drawn there, or for parameters the tool did not write.
|
||||
pub fn radius_circle(p: &Value, radius: f64) -> Option<Value> {
|
||||
if !(radius.is_finite() && radius > 0.0) {
|
||||
return None;
|
||||
}
|
||||
if p.get("radius").and_then(Value::as_f64) == Some(radius) {
|
||||
let points = p.get("points")?;
|
||||
let [a, b, c] = points.as_array()?.as_slice() else { return None };
|
||||
return [a, b, c].into_iter().all(|q| point_of(q).is_some()).then(|| json!({ "points": points }));
|
||||
}
|
||||
let first = curve_of(p.get("first")?)?;
|
||||
// The second segment and at most one on either side of it.
|
||||
let second: Vec<CubicBez> = p.get("second")?.as_array().filter(|s| (1..=3).contains(&s.len()))?.iter().map(curve_of).collect::<Option<_>>()?;
|
||||
let at = point_of(p.get("at")?)?;
|
||||
let tol = p.get("tol").and_then(Value::as_f64).filter(|t| t.is_finite() && *t > 0.0)?;
|
||||
let c = nearest_to(circles_of_radius(first, &second, radius), at, tol)?;
|
||||
match draw(&c, tol)? {
|
||||
Action::Exec(_, params) => Some(params),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl TangentCircleTool {
|
||||
/// How near (document units) the pointer picks a segment: with Smart Guides on, the snapping
|
||||
/// tolerance or Smart Guides' Snapping Tolerance, whichever is larger; with them off, the
|
||||
@@ -490,9 +620,20 @@ impl Tool for TangentCircleTool {
|
||||
// No circle, or one the three points cannot draw: the first segment stays picked,
|
||||
// for another try. It also stays when the command fails: only a drawn circle tells
|
||||
// the tool (`notify`) to forget it.
|
||||
let tol = cx.tol(DRAW_PX);
|
||||
let Some(c) = self.found.take() else { return vec![] };
|
||||
let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] };
|
||||
let Some(params) = circle_params(&c, tol) else { return vec![] };
|
||||
self.looked = false;
|
||||
// Asked for: a click, not a drag (which set the radius), opens the radius dialog,
|
||||
// which draws the circle. Until then the first segment stays picked, so Cancel
|
||||
// leaves it for another try.
|
||||
if self.ask_radius
|
||||
&& press.radius.is_none()
|
||||
&& let Some(first) = &self.first
|
||||
{
|
||||
let params = dialog_params(first, &press.pick, &press.second, press.at, &c, ¶ms["points"], tol);
|
||||
return vec![Action::Dialog(RADIUS_DIALOG.into(), params)];
|
||||
}
|
||||
// Alt at the release turns `addPoints` the other way.
|
||||
let steps = match &self.first {
|
||||
Some(first) if self.add_points != ev.mods.alt => {
|
||||
@@ -628,6 +769,8 @@ impl Tool for TangentCircleTool {
|
||||
"color": COLORS.get(self.color).map_or("red", |(name, _)| *name),
|
||||
"snapTolerance": self.snap_px,
|
||||
"snapWithoutGuides": self.snap_without_guides,
|
||||
"askRadius": self.ask_radius,
|
||||
"autoUpdateDefault": self.auto_update,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -644,6 +787,8 @@ impl Tool for TangentCircleTool {
|
||||
"color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color),
|
||||
"snapTolerance" => self.snap_px = v.as_f64().unwrap_or(self.snap_px),
|
||||
"snapWithoutGuides" => self.snap_without_guides = v.as_bool().unwrap_or(self.snap_without_guides),
|
||||
"askRadius" => self.ask_radius = v.as_bool().unwrap_or(self.ask_radius),
|
||||
"autoUpdateDefault" => self.auto_update = v.as_bool().unwrap_or(self.auto_update),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -721,6 +866,121 @@ mod tests {
|
||||
[(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-4)
|
||||
}
|
||||
|
||||
/// The circle `shape.circleThroughPoints` parameters `p` draw, as [`drawn`] gives it.
|
||||
fn boxed(p: &Value) -> (f64, f64, f64, f64) {
|
||||
drawn(&[Action::Exec("shape.circleThroughPoints".into(), p.clone()), Action::Notify(DRAWN.into())])
|
||||
}
|
||||
|
||||
/// The radius dialog's parameters in `actions`, which hold nothing else.
|
||||
fn asked(actions: &[Action]) -> Value {
|
||||
let [Action::Dialog(kind, p)] = actions else { panic!("{actions:?}") };
|
||||
assert_eq!(kind, RADIUS_DIALOG);
|
||||
p.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag() {
|
||||
let d = doc();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TangentCircleTool::default();
|
||||
assert_eq!((t.options()["askRadius"].clone(), t.options()["autoUpdateDefault"].clone()), (json!(false), json!(false)));
|
||||
for key in ["askRadius", "autoUpdateDefault"] {
|
||||
assert_eq!(t.check_option(key, &json!(true)), Ok(()));
|
||||
for bad in [json!(1), json!("true"), Value::Null] {
|
||||
assert_eq!(t.check_option(key, &bad), Err(format!("`{key}` must be true or false")), "{bad}");
|
||||
t.set_option(key, &bad);
|
||||
assert_eq!(t.options()[key], json!(false), "{bad}");
|
||||
}
|
||||
t.set_option(key, &json!(true));
|
||||
assert_eq!(t.options()[key], json!(true));
|
||||
}
|
||||
// A click on the second line: the dialog, at the click's circle (radius 20), and nothing
|
||||
// drawn yet; the first segment stays picked.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
|
||||
let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
|
||||
assert!((p["radius"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}");
|
||||
assert!(t.first.is_some() && !t.busy());
|
||||
let r = p["radius"].as_f64().unwrap();
|
||||
assert!(close(boxed(&radius_circle(&p, r).unwrap()), (130.0, 100.0, 40.0, 40.0)), "{p}");
|
||||
// Lines 40 pt apart take no other radius; nor is there a circle without a radius above 0.
|
||||
for no in [25.0, 0.0, -20.0, f64::NAN, f64::INFINITY] {
|
||||
assert_eq!(radius_circle(&p, no), None, "{no}");
|
||||
}
|
||||
// Shift on the L's corner: the dialog at the tool's radius, and another radius gives that
|
||||
// radius's fillet.
|
||||
t.key(&cx, ToolKey::Escape, Mods::default());
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0));
|
||||
t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0));
|
||||
let p = asked(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)));
|
||||
assert_eq!(p["radius"], json!(RADIUS));
|
||||
assert!(close(boxed(&radius_circle(&p, RADIUS).unwrap()), (300.0 - 72.0, 300.0, 72.0, 72.0)), "{p}");
|
||||
assert!(close(boxed(&radius_circle(&p, 10.0).unwrap()), (280.0, 300.0, 20.0, 20.0)), "{p}");
|
||||
// Parameters the tool did not write give no circle.
|
||||
assert_eq!(radius_circle(&json!({}), 10.0), None);
|
||||
let second = p["second"].as_array().unwrap()[0].clone();
|
||||
for (key, bad) in [
|
||||
("second", json!([])),
|
||||
("second", json!([second, second, second, second])),
|
||||
("at", json!([1.0])),
|
||||
("tol", json!(0)),
|
||||
("first", json!("x")),
|
||||
("points", json!([[0, 0]])),
|
||||
] {
|
||||
let mut q = p.clone();
|
||||
q[key] = bad;
|
||||
let r = if key == "points" { RADIUS } else { 10.0 };
|
||||
assert_eq!(radius_circle(&q, r), None, "{key}");
|
||||
}
|
||||
// A drag sets the radius itself: drawn at once, with no dialog.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 365.0));
|
||||
let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 365.0));
|
||||
assert!(close(drawn(&released), (300.0 - 30.0, 300.0, 30.0, 30.0)), "{released:?}");
|
||||
assert!(t.first.is_none());
|
||||
// A click that finds no circle opens no dialog.
|
||||
t.set_option("radius", &json!(5));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0));
|
||||
assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 139.0)).is_empty());
|
||||
assert!(t.first.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_radius_dialog_knows_when_its_segments_changed() {
|
||||
let d = doc();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TangentCircleTool::default();
|
||||
t.set_option("askRadius", &json!(true));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
|
||||
let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
|
||||
assert!(segments_unchanged(&d, &p));
|
||||
assert!(segments_unchanged(&doc_at(100.0, 140.0), &p), "the same paths");
|
||||
// Either line moved, or another document: changed.
|
||||
for (a, b) in [(100.0, 150.0), (110.0, 140.0)] {
|
||||
assert!(!segments_unchanged(&doc_at(a, b), &p), "{a} {b}");
|
||||
}
|
||||
assert!(!segments_unchanged(&Document::new(500.0, 500.0), &p));
|
||||
// The second line edited down to a closed subpath without segments: changed.
|
||||
let mut emptied = d.clone();
|
||||
let (second, ..) = place_of(&p["places"][1]).unwrap();
|
||||
emptied.node_mut(second).and_then(|n| n.path_data_mut()).unwrap().subpaths[0] = SubPath::polyline(&[], true);
|
||||
assert!(!segments_unchanged(&emptied, &p));
|
||||
// Parameters the tool did not write.
|
||||
for key in ["places", "first", "second"] {
|
||||
let mut q = p.clone();
|
||||
q[key] = json!("x");
|
||||
assert!(!segments_unchanged(&d, &q), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_clicks_draw_the_circle_tangent_at_the_first_click() {
|
||||
let d = doc();
|
||||
|
||||
@@ -467,16 +467,20 @@ impl ToolContext<'_> {
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::hit_options`] for the selection tools (Selection, Direct Selection, Group
|
||||
/// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]).
|
||||
/// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]), and
|
||||
/// where nothing else is hit, an unfilled closed path is hit inside unless Object Selection by
|
||||
/// Path Only is on ([`HitOptions::unfilled_interiors`]).
|
||||
/// Only for what a press or a hover selects: a double-click, loaded text or a guide's release
|
||||
/// acts on what is drawn and takes [`Self::hit_options`].
|
||||
///
|
||||
/// [`HitOptions::clip_outlines`]: vectorcraft_doc::hit::HitOptions::clip_outlines
|
||||
/// [`HitOptions::unfilled_interiors`]: vectorcraft_doc::hit::HitOptions::unfilled_interiors
|
||||
pub fn selection_hit_options(&self) -> vectorcraft_doc::hit::HitOptions {
|
||||
vectorcraft_doc::hit::HitOptions { clip_outlines: true, ..self.hit_options() }
|
||||
vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..self.hit_options() }
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,35 @@ impl CornerWidgets {
|
||||
out.insert(key.into(), value);
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// The cut corner whose widget is within `tol` (document units) of `p`, as the path draws it in
|
||||
/// the document, with the object it belongs to: what the canvas highlights while the pointer
|
||||
/// is over that widget. `None` away from the widgets and for a corner with no cut.
|
||||
pub fn hovered_cut(&self, doc: &Document, p: Point, tol: f64) -> Option<(NodeId, BezPath)> {
|
||||
let (i, k) = self.hit(p, tol)?;
|
||||
let (id, w) = (self.paths.get(i)?.id, self.widget(i, k)?);
|
||||
let node = doc.node(id)?;
|
||||
let NodeKind::Path { path, .. } = &node.kind else { return None };
|
||||
let lc = LiveCorners::of(node)?;
|
||||
let mut out = BezPath::new();
|
||||
for (sp, from) in path.subpaths.iter().zip(lc.sources()) {
|
||||
// A subpath whose anchors do not match its sources gives no cut rather than a wrong one.
|
||||
if from.len() != sp.anchors.len() {
|
||||
continue;
|
||||
}
|
||||
// A corner's cut is the segment between its two anchors (the last one, for a closed
|
||||
// subpath's first corner); a square corner is one anchor and has none.
|
||||
for s in 0..sp.segment_count() {
|
||||
let (a, b) = (from.get(s), from.get(s + 1).or(from.first()));
|
||||
if a == Some(&w.corner.index) && b == a {
|
||||
let c = sp.segment(s);
|
||||
out.move_to(c.p0);
|
||||
out.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
}
|
||||
}
|
||||
(!out.elements().is_empty()).then_some((id, out))
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle between corner `c`'s sides once `xf` maps them into the document, in degrees.
|
||||
|
||||
@@ -538,3 +538,77 @@ fn a_pen_path_shows_widgets_on_its_corners_only() {
|
||||
assert_eq!(w.corners(), [1, 2]);
|
||||
assert_eq!(pts(&w)[0], Point::new(290.0, 110.0));
|
||||
}
|
||||
|
||||
/// The bounds of the cut `w` gives for the pointer at `at`, rounded to 1e-6.
|
||||
fn hovered_bounds(w: &CornerWidgets, d: &Document, at: Point) -> Option<(NodeId, [f64; 4])> {
|
||||
let (id, cut) = w.hovered_cut(d, at, 5.0)?;
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&cut);
|
||||
Some((id, [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1e6).round() / 1e6)))
|
||||
}
|
||||
|
||||
/// #1232: the pointer within a press's reach of a widget gives the cut of the corner that widget
|
||||
/// controls, for each corner of a rounded rectangle, the first one included; nothing away from
|
||||
/// the widgets.
|
||||
#[test]
|
||||
fn a_widget_under_the_pointer_gives_its_corners_cut() {
|
||||
let (d, id) = live_rect(20.0, Affine::translate((100.0, 100.0)));
|
||||
let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap();
|
||||
assert_eq!(pts(&w), [Point::new(120.0, 120.0), Point::new(180.0, 120.0), Point::new(180.0, 180.0), Point::new(120.0, 180.0)]);
|
||||
let cuts = [[100.0, 100.0, 120.0, 120.0], [180.0, 100.0, 200.0, 120.0], [180.0, 180.0, 200.0, 200.0], [100.0, 180.0, 120.0, 200.0]];
|
||||
for (at, cut) in pts(&w).into_iter().zip(cuts) {
|
||||
assert_eq!(hovered_bounds(&w, &d, at + Vec2::new(3.0, -3.0)), Some((id, cut)), "{at:?}");
|
||||
}
|
||||
assert_eq!(hovered_bounds(&w, &d, Point::new(127.0, 120.0)), None, "past a press's reach");
|
||||
assert_eq!(hovered_bounds(&w, &d, Point::new(150.0, 150.0)), None);
|
||||
}
|
||||
|
||||
/// #1232: a square corner has no cut to give, and a plain path cut in one corner gives that
|
||||
/// corner's cut from its own widget, with the corners Direct Selection shows, for each corner
|
||||
/// kind.
|
||||
#[test]
|
||||
fn a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own() {
|
||||
let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap();
|
||||
assert_eq!(hovered_bounds(&w, &d, Point::new(110.0, 110.0)), None);
|
||||
for kind in [CornerKind::Round, CornerKind::InvertedRound, CornerKind::Chamfer] {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
vectorcraft_doc::corners::set_corners(path, live, &[2].into(), Some(30.0), Some(kind));
|
||||
}
|
||||
let w = CornerWidgets::of(&d, &selected(id), 1.0, true).unwrap();
|
||||
assert_eq!(w.corners(), [0, 1, 2, 3], "{kind:?}");
|
||||
assert_eq!(hovered_bounds(&w, &d, Point::new(110.0, 110.0)), None, "{kind:?}: the square top-left corner");
|
||||
let at = pts(&w)[2];
|
||||
assert_eq!(hovered_bounds(&w, &d, at), Some((id, [170.0, 170.0, 200.0, 200.0])), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1232: a live polygon's widget gives its corner's cut, and a widget hidden by Hide Corner
|
||||
/// Widget for angles greater than gives none at its place.
|
||||
#[test]
|
||||
fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() {
|
||||
let live =
|
||||
LiveShape::Polygon { radius: 80.0, sides: 6, xf: Affine::translate((200.0, 200.0)), radii: vec![], kinds: vec![], radii_relative: false };
|
||||
let (mut d, id) = doc_with(live.to_path(), Some(live));
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
vectorcraft_doc::corners::set_corners(path, live, &[0].into(), Some(10.0), None);
|
||||
}
|
||||
let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap();
|
||||
let at = pts(&w)[0];
|
||||
let (got, b) = hovered_bounds(&w, &d, at).unwrap();
|
||||
assert_eq!(got, id);
|
||||
// The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends.
|
||||
let (wide, high) = (b[2] - b[0], b[3] - b[1]);
|
||||
assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}");
|
||||
let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0);
|
||||
assert!(centre.distance(at) < 15.0, "{b:?} {at:?}");
|
||||
// Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°.
|
||||
let shear = Affine::translate((100.0, 100.0)) * Affine::new([1.0, 0.0, 30f64.to_radians().tan(), 1.0, 0.0, 0.0]);
|
||||
let (d, id) = live_rect(10.0, shear);
|
||||
let all = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap();
|
||||
let shown = all.clone().within_angle(100.0).unwrap();
|
||||
assert_eq!(shown.corners(), [0, 2]);
|
||||
assert!(hovered_bounds(&shown, &d, pts(&all)[0]).is_some());
|
||||
assert!(hovered_bounds(&all, &d, pts(&all)[1]).is_some(), "shown, the 120° corner has a cut");
|
||||
assert_eq!(hovered_bounds(&shown, &d, pts(&all)[1]), None, "hidden, it gives none");
|
||||
}
|
||||
+91
-34
@@ -18,6 +18,10 @@
|
||||
//! the drag makes it select only the objects entirely inside it, whole.
|
||||
//! In isolation mode both pick only the isolated object and what is inside it: anchors, segments,
|
||||
//! paths and groups outside it stay put.
|
||||
//! An object inside a selected group counts as selected whole: a click on its fill keeps the group
|
||||
//! selected, a drag from its fill or one of its anchors moves the group whole, and a click on an
|
||||
//! anchor or a segment selects that anchor or segment alone. With Group Selection a click there
|
||||
//! adds the next group up, if any.
|
||||
//! Both move objects selected as a whole as the Selection tool does, snapping alike. When the
|
||||
//! selection also holds direct-selected anchors or segments, a drag from an object moves those
|
||||
//! anchors and the objects selected whole, as an anchor drag does, and while Alt is held it
|
||||
@@ -53,7 +57,7 @@
|
||||
//! moves its anchors.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view};
|
||||
@@ -559,12 +563,14 @@ fn line_end_leave(cx: &ToolContext, grab: Point) -> Option<Leave> {
|
||||
/// objects behind it (#3405).
|
||||
fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> {
|
||||
let mut owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n) || is_path_type(n));
|
||||
owners.sort_by_key(|id| !cx.selection.contains(*id));
|
||||
// The members of a selected group count as selected.
|
||||
let selected = in_selection_all(cx);
|
||||
owners.sort_by_key(|id| !selected.contains(id));
|
||||
|
||||
// 1. Check selected objects first. Selected objects are NEVER occluded (#1508).
|
||||
let mut unselected_idx = owners.len();
|
||||
for (i, &id) in owners.iter().enumerate() {
|
||||
if !cx.selection.contains(id) {
|
||||
if !selected.contains(&id) {
|
||||
unselected_idx = i;
|
||||
break;
|
||||
}
|
||||
@@ -624,9 +630,22 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool {
|
||||
if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() {
|
||||
return true;
|
||||
}
|
||||
// The editable paths' control bounds are listed once per document state and selection; a
|
||||
// hover measures only the paths whose bounds it is near.
|
||||
let boxes = crate::select::selected_part_boxes(cx, || {
|
||||
selected_part_boxes(cx).iter().any(|&(id, b)| {
|
||||
b.inflate(tol, tol).contains(p)
|
||||
&& cx.doc.node(id).and_then(editable_path).is_some_and(|pd| {
|
||||
#[cfg(test)]
|
||||
MEASURED_PARTS.set(MEASURED_PARTS.get() + 1);
|
||||
nearest_anchor(&pd, p, tol, None).is_some()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The editable paths of the selected objects and inside them (a selected group's members), with
|
||||
/// their control bounds, topmost first across the whole document: the order [`hit_anchor`] tries
|
||||
/// them in. The list is made once per document state and selection; a hover measures only the
|
||||
/// paths whose bounds it is near.
|
||||
fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft_geom::Rect)]> {
|
||||
crate::select::selected_part_boxes(cx, || {
|
||||
let editable = cx.doc.editable();
|
||||
let mut v = vec![];
|
||||
for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) {
|
||||
@@ -638,15 +657,21 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool {
|
||||
}
|
||||
});
|
||||
}
|
||||
// The paint order of every node, a Shaper Group's original shapes included (isolation can
|
||||
// select them); the topmost path comes first.
|
||||
fn walk_all(n: &Node, order: &mut std::collections::HashMap<NodeId, usize>) {
|
||||
let i = order.len();
|
||||
order.insert(n.id, i);
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk_all(c, order);
|
||||
}
|
||||
}
|
||||
let mut order = std::collections::HashMap::new();
|
||||
for l in &cx.doc.layers {
|
||||
walk_all(l, &mut order);
|
||||
}
|
||||
v.sort_by_key(|(id, _)| std::cmp::Reverse(order.get(id).copied()));
|
||||
v.into()
|
||||
});
|
||||
boxes.iter().any(|&(id, b)| {
|
||||
b.inflate(tol, tol).contains(p)
|
||||
&& cx.doc.node(id).and_then(editable_path).is_some_and(|pd| {
|
||||
#[cfg(test)]
|
||||
MEASURED_PARTS.set(MEASURED_PARTS.get() + 1);
|
||||
nearest_anchor(&pd, p, tol, None).is_some()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -823,13 +848,37 @@ struct SegmentHit {
|
||||
fn next_group(cx: &ToolContext, ancestry: &[NodeId]) -> Option<NodeId> {
|
||||
// Skip the layer and its sublayers: they are not objects.
|
||||
let layers = ancestry.iter().take_while(|id| cx.doc.node(**id).is_some_and(Node::is_layer)).count().max(1);
|
||||
ancestry
|
||||
let chain: Vec<NodeId> = ancestry
|
||||
.iter()
|
||||
.skip(layers)
|
||||
.rev()
|
||||
.copied()
|
||||
.take_while(|id| in_scope(cx.doc, cx.isolation, *id) && !cx.doc.node(*id).is_some_and(Node::is_layer))
|
||||
.find(|id| !cx.selection.contains(*id))
|
||||
.collect();
|
||||
// The groups inside a selected group are selected with it: the next one is above the outermost
|
||||
// selected one.
|
||||
let outermost = chain.iter().rposition(|id| cx.selection.contains(*id));
|
||||
chain.get(outermost.map_or(0, |i| i + 1)).copied()
|
||||
}
|
||||
|
||||
/// Is `id` selected as an object: itself, or inside a selected group or other selected object? A
|
||||
/// press on a member of a selected group keeps the group selected, and a drag moves the group
|
||||
/// whole, as for a path that is itself selected.
|
||||
fn in_selection(cx: &ToolContext, id: NodeId) -> bool {
|
||||
!cx.selection.objects.is_empty()
|
||||
&& (cx.selection.contains(id) || cx.doc.ancestry(id).is_some_and(|a| a.iter().any(|x| cx.selection.contains(*x))))
|
||||
}
|
||||
|
||||
/// The selected objects and the objects inside them that Direct Selection may pick: the objects
|
||||
/// among those [`walk_pickable`] visits that [`in_selection`] accepts.
|
||||
fn in_selection_all(cx: &ToolContext) -> HashSet<NodeId> {
|
||||
let mut set = HashSet::new();
|
||||
for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) {
|
||||
walk_pickable_from(root, &mut |n| {
|
||||
set.insert(n.id);
|
||||
});
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// Is an object of instance `id`'s art selected ([`vectorcraft_doc::Selection::symbol_part`]),
|
||||
@@ -1332,7 +1381,7 @@ impl DirectSelectionTool {
|
||||
// anchors on mouse over finds them: walking every path on each hover is too slow.
|
||||
let hit = hit_test(cx.doc, p, cx.selection_hit_options());
|
||||
if let Some((id, _)) = hovered_anchor_with_hit(cx, p, hit.as_ref()) {
|
||||
return Some(if cx.selection.contains(id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor });
|
||||
return Some(if in_selection(cx, id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor });
|
||||
}
|
||||
if hit_frame_edge(cx, p, tol).is_some() {
|
||||
return None;
|
||||
@@ -1344,7 +1393,7 @@ impl DirectSelectionTool {
|
||||
return None;
|
||||
}
|
||||
let h = hit?;
|
||||
let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none();
|
||||
let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none();
|
||||
let curved = matches!(h.kind, HitKind::Stroke | HitKind::Outline) && segment_at(cx, h.leaf, p).is_some_and(|s| s.curved);
|
||||
(!whole && curved).then_some(Cursor::ReshapeSegment)
|
||||
}
|
||||
@@ -1360,7 +1409,11 @@ fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> {
|
||||
fn hovered_anchor_with_hit(cx: &ToolContext, p: Point, hit: Option<&Hit>) -> Option<(NodeId, Point)> {
|
||||
let tol = cx.point_tol();
|
||||
let under = hit.map(|h| cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf));
|
||||
cx.selection.objects.iter().copied().filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| {
|
||||
// The paths inside a selected group come before an object above them, as a press takes them
|
||||
// ([`hit_anchor`]).
|
||||
let selected = if cx.selection.objects.is_empty() { None } else { Some(selected_part_boxes(cx)) };
|
||||
let near = selected.iter().flat_map(|boxes| boxes.iter()).filter(|(_, b)| b.inflate(tol, tol).contains(p)).map(|&(id, _)| id);
|
||||
near.filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| {
|
||||
let path = cx.doc.node(id).and_then(editable_path)?;
|
||||
nearest_anchor(&path, p, tol, None).map(|(.., a)| (id, a))
|
||||
})
|
||||
@@ -1481,7 +1534,9 @@ impl DirectSelectionTool {
|
||||
h.ancestry.push(part);
|
||||
h.leaf = part;
|
||||
}
|
||||
let target = if cx.selection.contains(h.leaf) { next_group(cx, &h.ancestry).unwrap_or(h.leaf) } else { h.leaf };
|
||||
// On an object selected itself or inside a selected group, a click adds the next group up,
|
||||
// and keeps the selection when the outermost group is selected already.
|
||||
let inside = in_selection(cx, h.leaf);
|
||||
let mut deselect = None;
|
||||
let mut out = vec![];
|
||||
if ev.mods.shift {
|
||||
@@ -1490,15 +1545,13 @@ impl DirectSelectionTool {
|
||||
if cx.selection.contains(h.leaf) {
|
||||
deselect = Some(h.leaf);
|
||||
} else {
|
||||
out.push(Action::Exec("select.toggle".into(), json!({"id": target.0})));
|
||||
}
|
||||
} else if !cx.selection.contains(target) {
|
||||
if cx.selection.contains(h.leaf) {
|
||||
// A completed click climbs the group; a drag moves only the selected art.
|
||||
self.click_group = Some(target);
|
||||
} else {
|
||||
out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]})));
|
||||
out.push(Action::Exec("select.toggle".into(), json!({"id": h.leaf.0})));
|
||||
}
|
||||
} else if !inside {
|
||||
out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]})));
|
||||
} else if let Some(target) = next_group(cx, &h.ancestry) {
|
||||
// A completed click climbs the group; a drag moves only the selected art.
|
||||
self.click_group = Some(target);
|
||||
}
|
||||
self.state = Self::move_object(cx, &h, p, deselect);
|
||||
out
|
||||
@@ -1539,15 +1592,16 @@ impl DirectSelectionTool {
|
||||
// already selected whole, an Alt-click adds the next enclosing group on release.
|
||||
if ev.mods.alt {
|
||||
self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, edge: false, began: false, deselect: None };
|
||||
let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none();
|
||||
let whole = in_selection(cx, id) && cx.selection.partial(id).is_none();
|
||||
if whole && !ev.mods.shift {
|
||||
self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a));
|
||||
}
|
||||
return if whole { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] };
|
||||
}
|
||||
// A path with all its anchors selected is stored whole (no partial entry).
|
||||
// A path with all its anchors selected is stored whole (no partial entry), and so is each
|
||||
// path inside a selected group.
|
||||
let already =
|
||||
cx.selection.contains(id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai)));
|
||||
in_selection(cx, id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai)));
|
||||
// Paths all selected whole move as objects, held by this anchor, so Alt can turn
|
||||
// the copy on and off during the drag as with the Selection tool.
|
||||
self.state = if already && cx.selection.anchors.is_empty() {
|
||||
@@ -1625,7 +1679,7 @@ impl DirectSelectionTool {
|
||||
// A segment pick keeps its endpoints available for movement without selecting
|
||||
// the anchors themselves. Dragging reshapes a curve, else moves it. Alt picks
|
||||
// the whole path (and Alt-drag copies it), as with Group Selection.
|
||||
let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf);
|
||||
let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf);
|
||||
if !ev.mods.alt
|
||||
&& matches!(h.kind, HitKind::Stroke | HitKind::Outline)
|
||||
&& let Some(s) = segment_at(cx, h.leaf, p)
|
||||
@@ -1661,7 +1715,8 @@ impl DirectSelectionTool {
|
||||
return vec![Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))];
|
||||
}
|
||||
self.frame.clear();
|
||||
if !cx.selection.contains(h.leaf) || cx.selection.partial(h.leaf).is_some() || part_picked(cx, h.leaf) {
|
||||
// A press inside a selected group keeps the group: a drag moves it whole.
|
||||
if !whole {
|
||||
return vec![Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))];
|
||||
}
|
||||
vec![]
|
||||
@@ -1869,7 +1924,9 @@ impl DirectSelectionTool {
|
||||
(true, ..) => vec![Action::Commit],
|
||||
(false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))],
|
||||
(false, None, Some((id, si, ai)), _) => {
|
||||
if has_multiple_selected_anchors(cx) {
|
||||
// The key anchor is on a path selected itself (`select.key`); a click on an anchor of
|
||||
// a path inside a selected group selects that anchor alone.
|
||||
if cx.selection.contains(id) && has_multiple_selected_anchors(cx) {
|
||||
if cx.selection.key_anchor == Some((id, (si, ai))) {
|
||||
vec![Action::Exec("select.key".into(), json!({}))]
|
||||
} else {
|
||||
|
||||
@@ -1306,6 +1306,83 @@ fn group_selection_distinguishes_selected_leaf_drags_from_clicks() {
|
||||
assert!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty());
|
||||
}
|
||||
|
||||
/// A path inside a selected group counts as selected whole. With Direct Selection a click on its
|
||||
/// fill keeps the group, a drag from its fill or an anchor moves the group whole, and a click on an
|
||||
/// anchor selects that anchor alone; its anchors show the selected-anchor cursor and an object
|
||||
/// above the group does not take a press on one. With Group Selection a click adds the next group
|
||||
/// up and keeps the selection at the outermost one, and a drag moves the selection.
|
||||
#[test]
|
||||
fn a_press_inside_a_selected_group_keeps_the_group() {
|
||||
let (mut d, inside, _, inner, outer) = nested_group_doc();
|
||||
let p = paint();
|
||||
let mut s = Selection::default();
|
||||
s.set([outer]);
|
||||
let moves = |a: &[Action]| matches!(a, [Action::Begin(n), Action::Preview(c, _)] if n == "Move" && c == "object.transform");
|
||||
for group in [false, true] {
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = DirectSelectionTool::new(group);
|
||||
let down = PointerEvent::new(PointerKind::Down, 150.0, 150.0);
|
||||
assert!(t.pointer(&c, &down).is_empty(), "a press on the fill (group: {group})");
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty(), "a click on the fill (group: {group})");
|
||||
assert!(t.pointer(&c, &down).is_empty());
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 180.0, 165.0));
|
||||
assert!(moves(&a), "a drag from the fill (group: {group}): {a:?}");
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 180.0, 165.0)), vec![Action::Commit]);
|
||||
}
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
let corner = PointerEvent::new(PointerKind::Down, 100.0, 100.0);
|
||||
assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor");
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0));
|
||||
assert!(moves(&a), "a drag from an anchor: {a:?}");
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 115.0));
|
||||
t.pointer(&c, &corner);
|
||||
assert_eq!(
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)),
|
||||
vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))],
|
||||
"a click on an anchor"
|
||||
);
|
||||
assert_eq!(DirectSelectionTool::new(false).cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected);
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty(), "a press on a segment");
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0));
|
||||
assert!(matches!(a.as_slice(), [Action::Exec(c, v)] if c == "select.segments" && v["id"] == inside.0), "a click on a segment: {a:?}");
|
||||
// Group Selection climbs from a selected inner group to the group around it.
|
||||
let mut climb = Selection::default();
|
||||
climb.set([inner]);
|
||||
let c = cx(&d, &climb, &p);
|
||||
let mut t = DirectSelectionTool::new(true);
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty());
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)), vec![Action::Exec("select.add".into(), json!({"ids": [outer.0]}))]);
|
||||
// With two anchors of a path beside the group selected too, the click still selects the anchor
|
||||
// alone: the key anchor is on a path selected itself.
|
||||
let l = d.layers[0].id;
|
||||
let beside = d.alloc_id();
|
||||
let rect = vectorcraft_geom::shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0));
|
||||
d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(beside, rect, vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let mut mixed = Selection::default();
|
||||
mixed.set([outer, beside]);
|
||||
mixed.anchors.insert(beside, BTreeSet::from([(0, 0), (0, 1)]));
|
||||
let c = cx(&d, &mixed, &p);
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
assert!(t.pointer(&c, &corner).is_empty());
|
||||
assert_eq!(
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)),
|
||||
vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))],
|
||||
"a click on an anchor with anchors of {beside:?} selected"
|
||||
);
|
||||
// An opaque object above the group, over the anchor.
|
||||
let cover = d.alloc_id();
|
||||
let rect = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0));
|
||||
d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(cover, rect, vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
assert_eq!(hovered_anchor(&c, Point::new(100.0, 100.0)), Some((inside, Point::new(100.0, 100.0))), "the anchor under {cover:?} is highlighted");
|
||||
assert_eq!(t.cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected);
|
||||
assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor under {cover:?}");
|
||||
assert!(moves(&t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0))));
|
||||
}
|
||||
|
||||
/// Isolation mode: a marquee and an anchor click take the path inside the isolated group and
|
||||
/// leave the path beside it. Group Selection stops at the isolated group instead of adding
|
||||
/// the group around it.
|
||||
@@ -1735,13 +1812,18 @@ fn the_centre_point_selects_and_moves_the_object_whole() {
|
||||
let moved = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(Vec2::new(20.0, -10.0))), "copy": false});
|
||||
assert_eq!(a, vec![Action::Begin("Move".into()), Action::Preview("object.transform".into(), moved)]);
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 140.0)), vec![Action::Commit]);
|
||||
// Unselected, the centre isn't shown and a press there starts a marquee.
|
||||
// Unselected, the centre isn't shown and a press there starts a marquee (with Object Selection
|
||||
// by Path Only, where the inside of the unfilled square takes no press).
|
||||
let none = Selection::default();
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
let c = cx(&d, &none, &p);
|
||||
let c = ToolContext { path_only: true, ..cx(&d, &none, &p) };
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty());
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0));
|
||||
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_))));
|
||||
// Without it, a press inside the unfilled square selects it (#9175).
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
let c = cx(&d, &none, &p);
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]);
|
||||
}
|
||||
|
||||
/// Group Selection: E pressed during a marquee drag makes it select the objects entirely inside
|
||||
@@ -2997,3 +3079,31 @@ fn select_behind_is_measured_once_for_a_point() {
|
||||
assert!(crate::select::selects_behind_at(&c, at));
|
||||
assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only");
|
||||
}
|
||||
|
||||
/// With two selected groups whose anchors sit on the same point, the highlighted anchor is the one
|
||||
/// a press takes: the front group's, whatever order the groups were selected in.
|
||||
#[test]
|
||||
fn the_highlighted_anchor_of_two_selected_groups_is_the_one_a_press_takes() {
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let (back_path, back, front_path, front) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let path = |id, x| {
|
||||
std::sync::Arc::new(vectorcraft_doc::Node::path(
|
||||
id,
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(x, x, x + 100.0, x + 100.0)),
|
||||
vectorcraft_doc::Appearance::default_art(),
|
||||
))
|
||||
};
|
||||
d.insert(Some(l), 0, vectorcraft_doc::Node::group(back, vec![path(back_path, 100.0)])).unwrap();
|
||||
d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::group(front, vec![path(front_path, 100.0)])).unwrap();
|
||||
let p = paint();
|
||||
let corner = Point::new(100.0, 100.0);
|
||||
for order in [[back, front], [front, back]] {
|
||||
let mut s = Selection::default();
|
||||
s.set(order);
|
||||
let c = cx(&d, &s, &p);
|
||||
let pressed = hit_anchor(&c, corner, c.point_tol()).map(|(id, ..)| id);
|
||||
assert_eq!(pressed, Some(front_path), "a press takes the front anchor (selected {order:?})");
|
||||
assert_eq!(hovered_anchor(&c, corner), Some((front_path, corner)), "the front anchor is highlighted (selected {order:?})");
|
||||
}
|
||||
}
|
||||
@@ -2917,14 +2917,15 @@ fn a_double_click_on_a_symbol_instance_edits_its_symbol() {
|
||||
|
||||
/// #4891 for the Selection tool: a press on a selected object's centre point (Attributes › Show
|
||||
/// Center) moves the selection, also where no art is painted (an unfilled shape), which the press
|
||||
/// would otherwise take for a marquee; anywhere else a press still starts one.
|
||||
/// would otherwise take for a marquee; anywhere else a press still starts one. With Object
|
||||
/// Selection by Path Only, so that the inside of the unfilled shape takes no press of its own.
|
||||
#[test]
|
||||
fn a_press_on_the_centre_point_moves_an_unfilled_shape() {
|
||||
let (d, id) = doc_with_live_rect();
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let c = ToolContext { path_only: true, ..cx(&d, &s, &p) };
|
||||
let centre = Point::new(150.0, 150.0);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move);
|
||||
|
||||
@@ -110,7 +110,11 @@ const ROWS: &[Row] = &[
|
||||
(&[crate::addons::extend_path::ID], None, &["mode"]),
|
||||
(&[crate::addons::corner_tool::ID], None, &["radius", "kind"]),
|
||||
(&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]),
|
||||
(&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
|
||||
(
|
||||
&[crate::addons::tangent_circle::ID],
|
||||
None,
|
||||
&["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides", "askRadius", "autoUpdateDefault"],
|
||||
),
|
||||
(&[crate::addons::smart_pen::ID], None, &["next"]),
|
||||
// The kind first: a new kind resets the values after it.
|
||||
(&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]),
|
||||
|
||||
@@ -34,6 +34,8 @@ pub(crate) struct Spec {
|
||||
pub(crate) struct AddonDialogs {
|
||||
open: Option<Open>,
|
||||
preview: LivePreview,
|
||||
/// The open Tangent Circle Tool radius dialog.
|
||||
pub(crate) tangent_radius: Option<super::pathtools::tangent_circle_radius::Open>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -105,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
/// by type: two hosted parameter dialogs would take each other's answers.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
|
||||
pump_commit(app);
|
||||
super::pathtools::tangent_circle_radius::pump(app, ctx);
|
||||
super::color::nearest::pump(app, ctx);
|
||||
super::select::pump(app, ctx);
|
||||
super::select::link_status::pump(app, ctx);
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected
|
||||
//! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values,
|
||||
//! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel
|
||||
//! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and
|
||||
//! `tool.setOption`.
|
||||
//! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog
|
||||
//! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius
|
||||
//! dialog draws its circle with `shape.circleThroughPoints`.
|
||||
|
||||
pub mod bridge;
|
||||
pub mod corner;
|
||||
@@ -13,6 +14,7 @@ pub mod set_corners;
|
||||
pub mod shape;
|
||||
pub mod shared_edge;
|
||||
pub mod tangent_circle;
|
||||
pub mod tangent_circle_radius;
|
||||
|
||||
use craft::behavior::ColumnWidth;
|
||||
use craft::menu::Node;
|
||||
@@ -317,6 +319,8 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec<Param> {
|
||||
Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))),
|
||||
Param::new("snapTolerance", tl!("Snap Tolerance"), snap).unit(UnitKind::Pixels),
|
||||
Param::new("snapWithoutGuides", tl!("Snap When Smart Guides Are Off"), ParamKind::bool(true)),
|
||||
Param::new("askRadius", tl!("Ask For Circle Radius"), ParamKind::bool(false)),
|
||||
Param::new("autoUpdateDefault", tl!("Auto-Update Default"), ParamKind::bool(false)),
|
||||
];
|
||||
}
|
||||
let (size, tolerance) = (anchor_eraser::SIZE_RANGE, anchor_eraser::TOLERANCE_RANGE);
|
||||
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user